/** 
 * @Description:
 * @author ayawai
 * date 2019/04/07
 */
import React from 'react';
import { Input, Button, Steps,Tree, Collapse, Timeline, Row, Col, Tabs, Popover, Divider, Checkbox, Progress } from 'antd';
import storage from "../../../utils/storage";
import { initFilter, extendRule, extendInclude, initQueryFilter,initFilterGroup,extendGroupRule,extendFilterGroup } from '../../../utils/common';
import { connect } from 'dva';
import styles from '../WO/ProductOrderQuery/index.css';
import ListTablePageBase from '../../Table/ListTablePageBase';
import TreePage from '../../Tree/TreePage';
import Edit from '../../Edit/Edit';
import { get } from 'http';
import TableComponent from '../../../baseComponents/TableComponent';

const { Panel } = Collapse;
const { TabPane } = Tabs;
const { Step } = Steps;
const TreeNode = Tree.TreeNode;

class SnSearchTable extends TableComponent{

    componentDidMount() {
        super.componentDidMount();  
        if(this.props.regLoadAllData){
            this.props.regLoadAllData(()=>{
                const { tableList } = this.state;
                tableList.forEach(t=>{
                    if(t.CODE==='snTree'){
                        if(this.loadTreeData){
                            this.loadTreeData({});
                        }
                    }
                    else{
                        this.loadTableData({ tableCode:t.CODE });
                    }
                });
            });
        }
    };

    renderSnBoxNode=(data,isShowState)=>{
        if(data&&data.length){
            return data.map(t=>{
                let title=t.Nav_Box.CODE;
                let state='/未送检';
                if(t.Nav_Box.Nav_SendOrder){
                    state='/已送检'
                }
                if(t.Nav_Box.Nav_SendOrder&&t.Nav_Box.Nav_SendOrder.Nav_QcOrder){
                    state='/检验中'
                }

                if(t.Nav_Box.Nav_SendOrder&&t.Nav_Box.Nav_SendOrder.Nav_QcOrder&&t.Nav_Box.Nav_SendOrder.Nav_QcOrder.ORDER_STATUS===2){
                    state='/检验完成'
                }
                if(isShowState){
                title+=state;
                }

                if(t.Nav_BoxChildrens&&t.Nav_BoxChildrens.length){
                    return <TreeNode key={t.Nav_Box.ID} title={title}
                    isLeaf={false} >
                        {
                           this.renderSnBoxNode(t.Nav_BoxChildrens) 
                        }
                    </TreeNode>
                }
                return <TreeNode key={t.Nav_Box.ID} title={title}
                isLeaf={true}></TreeNode>
            });
        }
    }

    doGetRenderTable=(table)=>{
        if(table.CODE==='snRecord'){
            if(this.props.sn&&this.props.sn.Nav_SNRecords
                &&this.props.sn.Nav_SNRecords.length){ 
              return <Timeline>
                            {this.props.sn.Nav_SNRecords.map(t => {
                                return <Timeline.Item>{t.REMARK}</Timeline.Item>;
                            })}
                        </Timeline> 
            }
            return <div>暂无数据</div>;
        }
        else if(table.CODE==='snTree'){
            if (!this.props.isLoading&& this.props.sn&&this.props.sn.Nav_TopSN && this.props.sn.Nav_TopSN.ID) {
                return <div id='snTree'><TreePage formCode={'MM025'} data={{
                    rules: [{ field: 'ID', operator: 1, value: this.props.sn.Nav_TopSN.ID }]
                }} onRegLoadFunc={func=>this.loadTreeData=func} /></div>
            }
            return <div>暂无数据</div>;
        }
        else if(table.CODE==='snBox'){
            if (this.props.sn&&this.props.sn.Nav_BoxChildrens && this.props.sn.Nav_BoxChildrens.length) {
                return <Tree>
                        {
                            this.renderSnBoxNode(this.props.sn.Nav_BoxChildrens,true)
                        }
                </Tree>
            }
            return <div>暂无数据</div>;
        }
        return this.getRenderTable(table.CODE);
    }

    onLoadTableDataParam(params){
        const { tableCode, loadParam }=params;
        let isError=super.onLoadTableDataParam(params);
        if(!this.props.sn||!this.props.sn.Nav_SN||
            !this.props.sn.Nav_SN.ID||
            tableCode=== 'snRecord'||
            tableCode=== 'snTree'||
            tableCode==='snBox'){
            isError=true;
        } 
        else if(tableCode==='sntestResult'){
            loadParam.Keyword=this.props.sn.Nav_SN.ID;
            const g=initFilterGroup(false);
            extendGroupRule(g,'SN',1,this.props.sn.Nav_SN.CODE);
            extendGroupRule(g,'ORGIN_SN',1,this.props.sn.Nav_SN.CODE); 
            extendFilterGroup(loadParam,g);
        }
        else  if(tableCode==='split'){
            loadParam.Keyword=this.props.sn.Nav_SN.ID;
            extendRule(loadParam,'SPLIT_SN_ID',1,this.props.sn.Nav_SN.ID);
        }
        else 
        {
            loadParam.Keyword=this.props.sn.Nav_SN.ID;
            extendRule(loadParam,'SN_ID',1,this.props.sn.Nav_SN.ID);
        } 
        if(isError){
            this.setTableData({tableCode,data:{}});
        }
        if(this.props.formData){ 
            loadParam.AuthOrgCodes=this.props.formData.AUTH_ORG_CODES; 
        }
        return isError;
    }

