import React from 'react';
import HeaderComponent from '../../components/CommonComponent/HeaderComponent/HeaderComponent'
import Button from '../../components/CommonComponent/ButtonComponent/ButtonComponent'
import PopModel from '../../components/CommonComponent/PopupComponent/PopupChildComponent'
import {sendMsg} from "../../util/socket";
import fetch from 'isomorphic-fetch'
require('./index.css');
let domain = ENV.domain;
export default class HomePageContainer extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            text : '',
            closeDoorStatus : 0
        }
        this.logout = this.logout.bind(this);
        this.showLogoutPopup = this.showLogoutPopup.bind(this)
    }

    componentWillMount(){
        let text = '';
        let hour = parseInt(new Date().getHours());
        switch (true){
            case hour >= 0 && hour < 11:
                text = '上午好，';
                break;
            case hour >= 11 && hour < 13:
                text = '中午好，';
                break;
            case hour >= 13 && hour < 18:
                text = '下午好，';
                break;
            case hour >= 18 && hour < 24:
                text = '晚上好，';
                break;
        }
        this.setState({
            text:text,



        })
    }
    onConnectionChange(){
        const { rtt, downlink, effectiveType, saveData } = navigator.connection;
        console.log(`有效网络连接类型: ${effectiveType}`);
        console.log(`估算的下行速度/带宽: ${downlink}Mb/s`);
        console.log(`估算的往返时间: ${rtt}ms`);
        console.log(`打开/请求数据保护模式: ${saveData}`);
        console.log(navigator.connection.effectiveType)
    }
    logout(){
        if(this.state.closeDoorStatus === 0){
            this.setState({
                closeDoorStatus : 1
            },()=>{
                UTILPATH.myLogger.info("logout startStopServer ",this.props.startStopServer);
                if(!navigator.onLine){
                    // 断网调用
                    // this.props.willCloseDoor().then(()=>{
                    //     this.props.endCountBack();
                    //     this.props.tempLogout()

                    // })
                     this.setState({ closeDoorStatus : 0},()=>{
                         alert('当前无网络连接，稍后重试')
                     })

                }else{
                    //正常调用


                    try {
                        fetch(domain+'machine_pad/finish_task.action',{
                            credentials : 'include',
                            method : 'POST',
                            mode : 'cors',
                            headers:{
                                'Access-Control-Allow-Origin': '*',
                                'Content-Type': 'application/json; charset=UTF-8'
                            },
                            body:JSON.stringify({
                                area:this.props.headerInfo.taskInfo.area,
                                storeId:this.props.headerInfo.storeInfo.id,
                                taskId:this.props.headerInfo.taskInfo.taskId,
                                 taskType:this.props.headerInfo.taskInfo.currentTaskType,
                                userId:this.props.headerInfo.userInfo.employeeId})}

                        ).then((res)=>{
                            if(res.status!=200){
                                var error = new Error(response.statusText)
                                error.response = response
                                throw error
                            }else{
                                console.log('res',res)
                            this.props.willCloseDoor().then(()=>{
                            this.props.endCountBack();
                            this.props.changeIsSend(true);
                            let msg={type:'WILL_CLOSEDOOR'};
                            sendMsg(JSON.stringify(msg));
                            // this.props.tempLogout()
                            console.log('有网络',this.props)
                        })
                            }
                        })
                        .catch((err)=>{
                            this.setState({ closeDoorStatus : 0},()=>{
                                        alert('当前网络不佳，请稍后重试')
                                    })
                        })


                    //     this.props.willCloseDoor().then(()=>{
                    //         this.props.endCountBack();
                    //         let msg={type:'WILL_CLOSEDOOR'};
                    //         sendMsg(JSON.stringify(msg));
                    //         this.props.changeIsSend(true);
                    //         // this.props.tempLogout()
                    //         console.log('有网络',this.props)
                    //     })
                    //    }else{
                    //     this.setState({ closeDoorStatus : 0},()=>{
                    //         alert('当前网络不佳，请稍后重试')
                    //     })


                    //    }

                    } catch (error) {
                        console.log(error,'cuowu')
                    }



                }

            })
        }
    }

    componentWillUnmount(){
        this.setState({
            closeDoorStatus : 0
        })
    }

    showLogoutPopup(){
        let {showPopup,hidePopup} = this.props;
        let btnDom1 = <Button btnContainer={"headerLogoutBtn backff775c colfff font32 font32 "} key={"headerLogoutBtn1"} text={"确定退出？"} option={this.logout}/>
        let btnDom2 = <Button btnContainer={"headerLogoutBtn btne5 font32"} key={"headerLogoutBtn2"} text={"取消"} option={hidePopup}/>
        let popDom =
            <PopModel popupTitle={"是否退出登录"} classContainer={"headerLogout"}>
                <div className={"icon iconfont icon-exclamation font150 colf5a623"} />
                <div className={"text font40 col000"} style={{lineHeight:'1.6'}}>
                    <p>此步临时添加，可用作测试退出登录</p>
                    <p>重新扫码开门，不必重启服务</p>
                </div>
                <div className={"btn"}>
                    {btnDom1}
                    {btnDom2}
                </div>
            </PopModel>;
        showPopup({popupChild:popDom});
    }

    render(){
        let props = this.props;
        let {headerInfo={}} = props;
        let {taskInfo={}} = headerInfo;
        let marginTop = UTILPATH.getRemByPx(77);
        let marginTop50 = UTILPATH.getRemByPx(50);
        let marginTop20 = UTILPATH.getRemByPx(20);
        let padding = UTILPATH.getRemByPx(8);
        let marginTop160 = UTILPATH.getRemByPx(160);
        let imgStyle =  taskInfo.area ? {marginTop: marginTop160} : {};
        let buttonStyle={background:'#ff775c',margin:"0 auto",marginTop:marginTop};
        return(
            <div>
                <HeaderComponent
                    showHeader={CONFIG.headerStatus[1]}
                    headerInfo={headerInfo}
                    showLogoutPopup={this.showLogoutPopup}
                    changePages = {this.props.changePages}
                />
                {
                    props.closeDoor ? <div className={"homeContainer"} >
                        <img className={"homeIcon"} style={imgStyle} src={UTILPATH.localImg.homePage} alt=""/>
                        {
                            taskInfo.area ? <div className={'homeWelcom font42 clo333'} style={{marginTop:marginTop50}}>恭喜您，{taskInfo.area}区工作任务完成</div>
                                : null
                        }
                        <div className={"homeText font42"} style={{marginTop:marginTop20}}>请关门，然后继续完成其他工作</div>
                        <Button text={this.state.closeDoorStatus === 1 ? '关门中...' : '请点击按钮后关门'} btnContainer={'colfff font30'} style={buttonStyle} option={this.logout.bind(this)}/>
                    </div> :
                    <div className={"homeContainer"} >
                        <img className={"homeIcon"} style={imgStyle} src={UTILPATH.localImg.homePage} alt=""/>
                        {
                            taskInfo.area ? <div className={'homeWelcom font30 clo333'} style={{marginTop:marginTop50}}>欢迎来到<span className="homeArea font50 colff775c" style={{padding:`0 ${padding}`}}>{taskInfo.area || ''}</span>区</div>
                                : null
                        }
                        <div className={"homeText font42"} style={{fontWeight:'800',marginTop:marginTop20}}>{this.state.text}你辛苦了！</div>
                        <Button text={'开始工作'} btnContainer={'colfff font30'} style={buttonStyle} option={this.start.bind(this)}/>
                    </div>

                }


            </div>

        )
    }
    start(){
        let props = this.props;
        let {getTaskList} = props;
        if(getTaskList){
            getTaskList();
        }
    }

}
11
HomePageContainer.propTypes = {
};

HomePageContainer.defaultProps = {
}
