import React from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Affix, Select,Checkbox,Modal,Transfer,Spin,Table,Radio,InputNumber,DatePicker,Steps,Icon,Divider  } from 'antd';
import {extend, extendRule, initFilter, initQueryFilter,getOnlyPropertyData,empty} from "../../../utils/common";
import ListTablePageBase from '../../Table/ListTablePageBase';
import { Search } from '@woowalker/feui'
import DropDownPagination from '../../common/DropDownPaginationEx';
import styles from './PlanningSchedulingPage.css';
import moment from 'moment';
const Option = Select.Option;
const RadioGroup = Radio.Group;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
const Step = Steps.Step;
const dateFormat = 'YYYY/MM/DD';
const DefaultPlanDay=2;//默认排产3天
//计划排产
class PlanningSchedulingPage extends React.Component {
  constructor(props) {
    //let assignQty=0;
    let advFilter={};
    let guidEmpty='00000000-0000-0000-0000-000000000000';
    super(props);
    this.state = {
      top: 80,
      tableList: [],
      formData:{},
      param:{},
      filterList:[],
      data:[],
      editList:[],
      dafaultDateRange:[],
      loadFunc:{},
      selectOrder:'',
      selectStage:'',
      // planQty:'',
      unplanQty:0,
      assignQty:0,
      selectOrderId:'',
      orderProcedureId:'',
      stageProcedureId:'',
      selectStageId:'',
      selectOrderRecord:{},
      selectStageRecord:{},
      orderFinsh:'wait',
      orderTitle:'选择生产订单',
      stageFinsh:'wait',
      stageTitle:'选择中心',
      planFinsh:'wait',
      planTitle:'分配数量',
      orderTableData:{},
      assignSelectKeys:[],
      releaseSelectKeys:[],
      onSelectStageName:'',
      searchRules:{},
    };
  };

  componentDidMount() {
    this.loadData();
  }

  loadData = () => {
    const {formId} = this.props;
    const orgId = this.props.login.OrgId;
    this.setState({
      dafaultDateRange:[moment(moment().add(this.props.login.baseConfig.PLAN_DEFAULT_START,"days"),dateFormat),
        moment(moment().add(this.props.login.baseConfig.PLAN_DEFAULT_END,"days"),dateFormat)]
    },()=>{
      const OJson = {'Key':formId,'orgid':orgId};
        //extendRule(OJson, 'CODE', 1, formCode);
        this.props.dispatch({
          type: 'app/getFormByRedis',
        payload: OJson,
        onComplete: (ret) => {
          if (ret) {
            this.setState({
              formData: ret
            },()=>{
              let val = initQueryFilter(orgId, 1, 100, "NUM", 0);
              extendRule(val, "PAGE_FORM_ID", 1, ret.ID);
              extendRule(val, "PARENT_ID", 1, null);
              this.props.dispatch({
                type: 'listPage/getTableListData',
                payload: val,
                onComplete: (ret) => {
                  if (ret !== null) {
                    this.setState({
                      tableList: ret,
                    });
                  }
                }
              });


              let json1 = initQueryFilter(orgId, 1, 100, "NUM", 0);
              extendRule(json1, "PAGE_FORM_ID", 1, ret.ID);
              this.props.dispatch({
                type: 'app/getDataByPost',
                url:'PF/PageEdit/OrderEntities',
                payload: json1,
                onComplete: (ret) => {
                  this.setState({
                    editList: ret
                  })
                }
              });
            });
          }
        }
      });
    });
  };

  onOrderTableData=(tableData,tableCode)=>{
    let tmp={...this.state.orderTableData};
    if(tableCode=="order"){
      tableData.forEach(item=>{
        if(item.ID==this.state.selectOrderId){
          item["selected"]=true;
          let unassign=item.QTY-item.ASSIGN_QTY;
          this.setState({
            unplanQty:unassign,
            assignQty:unassign
          });
        }else{
          item["selected"]=false;
        }
      });
    }else if(tableCode=="stage"){
      tableData.forEach(item=>{
        if(item.ID==this.state.selectStageId){
          item["selected"]=true;
      }else{
          item["selected"]=false;
      }
    });
    }
    tmp[tableCode]=tableData;
    this.setState({
      orderTableData:tmp
    });
  };

