import React from 'react';
import SwiperComponent from '../../components/CommonComponent/SwiperComponent/SwiperComponent'
import TroubleItem from '../../components/TroubleComponent/TroubleItemComponent/TroubleItemComponent'
import HeaderComponent from '../../components/CommonComponent/HeaderComponent/HeaderComponent'
import TextArea from "../../components/CommonComponent/TextAreaContainer/TextAreaContainer";
import Qrcode from '../../components/CommonComponent/Qrcode/Qrcode'
import FinishTrouble from '../../components/TroubleComponent/FinishTroubleComponent/FinishTroubleComponent'
import Button from '../../components/CommonComponent/ButtonComponent/ButtonComponent'
require('./index.css')

const showDom={
    1:'default',
    2:'textArea',
    3:'qrcode'
};

export default class TroubleContainer extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            showTrouble : true,
            troubleList : {},
            currentErrorCode : 0,
            tmpText : '',
            tmpUrl : '',
            showStatus:showDom[1],
            style : {},
            initialSlide : 0,
            tempinitialSlide : 0
        };
        this.setItem = this.setItem.bind(this);
        this.showText = this.showText.bind(this);
        this.showQrcode = this.showQrcode.bind(this);
        this.goBack = this.goBack.bind(this);
        this.saveText = this.saveText.bind(this);
        this.getDefaultDom = this.getDefaultDom.bind(this);
        this.getTextAreaDom = this.getTextAreaDom.bind(this);
        this.getQrcodeDom = this.getQrcodeDom.bind(this);
        this.updateImg = this.updateImg.bind(this);
        this.dealTrouble = this.dealTrouble.bind(this);
        this.setStyle = this.setStyle.bind(this);
        this.onSlideChangeEnd = this.onSlideChangeEnd.bind(this);
        this.abandonSaveText = this.abandonSaveText.bind(this);
    }


    componentWillMount(){
        let {troubleList,initTroubleList} = this.props;
        // initTroubleList({storeId: 7, employeeId: 5, token: "966D5C0B-3CF2-420D-B9A3-313BA37DE092"});
        this.setState({
            troubleList : troubleList
        })
    }

    componentWillReceiveProps(nextProps){
        let troubleList = nextProps.troubleList;
        let nowTroubleList = this.state.troubleList;
        let troubleErrorCodeList = Array.isArray(troubleList.details) ? troubleList.details.map(i=>i.errorCode) : [];
        let nowtroubleErrorCodeList = Array.isArray(nowTroubleList.details) ? nowTroubleList.details.map(i=>i.errorCode) : [];

        //上一次和这一次不一样
        let troubleErrorCodeListStr = troubleErrorCodeList.join(",");
        let nowtroubleErrorCodeListStr = nowtroubleErrorCodeList.join(",");

        if(
            troubleErrorCodeListStr !== nowtroubleErrorCodeListStr
        ){
            this.setState({
                troubleList : troubleList
            })
        }
        let refreshImg = nextProps.refreshImg;
        if(refreshImg && refreshImg.files &&  refreshImg.errorId && refreshImg.type){
            this.updateImg(refreshImg);
        }
        // let lastRefreshImg = this.props.refreshImg;
        // if(
        //     (
        //         !lastRefreshImg && (refreshImg && refreshImg.errorId && refreshImg.type && refreshImg.files)
        //     ) ||
        //     (
        //         lastRefreshImg && refreshImg && lastRefreshImg.errorId !== refreshImg.errorId
        //     ) ||
        //     (
        //         lastRefreshImg && refreshImg && lastRefreshImg.type !== refreshImg.type
        //     ) ||
        //     (
        //         lastRefreshImg && refreshImg && lastRefreshImg.files && refreshImg.files && refreshImg.files.length !== lastRefreshImg.files.length
        //     )
        //
        // ){
        //     this.updateImg(refreshImg);
        // }
    }

    updateImg(info){
        let {emptyImg} = this.props;
        let id = info.errorId;
        let type = info.type;
        let files = info.files;
        let troubleList = this.state.troubleList;
        let details = troubleList.details;
        let indexInfo = details.find(d=>d.id === id && d.type === type);
        if(indexInfo && indexInfo.id){
            this.setItem(indexInfo.errorCode,"files",files,()=>{
                emptyImg()
            });
        }
    }

    showText(errcode){
        let troubleList = this.state.troubleList;
        let details = troubleList.details;
        let indexInfo = details.find(d=>d.errorCode === errcode);
        let index = details.findIndex(d=>d.errorCode === errcode);
        if(indexInfo && indexInfo.id){
            let text = indexInfo.explanation;
            this.setState({
                currentErrorCode : errcode,
                showStatus : showDom[2],
                tmpText: text,
                tempinitialSlide : index
            })
        }
    }

    showQrcode(errcode){
        let troubleList = this.state.troubleList;
        let details = troubleList.details;
        let indexInfo = details.find(d=>d.errorCode === errcode);
        let index = details.findIndex(d=>d.errorCode === errcode);
        if(indexInfo && indexInfo.id){
            this.setState({
                currentErrorCode : errcode,
                showStatus : showDom[3],
                tmpUrl: `${ENV.uploadImg}/${indexInfo.id}/${indexInfo.type}`,
                tempinitialSlide : index
            })
        }
    }

    handleDeleteImg(errorId,type,fileId){
        let {deleteImg} = this.props;
        let troubleList = this.state.troubleList;
        let details = troubleList.details;
        let index = details.findIndex(d=>d.id === errorId && d.type === type);
        if(index > -1){
            this.setState({
                tempinitialSlide : index,
                initialSlide : index,
            },()=>{
                deleteImg(errorId,type,fileId)
            })
        }

    }

    setItem(errcode,option,info,callback){
        let troubleList = this.state.troubleList;
        let details = troubleList.details;
        let index = details.findIndex(d=>d.errorCode === errcode);
        if(index > -1){
            details[index][option] = info;
        }
        this.setState({
            troubleList : troubleList,
        },()=>{
            if(callback && callback instanceof Function){
                callback()
            }else{
                this.abandonSaveText()
            }

        })
    }

    saveText(text){
        let errcode = this.state.currentErrorCode;
        this.setItem(errcode,'explanation',text,()=>{
            this.abandonSaveText()
        });
    }

    abandonSaveText(){
        let {showPopup,hidePopup} = this.props;
        hidePopup();
        this.setState({
            currentErrorCode : 0,
            showStatus : showDom[1],
            tmpText: '',
            tmpUrl : '',
            style:{},
            initialSlide : this.state.tempinitialSlide
        })
    }

    goBack(hasChange){
        let {showPopup,hidePopup} = this.props;
        if(hasChange){
            let btnWidth = UTILPATH.getRemByPx(260);
            let btnMarginLeft = UTILPATH.getRemByPx(30);
            let btnDom1 = <Button key={"textGoBackTrouble1"} style={{'width':btnWidth,'marginRight':btnMarginLeft}} text={"取消"} option={hidePopup}/>
            let btnDom2 = <Button key={"textGoBackTrouble2"} style={{'width':btnWidth}} text={"放弃"} option={this.abandonSaveText}/>
            showPopup({
                popupText:'是否放弃更新编辑的内容？',
                popupButtons:[btnDom1,btnDom2]
            })
        }else{
            this.abandonSaveText();
        }

    }

    dealTrouble(){
        let {showPopup,hidePopup,updateTroubleList} = this.props;
        let troubleList = this.state.troubleList;
        let details = troubleList.details;
        let arr = details.filter(d=>{
            return !d.isExistProblem || ( d.isExistProblem === 1 && ! d.explanation)
        });
        let btnWidth = UTILPATH.getRemByPx(260);
        let btnDom = <Button key={"dealTrouble1"} style={{'width':btnWidth}} text={"关闭"} option={hidePopup}/>
        if(arr && arr.length > 0){
            showPopup({
                popupText:'请完成所有需要处理的故障的必填项',
                popupButtons:[btnDom]
            })
        }else{
            details.forEach((d)=>{
                d.imagesFileId = Array.isArray(d.files) ? d.files.map(f=>f.id).join(',') : d.imagesFileId;
            });
            updateTroubleList(details);
            this.setState({
                showTrouble : false
            })
        }
    }

    onSlideChangeEnd(swiper){
    }

    getDefaultDom(){
        let {userInfo,storeInfo,getRefreshImg,deleteImg,changePages,showPopup,hidePopup} = this.props;
        let troubleList = this.state.troubleList;
        let showTrouble = Array.isArray(troubleList.details) && troubleList.details.length > 0;
        let details = Array.isArray(troubleList.details) ? troubleList.details : [];
        let imgLength = details.map(d=>Array.isArray(d.files) ? d.files.length : 0).reduce((pre,next)=>{return pre + next},0);
        let dom = details.map((i,k)=>{
            return <TroubleItem key={k} item={i} num={k+1} setItem={this.setItem}
                                showText={this.showText} showQrcode={this.showQrcode}
                                getRefreshImg={getRefreshImg}
                                deleteImg={(errorId,type,fileId)=>this.handleDeleteImg(errorId,type,fileId)}
                                showPopup={showPopup}
                                hidePopup={hidePopup}

            />;
        });
        let initialSlide = this.state.initialSlide;
        let swiperCount = details.length + imgLength;
        let swiperOptions = {
            // width : 1396,
            slidesPerView: "auto",
            spaceBetween: 30,
            // freeMode:true,
            // pagination: '.pagination',
            // loop:false,
            mode: 'horizontal',
            touchRatio:0.5,
            longSwipesRatio:0.1,
            threshold:50,
            followFinger:false,
            observer: true,//修改swiper自己或子元素时，自动初始化swiper
            observeParents: true,//修改swiper的父元素时，自动初始化swiper
            lazyLoadingInPrevNextAmount: 1,
            onSlideChangeEnd : this.onSlideChangeEnd,
            initialSlide : initialSlide
        };
        let swiperContainer = CONFIG.swiperContainers.troubleSwiperContainer;


        return(
            <div className={"toubleContainer " + (showTrouble ? '' : 'hide')}>
                <HeaderComponent
                    showHeader={CONFIG.headerStatus[1]}
                    userinfo={userInfo}
                    storeInfo={storeInfo}
                />

                {
                    this.state.showTrouble ?
                        <div className={"troubleContent " + ( this.state.showTrouble ? '' : 'hide')}>
                            <div className={"troubleText font32"}><span className={"colff7860"}>* </span>必填项</div>
                            <div className={"troubleBox"}>
                                <SwiperComponent
                                    swiperContainer={swiperContainer} swiperOptions={swiperOptions} swiperCount={swiperCount}
                                    initialSlide={initialSlide} canMove={true}
                                >
                                    {dom}
                                </SwiperComponent>
                            </div>
                            <div className={"troubleBtnBox"}>
                                <div className={"troubleBtn colfff font32"} onClick={()=>this.dealTrouble.bind(this)()}>
                                    处理完毕
                                </div>
                            </div>

                        </div> : <FinishTrouble changePages={changePages}/>
                }
            </div>
        )
    }

    setStyle(style){
        this.setState({
            style : style
        })
    }

    getTextAreaDom(){
        return <TextArea
            text={this.state.tmpText}
            goBack={this.goBack}
            saveText={this.saveText}
            setStyle={this.setStyle}
        />
    }

    getQrcodeDom(){
        return <Qrcode goBack={this.goBack} url={this.state.tmpUrl}/>
    }

    getDom(){
        switch (this.state.showStatus){
            case showDom[1]:
                return this.getDefaultDom();
            case showDom[2]:
                return this.getTextAreaDom();
            case showDom[3]:
                return this.getQrcodeDom();
            default :
                return null;
        }
    }


    render(){
        return (
            <div className={"troubleContainers "+(this.state.showStatus === showDom[2] ? 'backfff' : '')} style={this.state.style}>
                {
                    this.getDom()
                }
            </div>
        )
    }
}
