'use strict';
import React from 'react'
import { connect }  from 'react-redux';
import PropTypes from 'prop-types'
import ReactQrCode from 'qrcode.react'

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,timeoutAlarm} 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 BoxRecoveryPage from '../BoxRecoveryContainer/BoxRecoveryContainer'
import ReplenishContainer from '../ReplenishContainer/ReplenishContainer'
import QuestionContainer from '../QuestionContainer/QuestionContainer'
import {getBarCodeProductInfo,saveProductInfo} from '../../actions/barcodeCommon'
import {getTaskList, askForNextTask, emptyStoreInfo} from '../../actions/common'
import {submitBreakageProduct,hasNoSku} from '../../actions/breakaegContainer'
import {checkProductQuantity} from '../../actions/TokeStokeContainer'
import {getStoreInfo,saveCommonInfo,getUserinfo,logout,getTaskName,fetchStoreInfo,fetchStoreDoorStatus} from "../../actions/common";
import {finishBoxRecovery} from "../../actions/recovery";
import replenishAction from "../../actions/replenish";
import {getStoreList,listStores} from "../../actions/getStore";
import {pollingGetUserinfo} from "../../actions/userinfo";
import AllClassify from '../AllClassifyContainer/AllClassifyContainer'
import {willCloseDoor,closeDoorSuccess} from '../../actions/chooseTaskContainer'
import {sendMsg} from '../../util/socket'
import PopModel from '../../components/CommonComponent/PopupComponent/PopupChildComponent'
import WeChatUtil from '../../util/WeChatUtil'
import DevPage from '../DevPage/DevPage'
/*二期引用 end*/
/**引用测试数据*/
import testTakeStoreData from '../../../testData/takeStore.json'
import testBreakData from '../../../testData/breakData.json'
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[initPage], // 当前显示页面
            lastPage : '', // 暂时没用
            page : null, // 暂时没用
            popupInfo : defaultPopupInfo, // 弹窗信息
            showClock : false, //关门页面显示倒计时
            headerInfo : {}, // 暂时没用
            pageStyle : {}, // 页面样式
            successCloseDoor : false, //关门成功标识
            showClassify : false, //显示右侧菜单栏，默认不显示,目前没用
            isSend:false, // 关门之后设置为true，当其为true的时候才会接口 关门的socket消息
            area:'',//区域
            maxTime : 300, // 超时时间
            showAlarm : false, // 是否已报警，已报警为true，未报警为false
            startStopServer : false, //开启断电断网流程
            storeValue : "", // 断网情况下的 门店id
            startWork : false, //断网情况下 开始工作标识（暂未用到）
            startCountback : false, // 开始超时倒计时标识
            showSelectStore: 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.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.toggleOrders = this.toggleOrders.bind(this); //二期显示菜单栏
        this.goBackTask = this.goBackTask.bind(this); //二期显示菜单栏
        this.showSecondTroubelPage = this.showSecondTroubelPage.bind(this); //根据用户的type判断显示的页面
        this.handleCloseDoor = this.handleCloseDoor.bind(this); //监听到关门回调
        this.showStoreListPop = this.showStoreListPop.bind(this); //展示门店列表窗口
        this.handleStoreChange = this.handleStoreChange.bind(this); //监听门店切换
        this.handleChooseStore = this.handleChooseStore.bind(this); //监听门店切换
        this.handleSelectStore = this.handleSelectStore.bind(this); //选择新的门店
        this.showQrcodePop = this.showQrcodePop.bind(this); //展示扫码开门二维码弹窗
        this.startWork = this.startWork.bind(this); //展示扫码开门二维码弹窗
        this.changeStore = this.changeStore.bind(this);//radio选择store
        /*以下是二期方法 end*/


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


        this.taskTypeOption = {
            'FIRST': this.showTroublePage,
            'SECOND': 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;
        if(WeChatUtil.getUrlParam().type){
            this.switchPages(WeChatUtil.getUrlParam().type)
        }
        /**
         * 测试数据
         * @type {number}

         let employeeId = 14;
         let area = "B";
         let storeId = 50;
         let maxTime = 300;
         dispatch(getStoreInfo(storeId));
         dispatch(saveCommonInfo({userInfo:{employeeId}}));
         dispatch(getUserinfo(employeeId,storeId));
         dispatch(saveCommonInfo(Object.assign({},{taskInfo:{area:area,taskId:0,currentTaskType:'OPEN'}})));
         if(!this.state.startCountback){
                    this.setState({
                        successCloseDoor : false,
                        area:area,
                        showAlarm : false,
                        maxTime : maxTime,
                        startCountback : true
                    },()=>{
                        //开门开始倒计时
                        this.countBackTime = maxTime;
                        this.beginCountBack()
                    });
                }

         */
        on(CONFIG.socketType.GETSTOREINFO,this,function (data) {
            //socket接收到门店id
            UTILPATH.myLogger.info(CONFIG.socketType.GETSTOREINFO ,data);
            dispatch(saveCommonInfo({ip:data.ip}));
            if(!this.state.startStopServer){
                //非断电断网模式
                dispatch(getStoreInfo(data.storeId));
                //通过地址栏信息判断是否显示测试数据
                if(WeChatUtil.getUrlParam().type && WeChatUtil.getUrlParam().type === 'info' ){
                    let employeeId = WeChatUtil.getUrlParam().employ;
                    let area = WeChatUtil.getUrlParam().area;
                    dispatch(saveCommonInfo({userInfo:{employeeId}}));
                    dispatch(getUserinfo(employeeId,data.storeId));
                    dispatch(saveCommonInfo(Object.assign({},{taskInfo:{area:area,taskId:0,currentTaskType:'OPEN'}})));
                    if(!this.state.startCountback){
                        this.setState({
                            successCloseDoor : false,
                            area:area,
                            showAlarm : false,
                            maxTime : maxTime,
                            startCountback : true
                        },()=>{
                            //开门开始倒计时
                            this.countBackTime = maxTime;
                            this.beginCountBack()
                        });
                    }
                }
            }
        });
        on(CONFIG.socketType.GETSOCKETMSG,this,function (data) {
            // 接收到 socket信息
            UTILPATH.myLogger.info(CONFIG.socketType.GETSOCKETMSG ,data);
            if(!this.state.startStopServer){
                //非断电断网模式
                that.getSocketMsg(data)
            }
        });
        on(CONFIG.socketType.STARTSTOPSERVER,this,()=>{
            // 接收到断网指令
            UTILPATH.myLogger.info(CONFIG.socketType.STARTSTOPSERVER);
            if(!this.state.startStopServer){
                this.setState({
                    startStopServer : true
                },()=>{
                    //获取门店列表
                    dispatch(emptyStoreInfo());
                    dispatch(getStoreList());
                })
            }
        });
        on(CONFIG.customEvent.STORELISTREADY, this, (data)=>{
            console.log('storelistready')
            const that = this;
            if(!this.state.showSelectStore){
                this.setState({
                    showSelectStore : true
                },()=>{
                    that.showStoreSelectPop(data);
                })
            }
        })
        on(CONFIG.customEvent.STOREINFOREADY, this, ()=>{
            const that = this;
            that.startWork();
        })

        on(CONFIG.customEvent.GETDOORSTATUSREADY,this,(data)=>{
            //门状态接收成功
            console.log("door status received ",data);
            console.log(data)
            let area = this.props.state.commonInfo.taskInfo.area;
            let storeId = this.props.state.commonInfo.storeInfo.id;
            console.log('ccccccccccccc0', area)
            console.log('ccccccccccc1',this.state, this.props)
            console.log(setTimeout, this.handleCloseDoor, this.getStoreDoorStatus)
            if(area==="A"){
                console.log('hihihihihiaaaaaaaaa')
                if(data.aDoor === 1){
                    console.log('hihihihihiaaaaaaaaaclose')
                    this.handleCloseDoor()
                }else{
                    console.log('hihihihihiaaaaaaaaatimeout')
                    window.setTimeout(()=>{this.getStoreDoorStatus(storeId)}, 3000)
                }
            }else if(area==="B"){
                console.log('hihihihihibbbbbbbbbb')
                if(data.bDoor === 1){
                    console.log('hihihihihibbbbbbbbbbbbclose')
                    this.handleCloseDoor()
                }else{
                    console.log('hihihihihibbbbbbbbbbtimeout')
                    window.setTimeout(()=>{this.getStoreDoorStatus(storeId)}, 3000)
                }
            }

        })

        on(CONFIG.socketType.STOPSTOPSERVER,this,()=>{
            // 接收到终止断网指令（即联网成功）
            UTILPATH.myLogger.info("componentWillMount " ,CONFIG.socketType.STOPSTOPSERVER);
            if(this.state.startStopServer){
                this.setState({
                    startStopServer : false
                },()=>{
                    this.hidePopup()
                })
            }
        })

    }


    emptyUser(){
        let {dispatch} = this.props;
        dispatch(logout());
    }
      //判断是否向monitor发起获取货柜门状态请求，点击关门按钮后获取
    changeIsSend(bool){
        this.setState({
            isSend:bool
        })
    }
    // 根据socket信息，执行开门关门相关逻辑
    getSocketMsg(data){
        let {dispatch,state} = this.props;
        let {isSend , area} = this.state;
        switch (data.type){
            case 'SUCCESS_OPENDOOR':
                //执行开门
                let info = data.info;
                let commonInfo = state.commonInfo;
                let {userinfo} = info;
                let datas = info.data;
                let {storeInfo} = commonInfo;
                if(storeInfo && userinfo &&
                    storeInfo.id && userinfo.employeeId
                ){
                    dispatch(saveCommonInfo({userInfo:{employeeId:userinfo.employeeId}}));
                    dispatch(getUserinfo(userinfo.employeeId,storeInfo.id))
                }
                if(info.area){
                    //区域信息
                    dispatch(saveCommonInfo(Object.assign({},{taskInfo:{area:info.area,taskId:0,currentTaskType:'OPEN'}})))
                }

                let maxTime = this.maxCountBackTime;

                if(parseInt(info.maxTime)){
                    maxTime = parseInt(info.maxTime);
                }
                if(!this.state.startCountback){
                    this.setState({
                        successCloseDoor : false,
                        area:info.area,
                        showAlarm : false,
                        maxTime : maxTime,
                        startCountback : true
                    },()=>{
                        //开门开始倒计时
                        this.countBackTime = maxTime;
                        this.beginCountBack()
                    });
                }
                break;
            case 'RESPONSE_ATTACHMENT_STATUS':
                UTILPATH.myLogger.info("RESPONSE_ATTACHMENT_STATUS isSend ",isSend);
                UTILPATH.myLogger.info("RESPONSE_ATTACHMENT_STATUS area ",area);
                if(isSend){
                    let {info={}} = data;
                    let {left_door=0,right_door=0} = info;
                    left_door = parseInt(left_door);
                    right_door = parseInt(right_door);
                    if(area==="A"){
                        if(left_door === 1){
                            this.handleCloseDoor()
                        }else{
                            sendMsg(JSON.stringify({type:'WILL_CLOSEDOOR'}))
                        }
                    }else if(area==="B"){
                        if(right_door === 1){
                            this.handleCloseDoor()
                        }else{
                            sendMsg(JSON.stringify({type:'WILL_CLOSEDOOR'}))
                        }
                    }
                }

                break;
        }
    }


    handleCloseDoor(){
        let {dispatch,state} = this.props;
        let {commonInfo={}} = state;
        UTILPATH.myLogger.info("handleCloseDoor commonInfo ",commonInfo);
        this.setState({
            showPage : showPage[initPage],
            showClock : false,
            showAlarm : false,
            popupInfo : defaultPopupInfo,
            successCloseDoor : true,
            isSend:false
        },()=>{
            this.endCountBack();
            dispatch(closeDoorSuccess(commonInfo,this.state.startStopServer));

        });
    }

    componentDidMount(){
    }
    componentDidUpdate() {
    }

    //判断要显示的页面的函数

    switchPages (type) {
        switch (type) {
            case 'LR' : //遗留上报
                this.changePages(CONFIG.showPage[5]);
                break;
            case 'CK' : // 盘点
            case 'CR' : // 盘点
                this.changePages(CONFIG.showPage[6]);
                break;
            case 'RE' : // 回收
                this.changePages(CONFIG.showPage[10]);
                break;
            case 'ADDR' : // 补货
                this.changePages(CONFIG.showPage[11]);
                break;
            case 'PF' : // 问题反馈
                this.changePages(CONFIG.showPage[14]);
                break;
            case 'ER' : // 故障处理
                this.changePages(CONFIG.showPage[12]);
                break;
            case 'REA' : // 回收箱回收
                this.changePages(CONFIG.showPage[15]);
                break;
            case 'FINISH' : // 任务完成，关门页面
                this.changePages(CONFIG.showPage[131]);
                break;
            default:
                this.changePages(CONFIG.showPage[13]);
                break;
        }
    }
    componentWillReceiveProps(nextProps){
        let {state,dispatch} = nextProps;
        let nextCommonInfo = state.commonInfo;
        let nextUserInfo = nextCommonInfo.userInfo || {};
        let nextStoreInfo = nextCommonInfo.storeInfo || {};
        let nextTaskInfo = nextCommonInfo.taskInfo || {};
        let nextStoreId = nextStoreInfo.id || 0;
        let nextUserId = nextUserInfo.id || "";
        let nextEmployeeId = nextUserInfo.employeeId || 0;
        let nextArea = nextTaskInfo.area || "";
        let storeList = state.storeInfo && state.storeInfo.storeList ? state.storeInfo.storeList : [];
        console.log('zzzzz5',nextUserInfo, nextTaskInfo)
        if(nextUserInfo && nextUserInfo.taskType && nextUserInfo.id) {
            let commonInfo = this.props.state.commonInfo;
            let {userInfo={},taskInfo={}} = commonInfo;
            if(!userInfo || !userInfo.taskType || !userInfo.id || (
                userInfo.id !== nextUserInfo.id || (userInfo.employeeId !== nextUserInfo.employeeId)
            ) || (
                userInfo.taskType !== nextUserInfo.taskType
            )){
                //如果不是同一个用户或者不是同一个任务，会再次进入
                this.dealPageByType(nextUserInfo.taskType);
            }

            //补货人员，根据type判断显示页面

            let lastCurrentType = taskInfo.currentTaskType || '';


            if(nextUserInfo.taskType === "SECOND" && nextTaskInfo && nextTaskInfo.currentTaskType &&
                nextTaskInfo.currentTaskType !== lastCurrentType && lastCurrentType !== 'FINISH'
            ){
               this.switchPages(nextTaskInfo.currentTaskType)
            }

        }else if(!nextUserInfo.employeeId && this.state.showPage !== showPage[initPage]&& !WeChatUtil.getUrlParam().type){
            this.setState({
                showPage : showPage[initPage]
            })
        }

        if(this.state.startStopServer){
            UTILPATH.myLogger.info("=====startStopServer======= ",this.state.startStopServer,this.state.startWork)
            if(storeList && storeList.length > 0 && !nextStoreId ){
                //断电断网，有门店列表，没有门店信息，弹出门店弹窗
                this.setState({
                    storeValue : storeList[0].id
                },()=>{
                    this.showStoreListPop(storeList);
                })
            }else if(nextStoreId && !nextEmployeeId){
                //todo 不应该判断区域，但是后台会在获取一次用户信息后就清空用户数据，所以加了区域的判断，这个地方要改一下
                //断电断网，有门店信息，但是没有用户信息，弹出扫描用户二维码的弹窗
                this.showQrcodePop(nextStoreId);
            }else if(nextStoreId && nextUserInfo && nextEmployeeId && nextArea){
                UTILPATH.myLogger.info("=====startStopServer===hasEverything==== ",this.state.startCountback)
                if(!this.state.startCountback){
                    this.setState({
                        successCloseDoor : false,
                        area:nextArea,
                        showAlarm : false,
                        maxTime : this.maxCountBackTime,
                        startCountback : true
                    },()=>{
                        //开门开始倒计时
                        this.countBackTime = this.maxCountBackTime;
                        this.beginCountBack();
                        this.hidePopup();
                    });
                }
            }
        }

        if(state.errMsg && state.errMsg.errMsg){
            //有错误信息，弹出错误信息弹窗
            this.showError(state.errMsg.errMsg)
        }
    }
    componentWillUnmount(){
    }

    showStoreSelect(){
        console.log('in show store select')
        let {dispatch} = this.props;
        console.log(dispatch, listStores)
        dispatch(listStores())
        // let {dispatch} = this.props;
        // console.log('kkkkkkkkk')
        // dispatch(listStores()).then(()=>{
        //     console.log('vvvvvvvvv');
        // })
        // let storeList = this.state.storeInfo && this.state.storeInfo.storeList ? this.state.storeInfo.storeList : [];
        //
        // this.setState({
        //     showSelectStore: true},()=>{
        //         this.showStoreListPop(storeList);
        // }
        // )
    }
    getStoreDoorStatus(storeId){

        console.log("in getStoreDoorStatus")
        if(!storeId){
            storeId = this.props.state.commonInfo.storeInfo.id
        }

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

        this.showPopup({popupChild:showErrorDom})
    }

    hideError(){
        let {dispatch} = this.props;
        console.log("in hideerror",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){
        this.setState({
            showPage : page,
            popupInfo : defaultPopupInfo
        })
    }

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

    beginCountBack(){
        if(this.countbackTimer){
            clearTimeout(this.countbackTimer);
            this.countbackTimer = null;
        }
        if(!this.countbackTimer){
            this.setState({
                showAlarm : false
            },()=>{
                this.countBackTime = this.state.maxTime;
                this.countBack.bind(this)();
            })

        }
    }

    endCountBack(){
        if(this.state.startCountback){
            this.setState({
                startCountback : false
            });
        }
        this.countBackTime = -1;
        if(this.countbackTimer){
            clearTimeout(this.countbackTimer);
        }
        this.countbackTimer = null;
        UTILPATH.myLogger.info("endCountBack countBackTime ",this.countBackTime);
    }

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

    countBack(){
        // UTILPATH.myLogger.info("countBack countBackTime ",this.countBackTime);
        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 border = "2px solid #e5e5e5";
                    let btnDom = <Button key={"pagecountBack1"} style={{'width':btnWidth,'border':border}} 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(){
        let {dispatch,state} = this.props;
        let {commonInfo={}} = state;
        dispatch(timeoutAlarm(commonInfo));
    }


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


    //弹出警告弹窗，并报警
    showAlarm(){
        //屏幕超过300s无人操作

        //TODO 上报300s无人操作
        this.uploadErrs();

        this.setState({
            showAlarm : true,
            popupInfo : defaultPopupInfo
        },()=>{
            this.playAlarmMusic() //播放音乐，暂未实现
        })
    }
    // 关门失败（一期逻辑，现未使用）
    failCloseDoor(){
        this.playAlarmMusic();
        this.uploadErrs();
    }
    // 判断关门状态（一期逻辑，现未使用）
    judgeDoorStatus(){
        this.setState({
            showPage : showPage[initPage],
            popupInfo : defaultPopupInfo,
        },()=>{
            if(!this.state.successCloseDoor){
                //关门失败，上传警报
                this.failCloseDoor();
            }
        });
    }

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

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

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


    showOpenDoorPage(){
        this.setState({
            showPage : showPage[7],
            showClock : true
        })
    }

    showHomePage(){
        this.setState({
            showPage : showPage[13]
        });
    }

    //二期临时退出（不考虑现实物理门，直接告诉服务器门已关）
    tempLogout(){
        this.handleCloseDoor()
    }

    /**
     * 显示右侧弹出菜单（暂未用）
     * @returns {*}
     */
    toggleOrders(page=0){
        let {state} = this.props;
        let {commonInfo={}} = state;
        let {userInfo={},storeInfo={}} = commonInfo;
        this.setState({
            showClassify : !this.state.showClassify
        },()=>{

            if(page){
               if(userInfo.employeeId && storeInfo.id){
                   this.changePages(CONFIG.showPage[page]);
               } else{
                   this.showError("没有用户信息或门店信息 ip:"+commonInfo.ip+" storeId:"+(commonInfo.storeInfo ? commonInfo.storeInfo.id : 0));
               }
            }else{

            }
        })


    }
    // 断网模式，在门店列表页，监听门店切换
    handleStoreChange(e){
        this.setState({
            storeValue : e.target.value
        })
    }
    // 断网模式，监听选择门店，获取门店信息
    handleChooseStore(){
        const {dispatch, state} = this.props;
        let storeId = this.state.storeValue;
        if(!storeId){
            storeId = state.storeInfo.storeList[0].id
        }
        dispatch(getStoreInfo(storeId));
    }
    // 门店选择后获取门店信息及开门用户信息
    handleSelectStore(){
        const {dispatch, state} = this.props;
        let storeId = this.state.storeValue;
        if(!storeId){
            storeId = state.storeInfo.storeList[0].id
        }
        dispatch(fetchStoreInfo(storeId));
        this.hidePopup();
    }
    changeStore(e){
        console.log("change storeid to:", e.target.value);
        this.setState({
            storeValue : e.target.value
        })
    }
    // 选择门店拉取任务
    showStoreSelectPop(data){
        let {state} = this.props;
        let storeList = state.storeInfo && state.storeInfo.storeList ? state.storeInfo.storeList : [];
        if(!storeList || storeList.length==0){
            storeList = data
        }
        if(storeList && storeList.length > 0){
            let storeDom = storeList.map((store,index)=>{
                return <span key={"storeListPop"+index}>
                    <label style={{"width":"200px","textAlign":"left","marginBottom":UTILPATH.getRemByPx(10)}}>
                        <input className="radio_type" type="radio" id={"storeRadio"+store.id} name="storeRadio" value = {store.id}
                        defaultChecked={index==0?true:false} />
                    {store.name}</label></span>
            });
            let btnWidth = UTILPATH.getRemByPx(240);
            let btnMiddle = UTILPATH.getRemByPx(40)
            let border = "2px solid #e5e5e5"
            let btnDom = <Button key={"showStoreListBtn"} style={{'width':btnWidth,'border':border,'marginRight':btnMiddle,'display':'inline-block'}} text={"确定"} option={this.handleSelectStore}/>
            let cancelBtnDom = <Button key={"cancelStoreListBtn"} style={{'width':btnWidth,'border':border,'display':'inline-block'}} text={"取消"} option={this.hidePopup}/>
            let dom = <PopModel popupTitle={"门店任务拉取"} classContainer={"recoveryPopInfo"}>
                <div className={"font36"} style={{paddingTop:'2%', paddingBottom:'6%', height:'4.5rem', overflowY: 'auto'}}>
                    <div className={"font"} style={{"marginBottom":UTILPATH.getRemByPx(40)}}>请选择当前门店 </div>
                    {/*<RadioGroup onChange={this.onGroupe.bChangind(this)} active={this.state.active}>*/}
                    {/*    <Radio value={1}>使用余额支付</Radio>*/}
                    {/*    <Radio value={2}>使用微信支付</Radio>*/}
                    {/*</RadioGroup>*/}
                    <div style={{'width':UTILPATH.getRemByPx(1800), 'textAlign':'left'}} onChange={this.changeStore}>

                        {storeDom}
                    </div>
                </div>
                {btnDom}{cancelBtnDom}
            </PopModel>;

            this.setState({
                popupInfo : defaultPopupInfo
            },()=>{
                this.showPopup({
                    popupChild : dom
                });
            });
        }
    }
    // 断网模式，显示门店列表弹窗
    showStoreListPop(storeList){
        if(storeList && storeList.length > 0){
            let storeDom = storeList.map((store,index)=>{
                return <option key={"storeListPop"+index} value = {store.id}>{store.name}</option>
            });
            let btnWidth = UTILPATH.getRemByPx(260);
            let btnMarginLeft = UTILPATH.getRemByPx(30);
            let btnBorderRadius = UTILPATH.getRemByPx(10);
            let border = "2px solid #e5e5e5"
            let btnDom = <Button key={"stopServerStoreListBtn"} style={{'width':btnWidth,'border':border,'marginLeft':'40%','marginTop':'12%'}} text={"确定"} option={this.handleChooseStore}/>
            let dom = <PopModel popupTitle={"选择门店"} classContainer={"recoveryPopInfo"}>
                <div className={"font36"} style={{'marginTop':'12%'}}>
                    <span className={"font"}>选择当前门店 </span>
                    <select
                        defaultValue=""
                        onChange={this.handleStoreChange}
                    >
                        {storeDom}
                    </select>
                </div>
                {btnDom}
            </PopModel>;

            this.setState({
                popupInfo : defaultPopupInfo
            },()=>{
                this.showPopup({
                    popupChild : dom
                });
            });
        }
    }
    // 断网模式，显示扫码弹窗，这个是为让用户通过小程序扫码登录
    showQrcodePop(storeId){
        if(storeId){
            UTILPATH.myLogger.info("showQrcodePop ")
            const {dispatch,state} = this.props;
            let {commonInfo={}} = state;
            let {userInfo={}} = commonInfo;
            let {employeeId=0,id=""} = userInfo;
            if(!employeeId){
                dispatch(pollingGetUserinfo(storeId));
            }
            let qrcodeUrl = `http://www.mjitech.com/web/redirect.action?type=store&storeId=${storeId}&from=panel`;
            UTILPATH.myLogger.info("showQrcodePop qrcodeUrl ",qrcodeUrl);
            let btnWidth = UTILPATH.getRemByPx(260);
            let btnMarginLeft = UTILPATH.getRemByPx(30);
            let btnBorderRadius = UTILPATH.getRemByPx(10);
            let border = "2px solid #e5e5e5";
            let style = {
                width: UTILPATH.getRemByPx(300),
                height: UTILPATH.getRemByPx(300),
                border: border,
                position: "absolute",
                left: "50%",
                top: "50%",
                transform: "translate(-50%,-50%)"
            }
            let dom = <PopModel popupTitle={"扫码开门二维码"} classContainer={"recoveryPopInfo"}>
                <div className={"font36"} style={style}>
                    <ReactQrCode className={"qrcodeCanvas"} value={qrcodeUrl || ''}/>
                </div>
            </PopModel>;

            this.setState({
                popupInfo : defaultPopupInfo
            },()=>{
                this.showPopup({
                    popupChild : dom
                });
            });

        }

    }
    // 点击页面“开始工作”
    startWork(){
        const {dispatch,state} = this.props;
        let {commonInfo={}} = state;
        console.log(state)
        this.setState({
            startWork : true
        },()=>{
            dispatch(getTaskList(commonInfo))
        });

    }
    // 回退，菜单栏进入页面的回退按钮，执行这个方法，暂时未用
    goBackTask(){
        let {state} = this.props;
        let {commonInfo={}} = state;
        let {userInfo={},taskInfo={}} = commonInfo;
        if(userInfo.taskType === "SECOND" && taskInfo && taskInfo.currentTaskType){
            switch (taskInfo.currentTaskType) {
                case 'LR' :
                    this.changePages(CONFIG.showPage[5]);
                    break;
                case 'CK' :
                case 'CR' :
                    this.changePages(CONFIG.showPage[6]);
                    break;
                case 'RE' :
                    this.changePages(CONFIG.showPage[10]);
                    break;
                case 'ADDR' :
                    this.changePages(CONFIG.showPage[11]);
                    break;
                case 'PF' :
                    this.changePages(CONFIG.showPage[14]);
                    break;
                case 'ER' :
                    this.changePages(CONFIG.showPage[12]);
                    break;
                case 'REA' :
                    this.changePages(CONFIG.showPage[15]);
                    break;
                case 'FINISH':
                    this.changePages(CONFIG.showPage[131]);
                    break;
                default:
                    this.changePages(CONFIG.showPage[13]);
                    break;
            }
        }else{
            this.changePages(CONFIG.showPage[13]);
        }
    }

    getChildContext() {
        return {
            toggleOrders: this.toggleOrders,
            goBackTask: this.goBackTask
        }
    }
    //得到当前页面
    getPages(){
        let pages = null;
        let{state,dispatch} = this.props;
        let {commonInfo} = state;
        let area =commonInfo.taskInfo&&commonInfo.taskInfo.area;
        switch (this.state.showPage){
            case showPage[1]:
                pages = <TroubleContainer
                    troubleList={state.troubleList}
                    refreshImg = {state.refreshImg}
                    headerInfo = {commonInfo}
                    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,commonInfo))}
                    emptyImg={()=>dispatch(emptyImg())}
                />;
                break;
            case showPage[2]:
                pages = <ScanBarCodeContainer
                            headerInfo = {commonInfo}
                            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 = {commonInfo}
                            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)}
                            state = {state}
                            showPopup={(info)=>this.showPopup(info)}
                            hidePopup={()=>this.hidePopup()}
                        />;
                break;
            case showPage[7]:
                pages = <HomeContainer showClock={this.state.showClock}
                                       headerInfo={commonInfo}
                                       judgeDoorStatus={this.judgeDoorStatus}
                />;
                break;
            case showPage[8]:
                pages = <FinishAskContainer headerInfo={commonInfo}
                                            endCountBack={this.endCountBack}
                                            changePages={(data)=>this.changePages(data)}
                                            showOpenDoorPage={()=>this.showOpenDoorPage.bind(this)()}
                                            showPopup={(info)=>this.showPopup(info)}
                                            uploadErrs={()=>this.uploadErrs()}
                                            hidePopup={()=>this.hidePopup()}
                />;
                break;
            case showPage[9]:
                pages = <ChooseTaskContainer headerInfo={commonInfo}
                                             changePages={(data)=>this.changePages(data)}
                                             showOpenDoorPage={()=>this.showOpenDoorPage.bind(this)()}
                                             showPopup={(info)=>this.showPopup(info)}
                                             hidePopup={()=>this.hidePopup()}
                                             willCloseDoor={async ()=>{return await dispatch(willCloseDoor(commonInfo,false))}}

                />;
                break;
            /*以下是二期页面 start*/
            case showPage[13]:
                pages = <HomePage headerInfo={commonInfo}
                                  getTaskList={()=>this.startWork()}
                                  changePages={(data)=>this.changePages(data)}
                                  showPopup={(info)=>this.showPopup(info)}
                                  hidePopup={()=>this.hidePopup()}
                                  dispatch={dispatch}
                                  showStoreSelect={()=>this.showStoreSelect()}
                                  getStoreDoorStatus={()=>this.getStoreDoorStatus()}

                                   />;
                break;
            case showPage[131]:
                pages = <HomePage headerInfo={commonInfo}
                                  changePages={(data)=>this.changePages(data)}
                                  showPopup={(info)=>this.showPopup(info)}
                                  hidePopup={()=>this.hidePopup()}
                                  willCloseDoor={async ()=>{return await dispatch(willCloseDoor(commonInfo,false))}}
                                  closeDoor={true}
                                  tempLogout={()=>this.tempLogout.bind(this)()}
                                  changeIsSend ={this.changeIsSend.bind(this)}
                                  endCountBack={this.endCountBack}
                                  startStopServer={this.state.startStopServer}
                                  getStoreDoorStatus={()=>this.getStoreDoorStatus()}
                                  dispatch={dispatch}
                />;
                break;
            case showPage[12]:
                pages =<TroubleContainer
                                 headerInfo={commonInfo}
                                 showPopup={(info)=>this.showPopup(info)}
                                 hidePopup={()=>this.hidePopup()}
                                 updateTroubleList={(info)=>dispatch(updateTroubleList(info,commonInfo))}
                        />
                break;
            case showPage[6]:
                pages = <TakeStokeContainer headerInfo = {commonInfo}
                                            showPopup={(info)=>this.showPopup(info)}
                                            hidePopup={()=>this.hidePopup()}
                                            tokeTaskProduct={WeChatUtil.getUrlParam().type&&WeChatUtil.getUrlParam().type==='CK'?testTakeStoreData.data.skuFlatVo:commonInfo.taskList}
                                            checkProductQuantity={(tokeProductInfo)=>{dispatch(checkProductQuantity({commonInfo,tokeProductInfo}))}}
                                            TokeStokeState={state.TokeStokeContainer}
                                            getTaskList={()=>{dispatch(getTaskList(commonInfo))}}
                />;
                break;
            case showPage[5]:
                pages = <BreakageContainer
                                 menuType={''}
                                 pullTaskList={()=>{dispatch(hasNoSku(commonInfo))}}
                                 headerInfo={commonInfo}
                                 getBarCodeProductInfo={(barcode)=>{dispatch(getBarCodeProductInfo({barcode,commonInfo}))}}
                                 breakageProductInfo={WeChatUtil.getUrlParam().type&&WeChatUtil.getUrlParam().type==='LR'?testBreakData.data:state.barcodeCommon}
                                 breakageContainer ={state.breakageContainer}
                                 submitBreakageProduct={(productDetail)=>{dispatch(submitBreakageProduct({commonInfo,productDetail}))}}
                                 area={area}
                                 />;
                break;
            case showPage[51]:
                pages = <BreakageContainer
                                menuType={'HPBS'}
                                pullTaskList={()=>{dispatch(hasNoSku(commonInfo))}}
                                headerInfo={commonInfo}
                                getBarCodeProductInfo={(barcode)=>{dispatch(getBarCodeProductInfo({barcode,commonInfo}))}}
                                breakageProductInfo={state.barcodeCommon}
                                breakageContainer ={state.breakageContainer}
                                submitBreakageProduct={(productDetail)=>{dispatch(submitBreakageProduct({commonInfo,productDetail}))}}
                                area={area}
                />;
                break;
            case showPage[10]:
                pages = <RecoveryPage
                        headerInfo = {commonInfo}
                        recoveryInfo = {state.recoveryInfo}
                        showPopup={(info)=>this.showPopup(info)}
                        hidePopup={()=>this.hidePopup()}
                        getTaskName={()=>dispatch(getTaskName(commonInfo.taskInfo.currentTaskType,2))}
                        finishBoxRecovery={async ()=>{ return await dispatch(finishBoxRecovery(commonInfo))}}
                        uploadError={(exceptionType)=>dispatch(uploadError(commonInfo,exceptionType))}
                        getBarCodeProductInfo={(barcode)=>{dispatch(getBarCodeProductInfo({barcode,commonInfo}))}}
                />;
                break;
            case showPage[15]:
                pages = <BoxRecoveryPage
                    headerInfo = {commonInfo}
                    showPopup={(info)=>this.showPopup(info)}
                    hidePopup={()=>this.hidePopup()}
                    willCloseDoor={async ()=>{return await dispatch(willCloseDoor(commonInfo,true))}}
                />;
                break;
            case showPage['DevPage'] :
                 pages = <DevPage
                    headerInfo = {commonInfo}
                    changePages={(data)=>this.changePages(data)}
                 />
                 break;
            case showPage[11]:
                pages = <ReplenishContainer
                    headerInfo = {commonInfo}
                    showPopup={(info)=>this.showPopup(info)}
                    hidePopup={()=>this.hidePopup()}
                    barcodeInfo={state.barcodeCommon}
                    emptyBarcodeInfo={()=>dispatch(saveProductInfo({}))}
                    replenishInfo={state.replenishInfo}
                    getBarCodeProductInfo={(barcode)=>{dispatch(getBarCodeProductInfo({barcode,commonInfo}))}}
                    finishBoxRecovery={async ()=> { return await dispatch(finishBoxRecovery(commonInfo))}}
                    emptyErrorInfo={()=>dispatch(replenishAction.emptyErrorInfo())}
                    uploadError={(exceptionType)=>dispatch(uploadError(commonInfo,exceptionType))}
                    finishReplenish={(source)=>dispatch(replenishAction.finishReplenish(commonInfo,source))}
                />;
                break;
            case showPage[14]:
                pages = <QuestionContainer headerInfo={commonInfo}
                                           changePages={(data)=>this.changePages(data)}
                                           showPopup={(info)=>this.showPopup(info)}
                                           hidePopup={()=>this.hidePopup()}
                                           willCloseDoor={()=>{dispatch(willCloseDoor(commonInfo,false))}}
                />;
                break;
            case showPage[141]:
                pages = <QuestionContainer
                                menuType={'WTFK'}
                                headerInfo={commonInfo}
                                changePages={(data)=>this.changePages(data)}
                                showPopup={(info)=>this.showPopup(info)}
                                hidePopup={()=>this.hidePopup()}

                />
            /*以下是二期页面 end*/
        }
        return pages;
    }


    handleTouch(){
        this.countBackTime = this.state.maxTime;
        if(this.state.showAlarm){
            this.setState({
                showAlarm : false
            },()=>{
                this.beginCountBack();
            })
        }
    }

    render() {
        let {state} = this.props;
        let headerInfo = state.commonInfo;
        let ip = headerInfo ? headerInfo.ip : '';
        let mp3Url = ip ? `http://${ip}:8088/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.state.showClassify ? <AllClassify showClassify={this.state.showClassify}/> : null
                }

                {this.getPages()}
            </div>
        )
    }
}

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

PageContainer.childContextTypes = {
    toggleOrders: PropTypes.func,
    goBackTask: PropTypes.func
};

export default connect(select)(PageContainer)