  getSearchComponent=(code)=> {
    return <Search onRef={ref => this.refOfSearch = ref} formId={this.props.formId} onSearch={(value)=>this.handleSearch(value,code)} code={code} />
  };

  getListComponent=(code)=> {
    let tableIndex = this.props.tableIndex;
    if(!tableIndex) {
      tableIndex = 1;
    }
   return this.state.tableList.map(item => {
     let query = true;
     if (code === "work" || code === "stagework"||code==="order") { query = false }
     if(item.CODE === code) {
       if (item.CODE ==="order")
       {
         return (<ListTablePageBase
             // key="ID"
             tableId={item.ID}
             formData={this.state.formData}
             formCode={this.state.formData?this.state.formData.CODE:''}
             onRegLoadDataFunc={this.handleLoadDataFunc}
             onLoadParam={this.handleLoadParam}
             formId={this.props.formId}
             SetRowClass={this.setRowClass}
             onClickRow={this.handleOrderRowClick}
             isQuery={query}
             onTableData={this.onOrderTableData}/>)
       }else if(item.CODE==="stage"){
         return  (<ListTablePageBase
             // key="ID"
             tableId={item.ID}
             formData={this.state.formData}
             formCode={this.state.formData?this.state.formData.CODE:''}
             onRegLoadDataFunc={this.handleLoadDataFunc}
             onLoadParam={this.handleLoadParam}
             formId={this.props.formId}
             SetRowClass={this.setRowClass}
             onClickRow={this.handleOrderRowClick}
             isQuery={query}
             onTableData={this.onOrderTableData} />)
       }
       else{
         return (<ListTablePageBase
             // key="ID"
             tableId={item.ID}
             formData={this.state.formData}
             formCode={this.state.formData?this.state.formData.CODE:''}
             onRegLoadDataFunc={this.handleLoadDataFunc}
             onLoadParam={this.handleLoadParam}
             isQuery={query}
             onRowSelectChange={this.assignSelectChange}/>)
       }
     } else {
       return null
     }
    });

  };
  handleSearch=(value,code)=>{
    this.setState({
      searchRules:value
    },()=>{
      this.loadFun("order");
    })
  };
  handleLoadDataFunc=({loadFunc,pageCode})=>{
    const d={...this.state.loadFunc};
    d[pageCode]=loadFunc;
    this.setState({
      loadFunc:d,
    },()=>{
      if(pageCode=='order'){
        this.refOfSearch && this.refOfSearch.handleSearch()
      }
    });
  };

  refleshData=()=>{
    this.loadFun("order");
    this.loadFun("stage");
    this.loadFun("assign");
    this.loadFun("norelease");
  };
  refleshPlanData=()=>{
    this.loadFun("stagework");
    this.loadFun("work");
    this.loadFun("assign");
    this.loadFun("norelease");
  };
  refleshWorkData=()=>{
    this.loadFun("work");
    this.loadFun("stage");
  };

