'use strict';
import React from 'react'
import { connect }  from 'react-redux';

import {getStoreInfo,saveCommonInfo,getUserinfo,logout,hasNoSku,getTaskName} from "../../actions/common";
import {finishBoxRecovery,wrongShelf} from "../../actions/recovery";
import {getTroubleList,updateTroubleList} from "../../actions/getTroubles";
import {initGetOtherProblem,addNewProbem,deleteProblem,editProblemItem,submitProblemList} from "../../actions/otherQuestion"
import {scanBarCodeGetProductInfo,submitProductInfo,saveEditProductInfo,submitProductSuccess,clearProductSuccess} from "../../actions/ScanBarCode"
import {getReportDamageList,deleteDamageItem} from '../../actions/reportDamageList'
import {getRefreshImg,deleteImg,emptyImg} from "../../actions/refreshImg"
import {uploadError,addErrorInfo} from '../../actions/uploadError'
import PopupComponent from '../../components/CommonComponent/PopupComponent/PopupComponent'
import TroubleContainer from '../TroubleContainer/TroubleContainer'
import ScanBarCodeContainer from '../ScanBarCodeContainer/ScanBarCodeContaienr'
import ReportDamagesListContainer from '../ReportDamagesListContainer/ReportDamagesListContainer'
import OtherQuestionContainer from '../OtherQuestionContainer/OtherQuestionContainer'
import HomeContainer from '../HomeContainer/HomeContainer'
import FinishAskContainer from '../FinishAskContainer/FinishAskContainer'
import ChooseTaskContainer from '../ChooseTaskContainer/ChooseTaskContainer'
import Button from '../../components/CommonComponent/ButtonComponent/ButtonComponent';
import Clock from '../../components/CommonComponent/ClockComponent/ClockComponent';

/*二期引用 start*/
import HomePage from '../HomePageContainer/HomePageContainer'
import TakeStokeContainer from '../TakeStokeContainer/TakeStokeContainer'
import BreakageContainer from '../BreakageContainer/BreakageConatiner'
import RecoveryPage from '../RecoveryContainer/RecoveryContainer'
import ReplenishContainer from '../ReplenishContainer/ReplenishContainer'
import {getBarCodeProductInfo} from '../../actions/barcodeCommon'
import {getTaskInfo,getTaskList} from '../../actions/common'
/*二期引用 end*/

import {on,remove} from '../../util/event';

require('./index.css');

const showPage = CONFIG.showPage;

const headerStatus = CONFIG.headerStatus;


const defaultPopupInfo = {
        showPopup : false, //是否显示弹窗
        popupChild : null, // 自定义弹窗内部htmls,
        popupTitle : ''
    };
const initPage = 13;

const errorType = {
    1 : 1, //屏幕超时操作
    2 : 2, //确认完成任务超时
    3 : 3, //关门异常
};

class PageContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showPage : showPage[13],
            lastPage : '',
            page : null,
            popupInfo : defaultPopupInfo,
            showClock : false, //关门页面显示倒计时
            headerInfo : {},
            pageStyle : {},
            successCloseDoor : false,
            showClassify : false //显示右侧菜单栏，默认不显示,目前没用
        };
        this.getPages = this.getPages.bind(this); //获取当前页面
        this.showPopup = this.showPopup.bind(this); //显示弹窗
        this.hidePopup = this.hidePopup.bind(this); // 隐藏弹窗
        this.handleTouch = this.handleTouch.bind(this); //监听页面触碰
        this.beginCountBack = this.beginCountBack.bind(this); //开始300s倒计时
        this.endCountBack = this.endCountBack.bind(this); //结束300s倒计时
        this.showAlarm = this.showAlarm.bind(this); //显示警告弹窗
        this.beginCloseDoor = this.beginCloseDoor.bind(this); //开始关门倒计时
        this.playAlarmMusic = this.playAlarmMusic.bind(this); //播放警报音乐
        this.overTimeSolve = this.overTimeSolve.bind(this); //超时未完成
        this.failCloseDoor = this.failCloseDoor.bind(this); //关门倒数未监听到关门成功
        this.judgeDoorStatus = this.judgeDoorStatus.bind(this); //关门倒数判断门是否关闭
        this.getSocketMsg = this.getSocketMsg.bind(this); //获得socket信息
        this.changePages = this.changePages.bind(this); //改变当前页
        this.emptyUser = this.emptyUser.bind(this); //清空当前用户信息，关门结束或者关门超时人工处理
        this.dealPageByType = this.dealPageByType.bind(this); //根据用户type判断显示页面
        this.showTroublePage = this.showTroublePage.bind(this); //根据用户type判断显示页面
        this.showError = this.showError.bind(this); //展示错误信息
        this.hideError = this.hideError.bind(this); //隐藏错误信息
        this.getPageStyle = this.getPageStyle.bind(this); //
        this.uploadErrs = this.uploadErrs.bind(this); //
        /*以下是二期方法 start*/
        this.showHomePage = this.showHomePage.bind(this); //二期显示首页
        this.triggerAllClassify = this.triggerAllClassify.bind(this); //二期显示菜单栏
        this.showSecondTroubelPage = this.showSecondTroubelPage.bind(this); //根据用户的type判断显示的页面
        /*以下是二期方法 end*/


        this.maxCountBackTime = 300;
        this.count = 1000;
        this.countbackTimer = null;
        this.countBackTime = -1;


        this.taskTypeOption = {
            'ER': this.showTroublePage,
            'BH': this.showSecondTroubelPage
        };
    }

    getPageStyle(){
        let deviceWidth = window.innerWidth;
        let deviceHeight = window.innerHeight;
        let scaleX = deviceWidth / 1920;
        let scaleY = deviceHeight / 1080;
        let left = 1920 - deviceWidth;
        let top = 1080 * (1 - scaleX);
        let style = {
            'transform':`scale(${scaleX})`,
            'height': '945px',
            'width': '1920px'
        };
        this.setState({
            pageStyle : style
        })
    }


    componentWillMount() {
        this.getPageStyle();
        let that = this;
        let {dispatch} = this.props;
        on(CONFIG.socketType.GETSTOREINFO,this,function (data) {
            console.log("==GETSTOREINFO===")
            console.log(data);
            dispatch(saveCommonInfo({ip:data.ip}));
            dispatch(getStoreInfo(data.storeId));
        });
        on(CONFIG.socketType.GETSOCKETMSG,this,function (data) {
            console.log("==GETSTOREINFO===")
            console.log(data)
            that.getSocketMsg(data)
        })

    }


    emptyUser(){
        let {dispatch} = this.props;
        dispatch(logout());
    }

    getSocketMsg(data){
        let {dispatch,state} = this.props;
        switch (data.type){
            case 'SUCCESS_OPENDOOR':
                //执行开门
                let info = data.info;
                let commonInfo = state.commonInfo;
                console.log("SUCCESS_OPENDOOR " ,info);
                let {userinfo} = info;
                let datas = info.data;
                let {storeInfo} = commonInfo;
                console.log("========= ",userinfo,storeInfo)
                if(storeInfo && userinfo &&
                    storeInfo.id && userinfo.employeeId
                ){
                    dispatch(getUserinfo(userinfo.employeeId,storeInfo.id))
                }
                if(datas.area){
                    //区域信息
                    dispatch(saveCommonInfo(Object.assign({},{taskInfo:{area:datas.area}})))
                }

                this.setState({
                    successCloseDoor : false
                });
                break;
            case 'SUCCESS_CLOSEDOOR':
                //关门成功
                console.log("closedoor");
                dispatch(logout());
                this.endCountBack();
                // remove(CONFIG.socketType.GETSTOREINFO,this)
                // remove(CONFIG.socketType.GETSOCKETMSG,this)
                this.setState({
                    showPage : showPage[7],
                    showClock : false,
                    popupInfo : defaultPopupInfo,
                    successCloseDoor : true
                });
                break;
        }
    }

    componentDidMount(){
        // this.beginCountBack()
        let {dispatch} = this.props;
    }
    componentDidUpdate() {
    }
    componentWillReceiveProps(nextProps){
        let {state,dispatch} = nextProps;
        let userinfo = state.userInfo;
        let nowUserInfo = this.props.state.userInfo;
        let isNotOneUser = userinfo.employee && userinfo.employee.id &&
            (!nowUserInfo || !nowUserInfo.employee || (nowUserInfo.employee.id !== userinfo.employee.id));
        let isNotOneTask = userinfo.type && userinfo.type !== nowUserInfo.type;         

        if(isNotOneUser && isNotOneTask){
            //不是同一个用户，并且不是同一个任务
            this.dealPageByType(userinfo.type);
        }
        if(state.errMsg.errMsg){
            //有错误信息，弹出错误信息弹窗
            this.showError(state.errMsg.errMsg)
        }
        //根据后台数据控制该显示的页面 
        if(nextProps.state.commonInfo.taskInfo){
            let num=nextProps.state.commonInfo.taskInfo.currentTaskNum;
                switch(num){
                case 1 :
                this.changePages(CONFIG.showPage[5]);
                break;
                case 2 :
                this.changePages(CONFIG.showPage[6]);
                break;
                case 3 :
                this.changePages(CONFIG.showPage[10]);
                break;
                case 4 :
                this.changePages(CONFIG.showPage[11]);
                break;
            }
        }
    }
    componentWillUnmount(){
    }

    showError(errMsg){
        let className = errMsg.length > 24 ? 'popupExtClass' : '';
        let style = {'width':UTILPATH.getRemByPx(260)}
        let btnDom = <Button key={"pagecountBack1"} style={style} text={'确定'} option={this.hideError}/>;
        let showErrorDom = this.getPopDom({
            popupText : errMsg,
            popupButtons:[btnDom],
            classNames : className
        })

        this.showPopup({popupChild:showErrorDom})
    }

    hideError(){
        console.log("hideError");
        let {dispatch} = this.props;
        dispatch(addErrorInfo(""));
        this.hidePopup();
    }


    dealPageByType(type){
        let {dispatch,state} = this.props;
        if(this.taskTypeOption[type] && state.commonInfo){
            this.taskTypeOption[type](state.commonInfo);
        }
    }

    showTroublePage(info){
        let {dispatch} = this.props;
        dispatch(getTroubleList(info))
        this.setState({
            showPage : showPage[1]
        },()=>{
            this.beginCountBack();
        });
    }
    showSecondTroubelPage(info){
    //    let {dispatch} =this.props;
    this.setState({
        showPage : showPage[13]
    })
    }
    changePages(page){
        console.log("changePages : ",page);
        this.setState({
            showPage : page,
            popupInfo : defaultPopupInfo
        })
    }

    //开始倒计时,看有没有操作，只是在整个开门过程中才监听

    beginCountBack(){
        this.countBackTime = this.maxCountBackTime;
        clearTimeout(this.countbackTimer);
        this.countbackTimer = null;
        this.countBack.bind(this)();
    }

    endCountBack(){
        console.log("endCountBack")
        this.countBackTime = -1;
        clearTimeout(this.countbackTimer);
        this.countbackTimer = null;
    }

    overTimeSolve(){
        //300s 无人操作，点击确定
        this.setState({
            popupInfo : defaultPopupInfo
        },()=>{
            this.beginCountBack()
        })
    }

    countBack(){
        console.log("countbackTimer ",this.countbackTimer,)
        if(!this.countbackTimer && this.countBackTime >= 0){
            this.countBackTime--;
            this.countbackTimer = window.setTimeout(()=>{
                if(this.countBackTime > 0){
                    clearTimeout(this.countbackTimer);
                    this.countbackTimer = null;
                    this.countBack();
                }else{
                    //超过300s未点击，进入异常状态
                    clearTimeout(this.countbackTimer);
                    this.countbackTimer = null;
                    let btnWidth = UTILPATH.getRemByPx(260);
                    let btnMarginLeft = UTILPATH.getRemByPx(30);
                    let btnBorderRadius = UTILPATH.getRemByPx(10);
                    let btnDom = <Button key={"pagecountBack1"} style={{'width':btnWidth}} text={"确定"} option={this.overTimeSolve}/>
                    let clockDom = <Clock key={"pagecountBack2"} totalTime={60}
                                          style={{'width':btnWidth,'marginLeft':btnMarginLeft,'borderRadius':btnBorderRadius}}
                                          callback={this.showAlarm}
                    />;
                    let countBackDom = this.getPopDom({
                        popupText : '您是否还在店铺准备执行您的任务',
                        popupButtons:[btnDom,clockDom]
                    })
                    this.showPopup({popupChild:countBackDom})
                }
            },this.count);
        }

    }

    uploadErrs(type){
        let {dispatch,state} = this.props;
        dispatch(uploadError(Object.assign({},state.commonInfo,{exceptionType:type})));
    }


    getPopDom(info){
        let {text='',popupButtons=[],style={}} = info
        let dom = popupButtons.map((a,k)=>{
            return a;
        });
        return <div className={"defaultPopup col333"} style={style}>
            <div className={"defaultPopupText font30"}>
                {text}
            </div>
            <div className={"defaultPopupButtons font32"}>
                {dom}
            </div>
        </div>
    }


    //弹出警告弹窗，并报警
    showAlarm(){
        console.log("showAlarm");

        //屏幕超过300s无人操作
        this.uploadErrs(errorType[1])
        let btnWidth = UTILPATH.getRemByPx(260);
        let btnMarginLeft = UTILPATH.getRemByPx(30);
        let btnBorderRadius = UTILPATH.getRemByPx(10);
        let btnDom = <Button key={"pagecountBack1"} style={{'width':btnWidth}} text={"确定"} option={this.beginCloseDoor}/>
        let clockDom = <Clock key={"pagecountBack2"} totalTime={30}
                              style={{'width':btnWidth,'marginLeft':btnMarginLeft,'borderRadius':btnBorderRadius}}
                              callback={this.beginCloseDoor}
        />;
        let showAlarmDom = this.getPopDom({
            popupText : '检测到店铺反常，请站出店铺，关闭店铺门后重新验证您的身份',
            popupButtons:[btnDom,clockDom]
        });
        this.setState({
            popupInfo : defaultPopupInfo
        },()=>{
            this.showPopup({popupChild:showAlarmDom});
            this.playAlarmMusic()
        })

    }

    //关门
    beginCloseDoor(){
        console.log("beginCloseDoor");
        let btnWidth = UTILPATH.getRemByPx(260);
        let btnMarginLeft = UTILPATH.getRemByPx(30);
        let btnBorderRadius = UTILPATH.getRemByPx(10);
        this.setState({
            popupInfo:defaultPopupInfo
        },()=>{
            let clockDom = <Clock key={"pagecountBack2"} totalTime={30}
                                  style={{'width':btnWidth,'marginLeft':btnMarginLeft,'borderRadius':btnBorderRadius}}
                                  text={"关门中"}
                                  callback={this.judgeDoorStatus}
            />;
            let beginCloseDoorDom = this.getPopDom({
                popupText : '关门倒数，请尽快站到设备外关闭设备门',
                popupButtons:[clockDom]
            });
            this.showPopup({popupChild:beginCloseDoorDom})
        })

    }

    closeDoor(){

    }

    failCloseDoor(){
        this.playAlarmMusic();
        this.uploadErrs(errorType[3]);
    }

    judgeDoorStatus(){
        //成功关门
        //关门失败
        // this.emptyUser();
        // this.failCloseDoor()
        if(!this.state.successCloseDoor){
            //关门失败，上传警报
            this.failCloseDoor();
        }
    }

    playAlarmMusic(){
        //播放警报音乐
        console.log("playMusic");
        let music = this.refs.audioplay;
        if(music){
            music.play();
        }
    }

    hidePopup(){
        if(this.state.popupInfo.showPopup){
            this.setState({
                popupInfo : defaultPopupInfo
            })
        }

    }
    showPopup(info){
        let popupInfo = Object.assign({},defaultPopupInfo,info);
        if(info.popupChild){
            popupInfo.showPopup = true; //以防未设置显示弹窗，做此判断。
        }
        this.setState({
            popupInfo : popupInfo,
        })
    }


    showOpenDoorPage(){
        console.log("showOpenDoorPage")
        this.setState({
            showPage : showPage[initPage],
            showClock : true
        })
    }

    showHomePage(){
        this.setState({
            showPage : showPage[13]
        });
    }
    triggerAllClassify(status=false){
        this.setState({
            showAllClassify : status
        })
    }

    getPages(){
        let pages = null;
        let{state,dispatch} = this.props;
        switch (this.state.showPage){
            case showPage[1]:
                pages = <TroubleContainer
                    troubleList={state.troubleList}
                    refreshImg = {state.refreshImg}
                    storeInfo={state.commonInfo.storeInfo}
                    userInfo={state.userInfo}
                    initTroubleList={(info)=>dispatch(getTroubleList(info))}
                    showTextArea={(text)=>this.showTextArea(text)}
                    showPopup={(info)=>this.showPopup(info)}
                    hidePopup={()=>this.hidePopup()}
                    changePages={(pageIndex)=>this.changePages(pageIndex)}
                    getRefreshImg={(errorId,type)=>dispatch(getRefreshImg(errorId,type))}
                    deleteImg={(errorId,type,fileId)=>dispatch(deleteImg(errorId,type,fileId))}
                    updateTroubleList={(info)=>dispatch(updateTroubleList(info,state.headerInfo))}
                    emptyImg={()=>dispatch(emptyImg())}
                />;
                break;
            case showPage[2]:
                pages = <ScanBarCodeContainer
                            headerInfo = {state.commonInfo}
                            storeInfo={state.storeInfo}
                            userInfo={state.userInfo}
                            getProductInfo = {(postData)=>dispatch(scanBarCodeGetProductInfo(postData))}
                            submitProductInfo = {(postData)=>dispatch(submitProductInfo(postData))}
                            getRefreshImg={(errorId,type)=>dispatch(getRefreshImg(errorId,type))}
                            deleteImg={(errorId,type,fileId)=>dispatch(deleteImg(errorId,type,fileId))}
                            saveEditProductInfo = {(postData)=>dispatch(saveEditProductInfo(postData))}
                            changePages={(data)=>this.changePages(data)}
                            submitProductSuccess = {(postData)=>dispatch(submitProductSuccess(postData))}
                            clearProductSuccess = {()=>dispatch(clearProductSuccess())}
                            state = {state}
                />;
                break;
            case showPage[3]:
                pages = <ReportDamagesListContainer
                            getReportDamageList = {(postData)=>dispatch(getReportDamageList(postData))}
                            deleteDamageItem = {(postData)=>{dispatch(deleteDamageItem(postData))}}
                            changePages={(data)=>this.changePages(data)}
                            headerInfo = {state.commonInfo}
                            storeInfo={state.storeInfo}
                            userInfo={state.userInfo}
                            state = {state}
                            showPopup={(info)=>this.showPopup(info)}
                            hidePopup={()=>this.hidePopup()}
                />;
                break;
            case showPage[4]:
                pages = <OtherQuestionContainer
                            initStart = {(postData)=>dispatch(initGetOtherProblem(postData))}
                            addNewProblem = {(postData)=>dispatch(addNewProbem(postData))}
                            editProblemItem = {(data)=>dispatch(editProblemItem(data))}
                            deleteProblem = {(data)=>dispatch(deleteProblem(data))}
                            submitProblemList = {(data)=>dispatch(submitProblemList(data))}
                            getRefreshImg={(errorId,type)=>dispatch(getRefreshImg(errorId,type))}
                            deleteImg={(errorId,type,fileId)=>dispatch(deleteImg(errorId,type,fileId))}
                            changePages={(data)=>this.changePages(data)}
                            headerInfo = {state.commonInfo}
                            storeInfo={state.storeInfo}
                            userInfo={state.userInfo}
                            state = {state}
                            showPopup={(info)=>this.showPopup(info)}
                            hidePopup={()=>this.hidePopup()}
                        />;
                break;
            case showPage[7]:
                pages = <HomeContainer showClock={this.state.showClock} storeInfo={state.storeInfo}
                                       userInfo={state.userInfo}
                                       judgeDoorStatus={this.judgeDoorStatus}
                />;
                break;
            case showPage[8]:
                pages = <FinishAskContainer storeInfo={state.storeInfo}
                                            userInfo={state.userInfo}
                                            endCountBack={this.endCountBack}
                                            changePages={(data)=>this.changePages(data)}
                                            showOpenDoorPage={()=>this.showOpenDoorPage.bind(this)()}
                                            showPopup={(info)=>this.showPopup(info)}
                                            uploadErrs={(type)=>this.uploadErrs(type)}
                                            hidePopup={()=>this.hidePopup()}
                />;
                break;
            case showPage[9]:
                pages = <ChooseTaskContainer storeInfo={state.storeInfo}
                                             userInfo={state.userInfo}
                                             changePages={(data)=>this.changePages(data)}
                                             showOpenDoorPage={()=>this.showOpenDoorPage.bind(this)()}
                                             hidePopup={()=>this.hidePopup()}
                />;
                break;
            /*以下是二期页面 start*/
            case showPage[13]:
                pages = <HomePage headerInfo={state.commonInfo}
                                  startTask={()=>{dispatch(getTaskInfo(state.commonInfo))}}
                                  changePages={(data)=>this.changePages(data)}
                                   />;
                break;
            case showPage[6]:
                pages = <TakeStokeContainer headerInfo = {state.commonInfo}
                                            showPopup={(info)=>this.showPopup(info)}
                                            hidePopup={()=>this.hidePopup()}
                />;
                break;
            case showPage[5]:
                pages = <BreakageContainer
                                 pullTaskList={()=>{dispatch(hasNoSku(state.commonInfo))}}
                                 headerInfo={state.commonInfo}
                                 getBarCodeProductInfo={(barcode)=>{dispatch(getBarCodeProductInfo({barcode,commonInfo:state.commonInfo}))}}
                                 breakageProductInfo={state.barcodeCommon}
                                 />;
                break;
            case showPage[10]:
                pages = <RecoveryPage
                        headerInfo = {state.commonInfo}
                        showPopup={(info)=>this.showPopup(info)}
                        hidePopup={()=>this.hidePopup()}
                        getTaskName={()=>dispatch(getTaskName(3,2))}
                        finishBoxRecovery={()=>dispatch(finishBoxRecovery())}
                        wrongShelf={()=>dispatch(wrongShelf())}
                />;
                break;
            case showPage[11]:
                pages = <ReplenishContainer
                    headerInfo = {state.commonInfo}
                    showPopup={(info)=>this.showPopup(info)}
                    hidePopup={()=>this.hidePopup()}
                />
            /*以下是二期页面 end*/
        }
        return pages;
    }
    


    handleTouch(){
        console.log("handleTouch");
        this.countBackTime = this.maxCountBackTime;
    }

    render() {
        let {state} = this.props;
        let headerInfo = state.commonInfo;
        let ip = headerInfo ? headerInfo.ip : '';
        let mp3Url = ip ? `http://${ip}:7788/defaultMedia/back.mp3` : '';
        return (
            <div className={"pageContainer "} onTouchStart={()=>this.handleTouch()}>
                {
                    mp3Url ? <audio
                        src={mp3Url}
                        preload="true"
                        controls={false}
                        ref={"audioplay"}
                        loop={false}
                    /> : null
                }
                <PopupComponent popupInfo={this.state.popupInfo} />
                {this.getPages()}
            </div>
        )
    }
}

function select(store) {
    return Object.assign({}, {state: store})
}

export default connect(select)(PageContainer)