import React from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Affix, Select,Checkbox,Modal,Transfer,Spin,Card,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';
import {Tabs} from "antd/lib/index";
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TabPane = Tabs.TabPane;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
const Step = Steps.Step;
const dateFormat = 'YYYY/MM/DD';
//计划排产
class BatchSchedulingPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tableList:[],
      param:{},
      loadFunc:{},
      clearRowFunc:{},
      searchRules:{},
      dafaultDateRange:[],
      selectRowKeys:{}
    };
  };

  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.props.app.handleSearch()
                    this.setState({
                      tableList: ret,
                    });
                  }
                }
              });
            });
          }
        }
      });
    });
  };
  pickChange=(dates,dateStr)=> {
    if(dates.length!=2)
      return;
    this.setState({
      dafaultDateRange: dates
    }, () => {
      //console.log(this.state.dafaultDateRange);
      this.loadFun("workstage");
    });
  };
  handleSearch=(value,code)=>{
    var tmpRules=this.state.searchRules;
    tmpRules[code]=value;
    this.setState({
      searchRules:tmpRules
    },()=>{
      this.loadFun(code);
      let tmpKeys=this.state.selectRowKeys;
      tmpKeys[code]='';
      this.setState({
        selectRowKeys:tmpKeys
      });
      if(this.state.clearRowFunc) {
        if (this.state.clearRowFunc[code] && typeof this.state.clearRowFunc[code] == "function") {
          this.state.clearRowFunc[code]();
        }
      }
    })
  };
  refleshData=()=>{
    this.loadFun("task");
    this.loadFun("workstage");
    this.loadFun("assign");
    this.loadFun("plan");
    //清除选择
    let tmpKeys=this.state.selectRowKeys;
    tmpKeys["task"]='';
    tmpKeys["workstage"]='';
    tmpKeys["assign"]='';
    this.setState({
      selectRowKeys:tmpKeys
    });
    if(this.state.clearRowFunc){
      if(this.state.clearRowFunc["task"]&&typeof this.state.clearRowFunc["task"]=="function"){
        this.state.clearRowFunc["task"]();
      }
      if(this.state.clearRowFunc["workstage"]&&typeof this.state.clearRowFunc["workstage"]=="function"){
        this.state.clearRowFunc["workstage"]();
      }
      if(this.state.clearRowFunc["assign"]&&typeof this.state.clearRowFunc["assign"]=="function"){
        this.state.clearRowFunc["assign"]();
      }
    }
  };
  refleshPlanData=()=>{
    //this.loadFun("task");
    //this.loadFun("workstage");
    this.loadFun("assign");
    this.loadFun("plan");
    let tmpKeys=this.state.selectRowKeys;
    tmpKeys["plan"]='';
    tmpKeys["assign"]='';
    this.setState({
      selectRowKeys:tmpKeys
    });
    //清除选择
    if(this.state.clearRowFunc){
      if(this.state.clearRowFunc["plan"]&&typeof this.state.clearRowFunc["plan"]=="function"){
        this.state.clearRowFunc["plan"]();
      }
    }
    if(this.state.clearRowFunc){
      if(this.state.clearRowFunc["assign"]&&typeof this.state.clearRowFunc["assign"]=="function"){
        this.state.clearRowFunc["assign"]();
      }
    }
  };


  rowSelectChange=(selectedRowKeys,code)=>{
    var tmp=this.state.selectRowKeys;
    tmp[code]=selectedRowKeys?selectedRowKeys.join(','):'';
    this.setState({
      selectRowKeys:tmp
    });
}
  handleLoadParam=({pageCode})=>{
    //this.searchFormRef.handleSearch();
    const param = this.state['param'];
    let tmp=param[pageCode];
    var extendRule=this.state.searchRules[pageCode];
    if(extendRule){
      const groups=extendRule.groups?extendRule.groups:[];
      const rules=extendRule.rules?extendRule.rules:[];
      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],
          }
        }
      }
    }
    if(pageCode=="workstage"){

      let customs=[
        {key: 'Parameter1', value:this.state.dafaultDateRange?this.state.dafaultDateRange[0].format():''},
        {key: 'Parameter2', value:this.state.dafaultDateRange?this.state.dafaultDateRange[1].format():''}
      ];
      tmp.data["customs"]=customs;
  }else if(pageCode=="assign"){
        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.selectRowKeys['workstage']},
          {key: 'Parameter4', value:this.state.selectRowKeys['task']}
        ];
        return this.setFuncs(tmp,func,cus);
    }else if(pageCode=="plan"){
      let func=[this.refleshPlanData];
      let cus=[];
      return this.setFuncs(tmp,func,cus);
    }
    return tmp;
  };

  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;
  };

  loadFun=(name)=>{
    if(this.state.loadFunc&&this.state.loadFunc[name]){
      this.state.loadFunc[name]({
        extendParam:{
          PageIndex: 1,
          Start:0
        }
      });
    }
  };
  handleLoadDataFunc=({loadFunc,pageCode})=>{
    const d={...this.state.loadFunc};
    d[pageCode]=loadFunc;
    this.setState({
      loadFunc:d,
    });
    this.refOfSearch && this.refOfSearch.handleSearch()
  };

  handleClearRowSelectd=({loadFunc,pageCode})=>{
    const d={...this.state.clearRowFunc};
    d[pageCode]=loadFunc;
    this.setState({
      clearRowFunc:d,
    });
  };

  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";
      }
    }
  };
  getTabPanel=(code)=>{

    let tableIndex=this.props.tableIndex;
    if(!tableIndex) {
      tableIndex = 1;
    }
    return this.state.tableList.map(item => {
      let query=false;
      if(item.CODE===code)
      {
        if (code === "task" || code === "assign" || code === "plan") {
        return (
          <div key={item.ID}>
            <Search
              onRef={ref => this.refOfSearch = ref}
              formId={this.props.formId}
              onSearch={(value)=>this.handleSearch(value,code)}
              code={code}
            />
            <ListTablePageBase
                key={item.ID}
                tableId={item.ID}
                formData={this.state.formData}
                formCode={this.state.formData?this.state.formData.CODE:''}
                onRegLoadDataFunc={this.handleLoadDataFunc}
                onRegClearSelectdRowFunc={this.handleClearRowSelectd}
                onRowSelectChange={this.rowSelectChange}
                onLoadParam={this.handleLoadParam}
                formId={this.props.formId}
                SetRowClass={this.setRowClass}
                //onClickRow={this.handleOrderRowClick}
                isQuery={query}
                //onTableData={this.onOrderTableData}
              />
          </div>
        )} else if (code === "workstage") {
          return (
            <div key={item.ID}>
              <Search
                onRef={ref => this.refOfSearch = ref}
                formId={this.props.formId}
                onSearch={(value) => this.handleSearch(value, code)}
                code={code}
              />
              <div style={{ marginBottom: 15 }}>
                <span className={styles.inputLabel}>日期:</span>
                <RangePicker
                  style={{display: "inline-block"}}
                  value={this.state.dafaultDateRange}
                  onChange={this.pickChange}
                  format={dateFormat}
                />
              </div>
              <ListTablePageBase
                key={item.ID}
                tableId={item.ID}
                formData={this.state.formData}
                formCode={this.state.formData?this.state.formData.CODE:''}
                onRegLoadDataFunc={this.handleLoadDataFunc}
                onRegClearSelectdRowFunc={this.handleClearRowSelectd}
                onLoadParam={this.handleLoadParam}
                onRowSelectChange={this.rowSelectChange}
                formId={this.props.formId}
                SetRowClass={this.setRowClass}
                //onClickRow={this.handleOrderRowClick}
                isQuery={query}
                //onTableData={this.onOrderTableData}
              />
          </div>
          )
        } else {
          return (
            <ListTablePageBase
              key={item.ID}
              tableId={item.ID}
              formData={this.state.formData}
              formCode={this.state.formData?this.state.formData.CODE:''}
              onRegLoadDataFunc={this.handleLoadDataFunc}
              onRegClearSelectdRowFunc={this.handleClearRowSelectd}
              onLoadParam={this.handleLoadParam}
              formId={this.props.formId}
              SetRowClass={this.setRowClass}
              onClickRow={this.handleOrderRowClick}
              onRowSelectChange={this.rowSelectChange}
              isQuery={true}
              onTableData={this.onOrderTableData}
            />
          )
        }
      } else {
        return null
      }
    });
  }

  render() {
    const tabListNoTitle = [{
      key: 'task',
      tab: this.state.selectRowKeys['task']?<span><Icon type="check" />1.计划任务</span>:<span><Icon type="exclamation-circle" />1.计划任务</span>,
    }, {
      key: 'workstage',
      tab: this.state.selectRowKeys['workstage']?<span><Icon type="check" />2.选择中心</span>:<span><Icon type="exclamation-circle" />2.选择中心</span>,
    }, {
      key: 'assign',
      tab: this.state.selectRowKeys['assign']?<span><Icon type="check" />3.分配详情</span>:<span><Icon type="exclamation-circle" />3.分配详情</span>,
    }, {
      key: 'plan',
      tab: this.state.selectRowKeys['plan']?<span><Icon type="check" />4.计划详情</span>:<span><Icon type="exclamation-circle" />4.计划详情</span>,
    }];
    const contentListNoTitle = {
      task:  this.getTabPanel('task'),
      workstage: this.getTabPanel('workstage'),
      assign: this.getTabPanel('assign'),
      plan: this.getTabPanel('plan')
    };


    return (
      <div style={{ marginTop: 16 }}>
        <Card>
          <Tabs defaultActiveKey={tabListNoTitle[0].key} >
            {tabListNoTitle.map(item => <TabPane tab={item.tab} key={item.key}>{contentListNoTitle[item.key]}</TabPane>)}
          </Tabs>
        </Card>
      </div>
    );
  }

}

BatchSchedulingPage.propTypes = {
};

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