  handleLoadParam=({pageCode})=>{
    //this.searchFormRef.handleSearch();
    const param = this.state['param'];
    if(param){
      //生产中心
      if (pageCode === "stage") {
        let tmp=param[pageCode];
        let customs=[
          {key: 'Parameter1', value:this.state.dafaultDateRange?this.state.dafaultDateRange[0].format():''},
          {key: 'Parameter2', value:this.state.dafaultDateRange?this.state.dafaultDateRange[1].format():''}
        ];
        let fun=[];
        return this.setFuncs(tmp,fun,customs);
      }
      if (pageCode === "assign") {
        let tmp=param[pageCode];
        let func=[this.refleshData];
        let cus=[
          {key: 'Keyword', value:this.state.assignQty},
          {key: 'Parameter1', value:this.state.dafaultDateRange?this.state.dafaultDateRange[0].format():''},
          {key: 'Parameter2', value:this.state.dafaultDateRange?this.state.dafaultDateRange[1].format():''},
          {key: 'Parameter3', value:this.state.selectStageId},
          {key: 'Parameter4', value:this.state.selectOrderId}
        ];
        return this.setFuncs(tmp,func,cus);
      }

      if (pageCode === "norelease") {
        let tmp=param[pageCode];
        let func=[this.refleshPlanData];
        let cus=[];
        return this.setFuncs(tmp,func,cus);
      }
      if (pageCode === "work") {
        let tmp=param[pageCode];
        let func=[this.refleshWorkData];
        let cus=[];
        return this.setFuncs(tmp,func,cus);
      }
      if (pageCode === "order") {
        let tmp=param[pageCode];
        const rules=this.state.searchRules&&this.state.searchRules.rules?this.state.searchRules.rules:[];
        const groups=this.state.searchRules&&this.state.searchRules.groups?this.state.searchRules.groups:[];
        if(tmp){
          if(tmp.data){
            tmp.data["rules"]=[...tmp.data["rules"],...rules];
            tmp.data["groups"]=[...tmp.data["groups"],...groups];
          }else{
            tmp["data"]={
              rules:[...rules],
              groups:[...groups],
            }
          }
        }else{
          tmp={
            data:{
              rules:[...rules],
              groups:[...groups],
            }
          }
        }
        //console.log(tmp);
        return  tmp;
      }
      //查询条件的参数
      // if(!param[pageCode])
      //   param[pageCode]={data:{filter:{...this.advFilter}}};
      // else
      //   param[pageCode].data["filter"]={...this.advFilter};
    }
    return param[pageCode];
  };

  setFuncs=(tmp,func,cus)=>{
    if(tmp){
      if(tmp.data){
        tmp.data["func"]=[...func];
        tmp.data["customs"]=cus;
      }else{
        tmp["data"]={
          func:[...func],
          customs:cus
        }
      }
    }else{
      tmp={
        data:{
          func:[...func],
          customs:cus
        }
      }
    }
    return tmp;
  };
  setRowClass=(record)=>{
    if(record["selected"]){
      return "selected";
    }else{
      var rate=Number(record["OccRadio"]);
      if(rate>=0.8&&rate<1){
        return "warning";
      }
      if(rate>=1)
      {
        return "danger";
      }
    }
  };