    onRenderTableByList({ tableList /*,parentRecord,onRegLoadDataFunc,onLoadParam,onClickRow,isQuery,parentId */ }) {
        return tableList && tableList.length
          ?<Tabs defaultActiveKey={tableList[0].ID}>
{
    tableList.map(item => {
        return (
          <TabPane tab={item.LABEL_NAME} key={item.ID}>
            {this.doGetRenderTable(item)}
          </TabPane>
        )
      })
}

          </Tabs> 
          : null
      }
}

class SnSearch extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isTip: {},
            currentStep: 0,
            tableList: [],
            SnInfo: {
                Nav_SN: {
                    Nav_Childrens: []
                },
                Nav_TopSN: {

                },
                Nav_SplitSN: {}
            },
            snProcessInfos: [],
            topCheck: false,
            visible: false,
            currentPdtDetail: {},
        };
    }

    componentDidMount() {
        this.loadData();
    }

    loadData = () => {
        const {
            formId,
            formCode
        } = this.props;
        const orgId = this.props.login.OrgId;
        //const OJson = initFilter(orgId);
        // if (formId) {
        //     extendRule(OJson, 'ID', 1, formId);
        // } else {
        //     extendRule(OJson, 'CODE', 1, formCode);
        // }
        const OJson = {'Key':formId||formCode,'orgid':orgId};
        //extendRule(OJson, 'CODE', 1, formCode);
        this.props.dispatch({
          type: 'app/getFormByRedis',
            payload: OJson,
            onComplete: (ret) => {
                if (ret) {
                    this.setState({
                        formData: ret
                    }, () => {
                        const parentRecord = this.props.data.parentRecord;
                        if (parentRecord) {
                            this.handleFormSearch(parentRecord.CODE);
                        }
                    });
                }
            }
        });
    };
 
  
    checkOnchange = (e) => {
        this.setState({
            topCheck: e.target.checked,
        });
        // this.setState({
        //     loadFunc: d,
        // });
    }

    handleFormSearch = value => {
        const {
            dispatch,
            loading
        } = this.props;
        if (loading) return;
        const OrgId = storage('lacal').getItem('webOrgId').val;

        const json = initFilter(OrgId, value, 'CREATE_TIME', 0, 0, this.state.topCheck);
        // extendRule(json, 'CODE', 1, value);//Nav_Booking.Nav_JobUsers
        extendInclude(json, 'Nav_PdtOrder');
        extendInclude(json, 'Nav_Product');
        extendInclude(json, 'Nav_Parent');
        extendInclude(json, 'Nav_Childrens');
        if(this.state.formData){
            json.AuthOrgCodes= this.state.formData.AUTH_ORG_CODES
        }
        let self = this;
        this.setState({isLoading:true});
        dispatch({
            type: 'snSearch/getFullSn',
            payload: json,
            onComplete: res => { 
                const snProcessInfos = [];
                let curSnProcessInfo = null;
                let currentStep = 0;

                let isGetComm = false;
                if (res && res.Nav_SNProcessDetails && res.Nav_SNProcessDetails.length) {
                    res.Nav_SNProcessDetails.sort((x, y) => (x.NUM > y.NUM ? 1 : -1));
                    res.Nav_SNProcessDetails.forEach((t, i) => {
                        let stageName = "";
                        if (t.Nav_Booking &&
                            t.Nav_Booking.Nav_Workstage.NAME) {
                            stageName = t.Nav_Booking.Nav_Workstage.NAME;
                        };

                        const temp = {
                            key: t.ID,
                            title: t.Nav_PdtProcessDetail.NAME
                                + (t.Nav_PdtProcessDetail.IS_SPIT_PROCEDURE ? ("[分板]") : (t.Nav_PdtProcessDetail.IS_COMPOSE_PROCEDURE ? ("[合板]") : '')),
                            status: t.STATE === 4 ? "finish" : (t.STATE === 0 ? "wait" : "process"),
                            users: this.formatterUserName(t),
                            index: i,
                            endTime: t.END_TIME,
                            workStageName: stageName
                        };
                        snProcessInfos.push(temp);
                        if (t.STATE === 4) {
                            isGetComm = true;
                        } else if (isGetComm && !curSnProcessInfo) {
                            currentStep = i;
                        }
                    });
                }

                this.setState({
                    SnInfo: res,
                    snProcessInfos,
                    curSnProcessInfo,
                    currentStep,
                    currentValue: null,
                    isLoading:false,
                },()=>{
                    if(this.regLoadAllData){
                        this.regLoadAllData();
                    } 
                });
               
            },
        });
    };
    handleProcedureDetail = (item, isShow) => {
        this.setState({
            visible: isShow,
            currentPdtDetail: item
        })
    };

    formatterUserName(processDetail) {
        if (processDetail.Nav_Booking && processDetail.Nav_Booking.Nav_JobUsers) {
            let users = processDetail.Nav_Booking.Nav_JobUsers;
            let ret = "";
            users.forEach(function (n, i) {
                if (n.Nav_User) {
                    ret += n.Nav_User.NAME + ",";
                }
            });
            if (ret.length > 0) {
                ret = ret.substring(0, ret.length - 1);
            }

            return ret;
        }

        return '';
    }

    render() {
        const {
            app
        } = this.props;
        const {
            SnInfo,
            currentValue,
            currentStep,
            curSnProcessInfo,
            snProcessInfos,
        } = this.state;
        const {
            Nav_SN,
            Nav_TopSN,
            Nav_SplitSN,
            Nav_SNRecords
        } = SnInfo || {};
        const curSnInfoIndex = curSnProcessInfo ? curSnProcessInfo.index : 0;
        const {
            enums
        } = app || {};
        const MMSnStateEnum = enums ? enums.MMSnStateEnum : '空'; 
        const popContext = (currentPdtDetail) => {
            return (<div style={{ width: 600 }}>
                <div>
                    <span>操作者：</span>
                    <span>{currentPdtDetail.users}</span>
                </div>
                <Divider style={{ margin: "12px 0" }} />
                <div>
                    <span>工作中心:</span>
                    <span>{currentPdtDetail.workStageName}</span>
                </div>
                <Divider style={{ margin: "12px 0" }} />
                <div>
                    <span>完成时间：</span>
                    <span>{currentPdtDetail.endTime}</span>
                </div>
            </div>);
        }; 

        const customDot = (dot, { status, index }) => (
            <Popover
                content={
                    <React.Fragment>
                        <div>
                            <span>操作者：</span>
                            <span>{snProcessInfos[index].users}</span>
                        </div>
                        <Divider style={{ margin: "12px 0" }} />
                        <div>
                            <span>工作中心:</span>
                            <span>{snProcessInfos[index].workStageName}</span>
                        </div>
                        <Divider style={{ margin: "12px 0" }} />
                        <div>
                            <span>完成时间：</span>
                            <span>{snProcessInfos[index] && snProcessInfos[index].endTime}</span>
                        </div>
                    </React.Fragment>
                }
            >
                {dot}
            </Popover>
        )

        return (

            <React.Fragment>

                <Row gutter={16} style={{ lineHeight: "32px" }}>
                    <Col span={3} style={{ textAlign: "right", fontSize: 16 }}>SN：</Col>
                    <Col span={16}>
                        <Input
                            placeholder="请输入或者扫描SN码"
                            size="large"
                            // eslint-disable-next-line no-return-assign
                            ref={e => (this.refInput = e)}
                            style={{ width: '50%' }}
                            value={currentValue}
                            onChange={e => this.setState({ currentValue: e.target.value })}
                            onPressEnter={e => this.handleFormSearch(e.target.value)}
                        />


                    </Col>
                    <Col>
                        {<Checkbox size="large" onChange={this.checkOnchange}>整机</Checkbox>}
                        <Button
                            size="large"
                            type="primary"
                            style={{ marginLeft: 10 }}
                            onClick={() => this.handleFormSearch(currentValue)}
                        > 搜索</Button>
                    </Col>
                </Row>
                <div style={{ marginTop: 16 }}>
                    <Collapse defaultActiveKey={['1']} style={{ marginBottom: 15 }}>
                        <Panel header="基础信息" key="1">
                            <Edit id={Nav_SN && Nav_SN.ID} formCode={'MM027'} data={{ isShow: true }} ></Edit>
                        </Panel>
                    </Collapse>
                    <Collapse defaultActiveKey={['1']} style={{ marginBottom: 15 }}>
                        <Panel header="生产进度" key="1">
                            <Row gutter={16}>
                                {
                                    snProcessInfos.length > 0
                                        ? snProcessInfos.map(item => {
                                            return <Col key={item.ID} xs={2} sm={4}>
                                                <Popover placement="topLeft" content={popContext(item)} title={item.title} arrowPointAtCenter>
                                                    <div onClick={() => this.handleProcedureDetail(item, true)} className={styles.procedureItem}>  <Progress type="circle" width={80} percent={item.status === 'finish' ? 100 : 0} />
                                                        <div>{item.title}</div>
                                                    </div> </Popover>
                                            </Col>
                                        })
                                        : <div className={styles.emptyProcedureData}>暂无数据</div>
                                }
                            </Row>
                        </Panel>
                    </Collapse>
                    <Collapse defaultActiveKey={['recordView']}>
                        <Panel header="生产详情" key="recordView">
                            <SnSearchTable {...this.props} isLoading={this.state.isLoading} formCode={'MM019'}
                                sn={SnInfo} regLoadAllData={(ref)=>this.regLoadAllData=ref}
                                formData={this.state.formData}/>
                        </Panel>
                    </Collapse>
                </div>
            </React.Fragment>
        );
    }
}

export default connect(({ login, app }) => ({ login, app }))(SnSearch);