  handleOrderRowClick=({record,pageCode})=>{
    if(pageCode==="order")
      {
        const tmp={...this.state.param};
         let selectId=this.state.selectOrderId==record.ID?this.guidEmpty:record.ID;
         let selectProcedureId=this.state.selectOrderId==record.ID?this.guidEmpty:record.Nav_PdtProcessDetail.PROCEDURE_ID;
         let order=this.state.selectOrderId==record.ID?'':record.Nav_PdtOrder.PDT_CODE+":"+record.Nav_PdtProcessDetail.NAME;
         let upplan=this.state.selectOrderId==record.ID?0:(record.QTY-record.ASSIGN_QTY);
         //let processDetailType=this.state.selectOrderId==record.ID?'99':record.Nav_PdtProcessDetail.PRO_TYPE;
         let orderSetpTitle=this.state.selectOrderId==record.ID?"选择生产工单":"生产工单：["+order+"]";
         let orderSetp=this.state.selectOrderId==record.ID?"wait":"finish";
         let selectRecord=record;
         if(selectId!=record.ID){
           selectRecord={};
         }
        tmp['work']= {
          data: {
            rules: [{field: 'PLAN_TASK_ID', operator: 1, value: selectId}],
          }
        };
        //过滤生产中心
        let isUpdateStage=false;
        if(this.state.orderProcedureId!=selectProcedureId)
        {
          isUpdateStage=true;
          if(selectProcedureId!=this.guidEmpty)
          {
              //根据工序过滤
              tmp['stage']={
                data: {
                  rules: [{field: 'PROCEDURE_ID', operator: 1, value:selectProcedureId}],
                }
              }
          }else {
            tmp['stage'] = {
              data: {
                rules: [],
              }
            }
          }
        }
        this.setSelected(selectId,pageCode);
        //this.assignQty=upplan;
        this.setState({
          param:tmp,
          selectOrder:order,
          selectOrderId:selectId,
          orderProcedureId:selectProcedureId,
          unplanQty:upplan,
          assignQty:upplan,
          orderFinsh:orderSetp,
          orderTitle:orderSetpTitle,
          selectOrderRecord:selectRecord,
        },()=>{
          this.loadFun("work");
          //工序变更后需要更新生产中心数据
          if(isUpdateStage)
          {
            this.loadFun("stage");
          }
        });
      }

    if (pageCode === "stage") {
      let selectStageId=this.state.selectStageId==record.ID?this.guidEmpty:record.ID;
      let selectProcedureId=this.state.selectStageId==record.ID?this.guidEmpty:record.PROCEDURE_ID;
      //let selectType=this.state.selectStageId==record.ID?'99':record.TYPE;
      let stage=this.state.selectStageId==record.ID?'':record.CODE+"/"+record.NAME;
      let stageSetpTitle=this.state.selectStageId==record.ID?"选择中心":"中心：["+stage+"]";
      let stageSetp=this.state.selectStageId==record.ID?"wait":"finish";
      let selectRecord=record;
      if(selectStageId!=record.ID){
        selectRecord={};
      }
      this.setState({
        onSelectStageName:stage,
        selectStageRecord:selectRecord,
      });
      this.selectStageFunc(selectStageId,selectProcedureId,stage,stageSetpTitle,stageSetp,pageCode);

    }

  };
  setSelected=(selectId,pageCode)=>{
    var tmpData=this.state.orderTableData;
    var data=tmpData[pageCode];
    if(data){
      data.forEach((n,i)=>{
        if(n.ID==selectId){
          n["selected"]=true;
        }else{
          n["selected"]=false;
        }
      })
    }
    this.setState({
      orderTableData:tmpData
    });
  };
  selectStageFunc=(selectStageId,selectProcedureId,stage,stageSetpTitle,stageSetp,pageCode)=>{
    const tmp={...this.state.param};
    let isUpdateOrder=false;
    if(this.state.stageProcedureId!=selectProcedureId){
      isUpdateOrder=true;
      if(selectProcedureId!=this.guidEmpty){
        tmp['order']={
          data: {
            rules: [{field: 'Nav_PdtProcessDetail.PROCEDURE_ID', operator: 1, value:selectProcedureId}],
          }
        }
      }else {
        tmp['order'] = {
          data: {
            rules: [],
          }
        }
      }
    }
    tmp['stagework']= {
      data: {
        rules: [{field: 'PLAN_WORKSTAGE_ID', operator: 1, value:selectStageId}],
      }
    };
    this.setState({
      param:tmp,
      selectStageId:selectStageId,
      stageProcedureId:selectProcedureId,
      selectStage:stage,
      stageFinsh:stageSetp,
      stageTitle:stageSetpTitle
    },()=>{
      this.setSelected(selectStageId,pageCode);
      this.loadFun("stagework");
      if(isUpdateOrder)
      {
        this.loadFun("order");
      }
    });
};
  loadFun=(name)=>{
    if(this.state.loadFunc&&this.state.loadFunc[name]){
      this.state.loadFunc[name]({
        extendParam:{
          PageIndex: 1,
          Start:0
        }
      });
    }
  };

  pickChange=(dates,dateStr)=> {
    if(dates.length!=2)
      return;
    this.setState({
      dafaultDateRange: dates
    }, () => {
      //console.log(this.state.dafaultDateRange);
      this.loadFun("stage");
    });
  };
  cancelSelectdOrder=()=>{
    if(this.state.selectOrderRecord)
    {
      let params={record:this.state.selectOrderRecord,pageCode:'order'}
      this.handleOrderRowClick(params);
    }

}

  cancelSelectdStage=()=>{
    if(this.state.selectStageRecord)
    {
      let params={record:this.state.selectStageRecord,pageCode:'stage'}
      this.handleOrderRowClick(params);
    }

  }
  assignQtyChange=(value)=>{
    if(value>this.state.unplanQty){
        this.setState({
          assignQty:this.state.unplanQty
        })
    }else{
      this.setState({
        assignQty:value
      })
    }
  };
  onSelectStage = ({data}) => {
    //console.log(data);
    //id,code,name,procedure_id
    if (data && data.length > 0) {
      let selectStageId=data[0];
      let selectProcedureId=data[3];
      let stage=data[1]+"/"+data[2];
      let stageSetpTitle="中心：["+stage+"]";
      let stageSetp="finish";
      this.selectStageFunc(selectStageId,selectProcedureId,stage,stageSetpTitle,stageSetp,"stage");
      this.setState({
        onSelectStageName:stage
      });
    }
  };

  assignSelectChange=(selectedRowKeys,code)=>{
    if(code === "assign"){
         this.setState({
           assignSelectKeys:selectedRowKeys,
         })
    }
    if(code === "norelease"){
      this.setState({
        releaseSelectKeys:selectedRowKeys,
      })
    }
  };
  render() {
    let tableIndex=this.props.tableIndex;
    if(!tableIndex) {
      tableIndex = 1;
    }
    const colIsShowCheck = (text, record, index) => {
      if (record.SHOW_CHECK)
        return '是';
      return '否';
    };
    const colOp = (text, record, index) => {
      if (record.SHOW_CHECK)
        return '是';
      return '否';
    };

    const columns = [
      {title: '生产订单', dataIndex: 'PDT_ORDER_CODE', key: 'PDT_ORDER_CODE'},
      {title: '中心', dataIndex: 'WORKSTAGE_NAME', key: 'WORKSTAGE_NAME'},
      {title: '日期', dataIndex: 'DATETIME', key: 'DATETIME'},
      {title: '班次', dataIndex: 'CLASS', key: 'CLASS'},
      {title: '数量', dataIndex: 'QTY', key: 'QTY', render: colIsShowCheck},
      {title: '负荷', dataIndex: 'API_URL', key: 'API_URL'},
      {title: '操作', dataIndex: '', key: '',render:colOp},
    ];

    return (
      <div className={styles.planningPage}>
        <Affix offsetTop={10} target={() => document.querySelector('.ant-layout-content')}>
          <Row>
            <Col span={20} push={2}>
              <div className={styles.affixStyle}>
                <Steps>
                  <Step status={this.state.orderFinsh} title={this.state.orderTitle}/>
                  <Step status={this.state.stageFinsh} title={this.state.stageTitle} />
                  <Step status={this.state.planFinsh} title={this.state.planTitle}/>
                </Steps>
              </div>
            </Col>
          </Row>
        </Affix>
        <Divider orientation="left">生产订单</Divider>
        <div style={{ marginBottom: 15 }}>
          {this.getSearchComponent('Search')}
        </div>
        <Row gutter={16}>
          <Col span={16}>
            <Button type={'default'} icon={'rollback'}  title={'取消选择'}
                    disabled={empty(this.state.selectOrderRecord)} onClick={this.cancelSelectdOrder}>取消选择</Button>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={16}>
            <RadioGroup name="radioOrder" value={this.state.selectOrderId} disabled={true} style={{width: "100%"}}>
              <div className={styles.tableWrap}>

                {this.getListComponent('order')}
              </div>
            </RadioGroup>
          </Col>
          <Col span={8}>
            <div className={styles.tableWrap}>
              {this.getListComponent('work')}
            </div>
          </Col>
        </Row>
        <Divider orientation="left">中心</Divider>
        <div style={{ marginBottom: 15 }}>
          <span className={styles.inputLabel}>中心：</span>
          <div style={{ display: "inline-block" }}>
            <DropDownPagination
              inputDataApi={'FM/WorkStage/OrderPaged'}
              inputLabelField={'NAME'}
              inputShowField={'CODE,NAME'}
              inputFilterField={'CODE,NAME'}
              value={this.state.onSelectStageName}
              onSelect={this.onSelectStage}
              inpuNavField={'ID,CODE,NAME,PROCEDURE_ID'}/>
          </div>
        </div>
        <Row gutter={16}>
          <Col span={16}>
            <Button type={'default'} icon={'rollback'}  title={'取消选择'}
                    disabled={empty(this.state.selectStageRecord)} onClick={this.cancelSelectdStage}>取消选择</Button>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={16}>
            <RadioGroup name="radioStage" value={this.state.selectStageId} disabled={true} style={{width:"100%"}}>
              <div className={styles.tableWrap}>

                {this.getListComponent('stage')}
              </div>
            </RadioGroup>
          </Col>
          <Col span={8}>
            <div className={styles.tableWrap}>
              {this.getListComponent('stagework')}
            </div>
          </Col>
        </Row>
        <Divider orientation="left">分配数量</Divider>
        <Row gutter={16} style={{ marginBottom: 15 }}>
          <Col xs={24} sm={24} md={10} lg={8} style={{ marginBottom: 10 }}>
            <span className={styles.inputLabel}>日期:</span>
            <RangePicker style={{ display: "inline-block" }} value={this.state.dafaultDateRange} onChange={this.pickChange} format={dateFormat}/>
          </Col>
          <Col xs={12} sm={12} md={5} lg={4} style={{ marginBottom: 10 }}>
            <span className={styles.inputLabel}>未分:</span>
            <InputNumber  value={this.state.unplanQty}   disabled={true} />
          </Col>
          <Col xs={12} sm={12} md={5} lg={4} style={{ marginBottom: 10 }}>
            <span className={styles.inputLabel}>分配:</span>
            <InputNumber  value={this.state.assignQty} onChange={this.assignQtyChange}  max={this.state.unplanQty} min={0} disabled={false} />
            {/*<Button type="primary" icon="down-square" disabled={!this.state.selectStageId||!this.state.selectOrderId}  onClick={this.AutoAssign}>自动分配</Button>*/}
            {/*<Button icon="right-square" onClick={this.genPlan} disabled={!this.state.assignSelectKeys.length}>生成计划</Button>*/}
          </Col>
          {/*<Col span={4}>*/}
          {/*当前：<InputNumber  value={this.state.planQty}  disabled={true} />*/}
          {/*</Col>*/}
          {/*<Button icon="right-square" onClick={this.releasePlan} disabled={!this.state.releaseSelectKeys.length}>发布计划</Button>*/}
          {/*<Col span={8}>*/}
          {/*<Button icon="right-square" onClick={this.releasePlan} disabled={!this.state.releaseSelectKeys.length}>发布计划</Button>*/}
          {/*</Col>*/}
        </Row>
        <Row gutter={16} justify="space-around">
          <Col span={16}>
            {/*<Table columns={columns} dataSource={this.state.data} pagination={false}   scroll={{ x: 800}}/>*/}
            <div className={styles.tableWrap}>
              {this.getListComponent('assign')}
            </div>
          </Col>
          <Col span={8}>
            <div className={styles.tableWrap}>
              {this.getListComponent('norelease')}
            </div>
          </Col>
        </Row>
        <div>
          {
            (()=>{
              if(this.state.editList&&this.state.editList.length) {
                // return this.state.editList.map(item => {
                //     return <Edit dataField={{
                //       ...this.props,
                //       formCode: this.state.formCode,
                //       id: this.state.selectedKeys,
                //       onSave: this.loadTreeData,
                //       parentId:this.state.parentId,
                //       isAdd:this.state.isAdd
                //     }} />
                // });
              }
            })()
          }
        </div>
      </div>
    );
  }

}

PlanningSchedulingPage.propTypes = {
};

export default connect(({ login, loading }) => ({ login, loading }))(PlanningSchedulingPage);
