/* eslint-disable array-callback-return,no-undef,object-curly-newline,prefer-destructuring,no-unused-vars */
import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import { LoadingOutlined } from '@ant-design/icons';
import { Modal, Layout, Spin, Card, Row, Col, message } from 'antd-v4'; // Switch Select, Tabs,
import styles from '@/index.less';
import selfstyles from '@/components/productionMainPlan/index.less';
import * as commonFunc from '@/components/Common/commonFunc';
import CommonBase from '@/components/Common/CommonBase';
import * as commonBusiness from '@/components/Common/commonBusiness';/* 单据业务功能 */
import StaticEditTable from '@/components/Common/CommonTable';/* 可编辑表格 */
import CommonProductionPlanEvent from '@/components/Common/CommonProductionPlanEvent';
import Toolbar from '@/components/Common/ToolBar/ToolBarNew';
import MoveUp from '@/assets/processUp.svg';
import MoveDown from '@/assets/processDown.svg';
import DisableMoveUp from '@/assets/disableprocessUp.svg';
import DisableMoveDown from '@/assets/disableprocessDown.svg';
import MoveTop from '@/assets/processTop.svg';
import DisableMoveTop from '@/assets/disableprocessTop.svg';
import MoveBottom from '@/assets/processBottom.svg';
import DisableMoveBottom from '@/assets/disableprocessBottom.svg';
import ChangeMachine from '@/assets/changeMachine.svg';
import DisableChangeMachine from '@/assets/disablechangeMachine.svg';
import ShowGantt from '@/assets/gantt.svg';
import DisableShowGantt from '@/assets/disablegantt.svg';
import ShowCheckModel from '@/assets/checkModel.svg';
import DisableShowCheckModel from '@/assets/disablecheckModel.svg';
import ShowTimer from '@/assets/timer.svg';
import DisableShowTimer from '@/assets/disabletimer.svg';
import ShowList from '@/assets/list.svg';
import DisableShowList from '@/assets/disablelist.svg';
import Reset from '@/assets/reset.svg';
import DisableReset from '@/assets/disablereset.svg';
import * as commonUtils from '@/utils/utils';
import ShowType from '@/components/Common/CommonComponent';
import commonConfig from '@/utils/config';
import AntdDraggableModal from '@/components/Common/AntdDraggableModal';
import * as commonServices from '@/services/services';
import Gantt from '@/components/Charts/Gantt';
import MessageArea from '@/components/Charts/Gantt/MessageArea/Message';
import CommonListSelect from '@/components/Common/CommonListSelect';
import GanttStyles from './index.less';

const { Header, Content, Sider } = Layout;

class ProductionSchedule extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isRender: 0,
      checkModelStatus: false,
    };
    this.form = {}; /*   表单对象   */
  }

  shouldComponentUpdate(nextProps) {
    const { slaveColumn, masterConfig } = nextProps;
    return commonUtils.isNotEmptyArr(slaveColumn) || commonUtils.isNotEmptyObject(masterConfig);
  }
  // onRowMouseEnter = (name, record) => {
  //   console.log('record:', record);
  // }
  onDoubleClick = (name, record) => {
    if (this.props.onDoubleClick !== undefined) {
      this.props.onDoubleClick(record);
    }
  };
  onRowClick = (name, record, bRowClick) => {
    const { slaveData } = this.props;
    let { slaveSelectedRowKeys, slaveInfoSelectedRowKeys } = this.props;
    slaveInfoSelectedRowKeys = commonUtils.isNotEmptyArr(slaveInfoSelectedRowKeys) ? slaveInfoSelectedRowKeys : [];
    if (name === 'slave') {
      if (commonUtils.isEmptyArr(slaveSelectedRowKeys)) {
        const keys = [];
        keys.push(record.sSlaveId);
        slaveSelectedRowKeys = keys;
        const sIds = record.sSlaveId.split('-');
        slaveInfoSelectedRowKeys.push(...sIds);
      } else {
        const indexKey = slaveSelectedRowKeys.indexOf(record.sSlaveId);
        if (indexKey === -1) {
          slaveSelectedRowKeys.push(record.sSlaveId);
          const sIds = record.sSlaveId.split('-');
          slaveInfoSelectedRowKeys.push(...sIds);
          sIds.forEach((item) => {
            const iIndex = slaveInfoSelectedRowKeys.findIndex(e => e === item);
            if (iIndex === -1) {
              slaveInfoSelectedRowKeys.push(item);
            }
          });
        } else if (indexKey !== -1) {
          if (!bRowClick) {
            slaveSelectedRowKeys.splice(indexKey, 1);
          }
          const sIds = record.sSlaveId.split('-');
          sIds.forEach((item) => {
            const index = slaveInfoSelectedRowKeys.findIndex(e => e === item);
            if (!bRowClick) {
              slaveInfoSelectedRowKeys.splice(index, 1);
            }
          });
        }
      }
    } else if (name === 'slaveInfo') {
      if (commonUtils.isEmptyArr(slaveInfoSelectedRowKeys)) {
        const keys = [];
        keys.push(record.sId);
        slaveInfoSelectedRowKeys = keys;
        const slaveDataNews = slaveData.filter(item => item.sSlaveId.split('-').includes(record.sId));
        if (commonUtils.isNotEmptyArr(slaveDataNews)) {
          slaveSelectedRowKeys = [slaveDataNews[0].sSlaveId];
        }
      } else {
        const indexKey = slaveInfoSelectedRowKeys.indexOf(record.sId);
        if (indexKey === -1) {
          slaveInfoSelectedRowKeys.push(record.sId);
          const slaveDataNews = slaveData.filter(item => item.sSlaveId.split('-').includes(record.sId));
          if (commonUtils.isNotEmptyArr(slaveDataNews)) {
            const iIndex = slaveSelectedRowKeys.findIndex(item => item === slaveDataNews[0].sSlaveId);
            if (iIndex === -1) {
              slaveSelectedRowKeys.push(slaveDataNews[0].sSlaveId);
            }
          }
        } else if (indexKey !== -1) {
          /* 可输入行，行内点击时 不去除selectedRowKeys */
          if (!bRowClick) {
            slaveInfoSelectedRowKeys.splice(indexKey, 1);
          }
          const slaveDataNews = slaveData.filter(item => item.sSlaveId.split('-').includes(record.sId));
          if (commonUtils.isNotEmptyArr(slaveDataNews)) {
            const sSlaveIds = slaveDataNews[0].sSlaveId.split('-');
            if (slaveInfoSelectedRowKeys.length === 0 || sSlaveIds.length === 1) {
              const iIndex = slaveSelectedRowKeys.indexOf(item => slaveDataNew[0].sSlaveId === item);
              if (!bRowClick) {
                slaveSelectedRowKeys.splice(iIndex, 1);
              }
            } else {
              let bdel = true;
              for (const sId of sSlaveIds) {
                if (slaveInfoSelectedRowKeys.findIndex(item => item === sId && item !== record.sId)) {
                  bdel = false;
                  break;
                }
              }
              if (bdel) {
                const iIndex = slaveSelectedRowKeys.indexOf(item => slaveDataNew[0].sSlaveId === item);
                if (!bRowClick) {
                  slaveSelectedRowKeys.splice(iIndex, 1);
                }
              }
            }
          }
        }
      }
    }
    let machineEnabled = false;
    if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
      const currSlave = slaveData.filter(item => item.sSlaveId === slaveSelectedRowKeys[0])[0];
      const processSlave = slaveData.filter(item => item.sProcessId === currSlave.sProcessId && slaveSelectedRowKeys.includes(item.sSlaveId));
      if (processSlave.length === slaveSelectedRowKeys.length) {
        machineEnabled = true;
      }
    }
    const { sModelsId } = this.props;
    commonUtils.setStoreDropDownData(sModelsId, 'master', 'sMachineId', []);
    this.props.onSaveState({ slaveSelectedRowKeys, slaveInfoSelectedRowKeys, machineEnabled });
  };
  onCloseChangeMachine = () => {
    const { masterData } = this.props;
    delete masterData.tStartDate;
    delete masterData.iSplitNum;
    delete masterData.bSplit;
    this.props.onSaveState({ isChangeMachine: false, masterData: { ...masterData, sMachineId: '', sTeamId: '' } });
  }
  onTableSelectRowChange = (name, selectedRowKeys) => {
    if (name === 'slave') {
      const addState = this.props.onTableSelectRowChange(name, selectedRowKeys, true);
      const slaveInfoSelectedRowKeys = [];
      if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
        selectedRowKeys.forEach((selectedRow) => {
          const sIds = selectedRow.split('-');
          slaveInfoSelectedRowKeys.push(...sIds);
        });
      }
      addState.slaveInfoSelectedRowKeys = slaveInfoSelectedRowKeys;
      this.props.onSaveState({ ...addState });
    } else {
      this.props.onTableSelectRowChange(name, selectedRowKeys);
    }
    // let record = {};
    // let key;
    // if (name === 'slave') {
    //   if (commonUtils.isNotEmptyArr(selectedRowKeys) && commonUtils.isEmptyArr(slaveSelectedRowKeys) && selectedRowKeys.length === 1) {
    //     key = selectedRowKeys[0];
    //   } else if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys) && commonUtils.isEmptyArr(selectedRowKeys) && slaveSelectedRowKeys.length === 1) {
    //     key = slaveSelectedRowKeys[0];
    //   } else if (commonUtils.isNotEmptyArr(selectedRowKeys) && commonUtils.isNotEmptyArr(slaveSelectedRowKeys) && selectedRowKeys.length > slaveSelectedRowKeys.length) {
    //     key = selectedRowKeys.filter(item => !slaveSelectedRowKeys.includes(item))[0];
    //   } else if (commonUtils.isNotEmptyArr(selectedRowKeys) && commonUtils.isNotEmptyArr(slaveSelectedRowKeys) && selectedRowKeys.length < slaveSelectedRowKeys.length) {
    //     key = slaveSelectedRowKeys.filter(item => !selectedRowKeys.includes(item))[0];
    //   }
    //   record = tableData.filter(item => key === item.sSlaveId)[0];
    //   this.onRowClick(name, record);
    // } else if (name === 'slaveInfo') {
    //   if (commonUtils.isNotEmptyArr(selectedRowKeys) && commonUtils.isEmptyArr(slaveInfoSelectedRowKeys) && selectedRowKeys.length === 1) {
    //     key = selectedRowKeys[0];
    //   } else if (commonUtils.isNotEmptyArr(slaveInfoSelectedRowKeys) && commonUtils.isEmptyArr(selectedRowKeys) && slaveInfoSelectedRowKeys.length === 1) {
    //     key = slaveInfoSelectedRowKeys[0];
    //   } else if (commonUtils.isNotEmptyArr(selectedRowKeys) && commonUtils.isNotEmptyArr(slaveInfoSelectedRowKeys) && selectedRowKeys.length > slaveInfoSelectedRowKeys.length) {
    //     key = selectedRowKeys.filter(item => !slaveInfoSelectedRowKeys.includes(item))[0];
    //   } else if (commonUtils.isNotEmptyArr(selectedRowKeys) && commonUtils.isNotEmptyArr(slaveInfoSelectedRowKeys) && selectedRowKeys.length < slaveInfoSelectedRowKeys.length) {
    //     key = slaveInfoSelectedRowKeys.filter(item => !selectedRowKeys.includes(item))[0];
    //   }
    //   record = tableData.filter(item => key === item.sId)[0];
    //   this.onRowClick(name, record);
    // } else {
    //   this.props.onTableSelectRowChange(name, selectedRowKeys);
    // }
  };
  /**   处理选择行发生改变   */
  handleTableFilterData = (name, data, record) => {
    /*   外置处理业务   */
    if (name === 'slave') {
      let slaveInfoDataNew = [];
      if (commonUtils.isNotEmptyArr(data)) {
        slaveInfoDataNew = data.filter(item => record.sSlaveId.split('-').includes(item.sId));
      }
      return slaveInfoDataNew;
    }
  };
  // 根据配置解析拼接具体参数
  handleProParams = (sKey, arr) => {
    const { [`${sKey}Data`]: tableData, [`${sKey}SelectedRowKeys`]: selectedRowKeys } = this.props;
    const keyData = tableData.filter(item => selectedRowKeys.includes(item.sId) || selectedRowKeys.includes(item.sSlaveId));
    if (commonUtils.isNotEmptyArr(keyData)) {
      const addState = {};
      addState.key = sKey;
      const val = [];
      keyData.forEach((currData) => {
        const currVal = {};
        arr.forEach((filed) => {
          currVal[`${filed}`] = currData[`${filed}`];
        });
        val.push(currVal);
      });
      addState.value = val;
      return addState;
    } else {
      return undefined;
    }
  };

  /* 甘特图数据改变出发事件 */
  logDataUpdate = (type, action, item, id) => {
    const { charGanttData } = this.props;
    /* 记录更新的数据 */
    if (action === 'update') {
      if (commonUtils.isNotEmptyArr(charGanttData)) {
        const { data } = charGanttData;
        if (Array.isArray(data) && data.length > 0) {
          const iIndex = data.findIndex(child => child.id === id);
          if (iIndex > -1) {
            if (commonUtils.isNotEmptyObject(item.start_date)) {
              data[iIndex].start_date = new Date(item.start_date);
            }
            if (commonUtils.isNotEmptyObject(item.end_date)) {
              data[iIndex].end_date = new Date(item.end_date);
            }
            charGanttData.tasks.data = data;
            this.props.onSaveState({ charGanttData });
          }
        }
      }
    }
    const text = item && item.text ? ` (${item.text})` : '';
    let message = `${type} ${action}: ${id} ${text}`;
    if (type === 'link' && action !== 'delete') {
      message += ` ( source: ${item.source}, target: ${item.target} )`;
    }
    this.addMessage(message);
  }
  logTaskUpdate = (id, mode, task) => {
    const text = task && task.text ? ` (${task.text})` : '';
    const message = `Task ${mode}: ${id} ${text}`;
    this.addMessage(message);
  }

  logLinkUpdate = (id, mode, link) => {
    let message = `Link ${mode}: ${id}`;
    if (link) {
      message += ` ( source: ${link.source}, target: ${link.target} )`;
      this.addMessage(message);
    }
  }
  addMessage = (message) => {
    const maxLogLength = 5;
    const newMessate = { message };
    const messages = [
    ];
    messages.push(newMessate);
    if (messages.length > maxLogLength) {
      messages.length = maxLogLength;
    }
    this.props.onSaveState({ messages });
  }
  sortData = (tempData) => {
    tempData.sort((g1, g2) => {
      return g1.iOrder - g2.iOrder;
    });
    return tempData;
  };

  /* 控制排序 */
  orderData = (e, name, type) => {
    const { [`${name}SelectedRowKeys`]: tableselectedRowKeys, app, slavePagination: slavePaginationOld } = this.props;
    let { [`${name}Data`]: currentData } = this.props;
    if (name === 'slave') {
      if (commonUtils.isEmptyArr(tableselectedRowKeys)) {
        message.warn(commonFunc.showMessage(app.commonConst, 'pleaseChooseMoveData'));/* 请勾选要移动数据 */
        return;
      }
      if (commonUtils.isEmptyArr(currentData)) {
        message.warn(commonFunc.showMessage(app.commonConst, 'NoProcessData'));/* 请填写工序表数据 */
        return;
      }
      const tempNew = currentData.filter((item) => { /* 获取勾选数据集 */
        return tableselectedRowKeys.indexOf(item.sSlaveId) > -1;
      });
      if (commonUtils.isEmptyArr(tempNew)) {
        message.warn(commonFunc.showMessage(app.commonConst, 'pleaseChooseMoveData'));/* 请选择要移动数据 */
        return;
      }
      const len = currentData.length;
      currentData = this.orderNum(currentData);
      const newLen = tempNew.length;
      let num = 0.01;/* 循环增加体 */
      let targetiOrder = -1;
      if (type === 1) { /*  上移 */
        const iIndex = currentData.findIndex(item => item.sSlaveId === tempNew[0].sSlaveId);/* 选中第一个节点的下标 */
        if (iIndex === 0) {
          if (newLen === 1) {
            message.warn(commonFunc.showMessage(app.commonConst, 'NoUp'));/* 无需上移 */
            return;
          } else {
            targetiOrder = 0;
          }
        } else if (iIndex === 1 && currentData[0].sDivRowNew) {
          message.warn(commonFunc.showMessage(app.commonConst, 'NoUp'));/* 无需上移 */
          return;
        } else {
          targetiOrder = currentData[iIndex - 1].iOrder - 1; /* 目标排序号 */
        }
      } else if (type === 2) { /*  下移 */
        const iIndex = currentData.findIndex(item => item.sSlaveId === tempNew[newLen - 1].sSlaveId);/* 选中最后一个节点的下标 */
        if (iIndex === len - 1) {
          if (newLen === 1) {
            message.warn(commonFunc.showMessage(app.commonConst, 'NoDown')); /* 无需下移 */
            return;
          } else {
            targetiOrder = currentData[iIndex].iOrder;
          }
        } else {
          targetiOrder = currentData[iIndex + 1].iOrder;
        }
      } else if (type === 0) { /*  置顶 */
        const iIndex = currentData.findIndex(item => item.sSlaveId === tempNew[0].sSlaveId);/* 选中第一个节点的下标 */
        if (iIndex === 0) {
          if (newLen === 1) {
            message.warn(commonFunc.showMessage(app.commonConst, 'NoTop')); /* 无需置顶 */
            return;
          } else {
            targetiOrder = currentData[iIndex].iOrder;
          }
        } else if (iIndex === 1 && currentData[0].sDivRowNew) {
          message.warn(commonFunc.showMessage(app.commonConst, 'NoTop'));/* 无需置顶 */
          return;
        } else if (currentData[0].sDivRowNew) { /* 如果顶层有分割 */
          targetiOrder = currentData[1].iOrder - 1;
        } else {
          targetiOrder = currentData[0].iOrder - 1;
        }
      } else if (type === 3) { /*  置底 */
        const iIndex = currentData.findIndex(item => item.sSlaveId === tempNew[newLen - 1].sSlaveId);/* 选中最后一个节点的下标 */
        if (iIndex === len - 1) {
          if (newLen === 1) {
            message.warn(commonFunc.showMessage(app.commonConst, 'NoBottom')); /* 无需置底 */
            return;
          } else {
            targetiOrder = currentData[iIndex].iOrder;
          }
        } else {
          targetiOrder = currentData[len - 1].iOrder + 1;
        }
      }
      tempNew.forEach((item) => {
        const index1 = currentData.findIndex(item1 => item1.sSlaveId === item.sSlaveId);
        currentData[index1] = { ...item, iOrder: targetiOrder + num, handleType: 'update' };
        num += 0.01;
      });
      currentData = this.sortData(currentData);
      currentData = this.orderNum(currentData);
      const iIndex = currentData.findIndex(item => item.sSlaveId === tableselectedRowKeys[0]);
      const slavePagination = { ...slavePaginationOld };
      slavePagination.current = Math.ceil((iIndex + 1) / commonConfig.pageSize);
      this.props.onSaveState({ [`${name}Data`]: currentData, slavePagination });
    } else if (name === 'slaveInfo') {
      this.props.onSaveState({ isChangeMachine: true });
    }
  };

  /* 自定义排序号 */
  orderNum = (tableData) => {
    const { slaveColumn } = this.props;
    tableData.forEach((item, index) => {
      item.iOrder = index + 1;
      item.handleType = 'update';
    });
    /* 移动后 重新计算分割间隔条数及用时逻辑 */
    const returnFilterData = tableData.filter(item => commonUtils.isNotEmptyObject(item.sDivRowNew) && item.sDivRowNew !== '');
    if (commonUtils.isNotEmptyArr(returnFilterData)) {
      returnFilterData.forEach((tableDataRow, index) => {
        /* 找到白班与晚班区间的汇总条数与工时 */
        let startIndex = 0; /* 找到开始下标 */
        let endindex = 0; /* 找到结束下标 */
        let sliceData = [];
        startIndex = tableData.findIndex(item => item.sId === returnFilterData[index].sId);
        if (index + 1 < returnFilterData.length) {
          endindex = tableData.findIndex(item => item.sId === returnFilterData[index + 1].sId);
        }
        if (index === returnFilterData.length - 1) {
          endindex = tableData.length;
        }
        if (startIndex < endindex) {
          sliceData = tableData.slice(startIndex + 1, endindex);
        }
        let num = 0;
        let dTime = 0;
        let dPlateQty = 0; /* 付版 */
        let dProcessQty = 0;
        /* 找到第二个字段 */
        if (commonUtils.isNotEmptyArr(sliceData)) {
          num = sliceData.length;
          sliceData.forEach((item) => {
            if (commonUtils.isNotEmptyNumber(item.dHour)) {
              dTime += item.dHour1;
              dPlateQty += item.dPlateQty;
              dProcessQty += item.dProcessQty;
            }
          });
          let sCount = '';
          if (num > 0) {
            sCount += `F${num}单`;
          }
          if (dProcessQty > 0) {
            sCount += ` - ${dProcessQty}`;
          }
          if (sliceData[0].sType === '1') {
            sCount += ` - ${dPlateQty}付版`;
          }
          if (dTime > 0) {
            // sCount +=  ' - ' + Math.floor(dTime/60) + ":" + (dTime%60) + '小时';
            sCount += ` - ${(dTime / 60).toFixed(2)}h`;
          }
          const sFileName = commonUtils.isNotEmptyArr(slaveColumn) && slaveColumn.length > 2 ? slaveColumn[1].dataIndex : '';
          if (sCount && sFileName) {
            const addState = {};
            addState[sFileName] = tableDataRow.sDivRowNew + sCount;
            tableData[startIndex] = { ...tableData[startIndex], ...addState };
          }
        }
      });
    }
    return tableData;
  };

  /* 切换甘特图/列表视图 */
  changeGantt = (e, type) => {
    let bGantt = false;
    if (type === 'gantt') {
      const { slaveFilterCondition } = this.props;
      bGantt = true;
      /* 调用获取甘特图数据 */
      const chart = {};
      chart.sProcedureName = 'Sp_Process_CommonGtChar';
      chart.paramsMap = {
      };
      this.props.onGanttChar(chart, slaveFilterCondition);
    } else if (type === 'list') {
      bGantt = false;
    }
    this.props.onSaveState({ bGantt });
  };

  /* 切换稽查列表 */
  changeCheckModel= async (e, type) => {
    if (type === 'checkModel') {
      if (this.state.checkModelStatus) {
        return;
      }
      this.setState({
        checkModelStatus: true,
      });
      const { slaveFilterCondition } = this.props;
      /* 调用获取甘特图数据 */
      const chart = {};
      chart.sProcedureName = 'Sp_Manufacture_GetAPSstate';
      chart.paramsMap = {
      };
      await this.props.onCheckModel(chart, slaveFilterCondition);
      this.setState({
        checkModelStatus: false,
      });
    }
  };
  /* 弹出重算时间弹窗 */
  showTimerModal= (e, type) => {
    if (type === 'changeTimer') {
      this.props.onSaveState({ changeTimerVisible: true });
    }
  };
  /**   处理选择行发生改变   */
  // handleTableFilterData = (name, data, record) => {
  //   /*   外置处理业务   */
  //   if (name === 'slave') {
  //     let slaveInfoDataNew = '';
  //     slaveInfoDataNew = data.filter(item => record.sSlaveId.split(',').includes(item.sId));
  //     return slaveInfoDataNew;
  //   }
  // };
  /**   处理card点击事件 */
  handleTabsCallback = (child) => {
    if (commonUtils.isNotEmptyArr(this.props.teamData)) {
      child.cardSelectedColor = '#fff7e6';
      const iIndex = this.props.teamData.findIndex(item => item.sId === child.sId);
      const teamDataNew = this.props.teamData;
      teamDataNew.forEach((item, index) => {
        if (index !== iIndex) { item.cardSelectedColor = ''; }
      });
    }
    this.props.onSaveState({ Loading: true });
    this.props.onTabsCallback(child);
  };

  // handleGanttChar = async (ganttChart) => {
  //   const { token, sModelsId, formRoute, slaveFilterCondition } = this.props;
  //   let charGanttData = {};
  //   const value = {
  //     sProName: ganttChart.sProcedureName,
  //     paramsMap: ganttChart.prodParamsMap,
  //     bFilter: slaveFilterCondition,
  //   };
  //   const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}&sName=${formRoute}`;
  //   const { data: returnData } = await commonServices.postValueService(token, value, url);
  //   console.log('returnData', returnData);
  //   if (returnData.code === 1) {
  //     const { dataset } = returnData;
  //     if (commonUtils.isNotEmptyObject(dataset)) {
  //       const outData = returnData.dataset.rows[0].dataSet.outData[0];
  //       if (outData.sCode === -1) {
  //         message.error(outData.sReturn);
  //       } else {
  //         charGanttData = commonUtils.isEmpty(outData.sReturn) ? [] : JSON.parse(outData.sReturn);
  //       }
  //     }
  //   } else {
  //     message.error(returnData.msg);
  //   }
  //   console.log('charGanttData', charGanttData);
  //   this.props.onSaveState({ charGanttData });
  // };
  // renderCards = (data) => {
  //   let showInfo = '';
  //   data.map((item) => {
  //     showInfo += (
  //       <Col span={4}>
  //         <Card title={item.sTeamName} bordered={false}>
  //           {item.sTeamName} {item.dHour} {'30%'}
  //         </Card>
  //       </Col>
  //     );
  //   });
  //   return showInfo;
  // }
  render() {
    const { pageLoading } = this.props;
    return (
      <div className="product-plan-info-box">
        <Spin spinning={pageLoading} style={{ height: '100%' }}>
          <div style={{ height: '100%' }}>
            <ProductionScheduleComponent
              style={{ height: '100%' }}
              {...this.props}
              {...this.state}
              onTableFilterData={this.handleTableFilterData}
              onRowClick={this.onRowClick}
              onDoubleClick={this.onDoubleClick}
              // onRowMouseEnter={this.onRowMouseEnter}
              orderData={this.orderData}
              changeGantt={this.changeGantt}
              onCheckModel={this.changeCheckModel}
              onChangeTimer={this.changeTimer}
              onShowTimerModal={this.showTimerModal}
              onCloseChangeMachine={this.onCloseChangeMachine}
              onTabsCallback={this.handleTabsCallback}
              onTableSelectRowChange={this.onTableSelectRowChange}
              onDataUpdated={this.logDataUpdate}
              onTaskUpdated={this.logTaskUpdate}
              onLinkUpdated={this.logLinkUpdate}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const ProductionScheduleComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const {
    form, onReturnForm, app, masterData, sModelsId, masterConfig, teamSelectedRowKeys, clearArray, slavePagination, planLoadingSate, bGantt, charGanttData, messages,
    Loading } = props;
  // console.log('props:===', props);
  /*   回带表单 */
  onReturnForm(form);
  // const pageFlag = sStateSelect === '0' || sStateSelect === '1' || sStateSelect === '2';
  const pagination = {
    pageSize: commonConfig.pageSize,
    ...slavePagination,
    size: 'large',
    pageSizeOptions: commonConfig.pageSizeOptions,
    // showQuickJumper: true,
    hideOnSinglePage: false,
    showSizeChanger: true,
    current: commonUtils.isEmptyObject(slavePagination) ? 1 : slavePagination.current,
  };
  const width = '18px';
  const height = '18px';
  const moveUp = {
    title: '上移',
    width: { width },
    height: { height },
    img: <img src={MoveUp} alt="上移" width="16px" height="16px" />,
    disableimg: <img src={DisableMoveUp} alt="上移" width="16px" height="16px" />,
  };
  const moveDown = {
    title: '下移',
    width: { width },
    height: { height },
    img: <img src={MoveDown} alt="下移" width="16px" height="16px" />,
    disableimg: <img src={DisableMoveDown} alt="下移" width="16px" height="16px" />,
  };
  const moveTop = {
    title: '置顶',
    width: { width },
    height: { height },
    img: <img src={MoveTop} alt="置顶" width="16px" height="16px" />,
    disableimg: <img src={DisableMoveTop} alt="置顶" width="16px" height="16px" />,
  };
  const moveBottom = {
    title: '置底',
    width: { width },
    height: { height },
    img: <img src={MoveBottom} alt="置底" width="16px" height="16px" />,
    disableimg: <img src={DisableMoveBottom} alt="置底" width="16px" height="16px" />,
  };
  const changeMachine = {
    title: '更换机台',
    width: { width },
    height: { height },
    img: <img src={ChangeMachine} alt="更换机台" width="20px" height="20px" />,
    disableimg: <img src={DisableChangeMachine} alt="更换机台" width="20px" height="20px" />,
  };
  const showGantt = {
    title: '查看Gantt',
    width: { width },
    height: { height },
    img: <img src={ShowGantt} alt="更换机台" width="20px" height="20px" />,
    disableimg: <img src={DisableShowGantt} alt="更换机台" width="20px" height="20px" />,
  };

  const showCheckModel = {
    title: '齐套稽查',
    width: { width },
    height: { height },
    img: <img src={ShowCheckModel} alt="齐套稽查" width="18px" height="18px" />,
    disableimg: <img src={DisableShowCheckModel} alt="齐套稽查" width="18px" height="18px" />,
  };

  const showTimer = {
    title: '重算时间',
    width: { width },
    height: { height },
    img: <img src={ShowTimer} alt="重算时间" width="20px" height="20px" />,
    disableimg: <img src={DisableShowTimer} alt="重算时间" width="20px" height="20px" />,
  };
  const showList = {
    title: '查看列表',
    width: { width },
    height: { height },
    img: <img src={ShowList} alt="更换机台" width="20px" height="20px" />,
    disableimg: <img src={DisableShowList} alt="更换机台" width="20px" height="20px" />,
  };
  const resetSearch = {
    title: '重置搜索',
    width: { width },
    height: { height },
    img: <img src={Reset} alt="重置搜索" width="18px" height="18px" />,
    disableimg: <img src={DisableReset} alt="重置搜索" width="18px" height="18px" />,
  };
  const addProps = {};
  const tableProps = {
    ...commonBusiness.getTableTypes('slave', props),
    onTableFilterData: props.onTableFilterData,
    tableProps: {
      rowKey: 'sSlaveId',
      pagination,
      sortSelf: true,
      onRow: (record) => {
        return {
          onClick: () => { props.onRowClick('slave', record, true); },
          onDoubleClick: () => { props.onDoubleClick('slave', record); },
          // onMouseEnter: () => { props.onRowMouseEnter('slave', record); },
        };
      },
      onChange: props.onTitleChange.bind(this, 'slave'),
    },
    clearArray: props.clearArray,
  };

  const tableInfoProps = {
    ...commonBusiness.getTableTypes('slaveInfo', props),
    tableProps: {
      rowKey: 'sId',
      pagination,
      planLoadingSate,
      onRow: (record) => {
        return {
          onClick: () => { props.onRowClick('slaveInfo', record, true); },
          onDoubleClick: () => { props.onDoubleClick('slaveInfo', record); },
          // onMouseEnter: () => { props.onRowMouseEnter('slaveInfo', record); },
        };
      },
      onChange: props.onTitleChange.bind(this, 'slaveInfo'),
    },
    // data: commonUtils.isNotEmptyObject(props.slaveInfoDataNew) ? props.slaveInfoDataNew : props.slaveInfoData,
  };
  let zoom = {};
  zoom.scale = 'Minutes';
  zoom.step = '10'; /* 间隔 */
  if (commonUtils.isNotEmptyObject(charGanttData)) {
    zoom = charGanttData.zoom;
  }
  const ganttProps = {
    // ...commonBusiness.getGanttTypes('slave', props),
    tasks: commonUtils.isNotEmptyObject(charGanttData) ? charGanttData : {}, /* 甘特图数据源 */
    zoom: commonUtils.isNotEmptyObject(zoom) ? zoom : {},
    onDataUpdated: props.onDataUpdated,
  };
  const gridStyle = {
    width: '100%',
    textAlign: 'left',
  };
  const setUp = commonFunc.showMessage(app.commonConst, 'setUp');/* 上移 */
  const setDown = commonFunc.showMessage(app.commonConst, 'setDown');/* 下移 */
  const setTop = commonFunc.showMessage(app.commonConst, 'setTop');/* 置顶 */
  const setBottom = commonFunc.showMessage(app.commonConst, 'setBottom');/* 置底 */
  const setMachine = commonFunc.showMessage(app.commonConst, 'changeMachine');/* 置底 */
  const setResetSearch = commonFunc.showMessage(app.commonConst, 'setResetSearch');/* 重置搜索 */
  const resetSearchEnabled = clearArray.length > 0;

  const iMachineIndex = commonUtils.isEmptyObject(masterConfig) ? -1 : masterConfig.gdsconfigformslave.findIndex(item => item.sName === 'sMachineId');
  const machineShowTypeProps = {
    app,
    record: masterData,
    name: 'master',
    form: props.form,
    formId: sModelsId,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getFloatNum: props.getFloatNum,
    getDateFormat: props.getDateFormat,
    onChange: props.onChange,
    showConfig: iMachineIndex > -1 ? masterConfig.gdsconfigformslave[iMachineIndex] : {},
    formItemLayout: {},
    enabled: true,
    dataValue: commonUtils.isEmptyObject(masterData) ? '' : masterData.sMachineId,
    bTable: false,
    onFilterDropDownData: props.onFilterDropDownData,
  };
  const iTeamIndex = commonUtils.isEmptyObject(masterConfig) ? -1 : masterConfig.gdsconfigformslave.findIndex(item => item.sName === 'sTeamId');
  const teamShowTypeProps = {
    app,
    record: masterData,
    name: 'master',
    form: props.form,
    formId: sModelsId,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getFloatNum: props.getFloatNum,
    getDateFormat: props.getDateFormat,
    onChange: props.onChange,
    showConfig: iTeamIndex > -1 ? masterConfig.gdsconfigformslave[iTeamIndex] : {},
    formItemLayout: {},
    enabled: true,
    dataValue: commonUtils.isEmptyObject(masterData) ? '' : masterData.sTeamId,
    bTable: false,
    onFilterDropDownData: props.onFilterDropDownData,
  };
  const iStartIndex = commonUtils.isEmptyObject(masterConfig) ? -1 : masterConfig.gdsconfigformslave.findIndex(item => item.sName === 'tStartDate');
  const startShowTypeProps = {
    app,
    record: masterData,
    name: 'master',
    form: props.form,
    formId: sModelsId,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getFloatNum: props.getFloatNum,
    getDateFormat: props.getDateFormat,
    onChange: props.onChange,
    showConfig: iStartIndex > -1 ? masterConfig.gdsconfigformslave[iStartIndex] : {},
    formItemLayout: {},
    enabled: true,
    dataValue: commonUtils.isEmptyObject(masterData) ? '' : masterData.tStartDate,
    bTable: false,
    onFilterDropDownData: props.onFilterDropDownData,
    showTime: true,
  };

  const bSplitIndex = commonUtils.isEmptyObject(masterConfig) ? -1 : masterConfig.gdsconfigformslave.findIndex(item => item.sName === 'bSplit');
  const splitShowTypeProps = {
    app,
    record: masterData,
    name: 'master',
    form: props.form,
    formId: sModelsId,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getFloatNum: props.getFloatNum,
    getDateFormat: props.getDateFormat,
    onChange: props.onChange,
    showConfig: bSplitIndex > -1 ? masterConfig.gdsconfigformslave[bSplitIndex] : {},
    formItemLayout: {},
    enabled: true,
    dataValue: commonUtils.isEmptyObject(masterData) ? '' : masterData.bSplit,
    bTable: false,
    onFilterDropDownData: props.onFilterDropDownData,
  };

  const iSplitNumIndex = commonUtils.isEmptyObject(masterConfig) ? -1 : masterConfig.gdsconfigformslave.findIndex(item => item.sName === 'iSplitNum');
  const splitNumShowTypeProps = {
    app,
    record: masterData,
    name: 'master',
    form: props.form,
    formId: sModelsId,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getFloatNum: props.getFloatNum,
    getDateFormat: props.getDateFormat,
    onChange: props.onChange,
    showConfig: iSplitNumIndex > -1 ? masterConfig.gdsconfigformslave[iSplitNumIndex] : {},
    formItemLayout: {},
    enabled: true,
    dataValue: commonUtils.isEmptyObject(masterData) ? '' : masterData.iSplitNum,
    bTable: false,
    onFilterDropDownData: props.onFilterDropDownData,
  };

  let searchWorkSchedule = {};
  let workScheduleConfig = {};
  let searchWorkTitle = '';
  if (commonUtils.isNotEmptyObject(props.workScheduleConfig)) {
    workScheduleConfig = props.workScheduleConfig;
    searchWorkTitle = workScheduleConfig.sActiveName;
    const sWorkOrderId = commonUtils.isNotEmptyObject(props.workScheduleRecord) ? props.workScheduleRecord.sWorkOrderId : '';
    searchWorkSchedule = {
      app: {
        ...props.app,
        currentPane: {
          name: 'workSchedule',
          config: workScheduleConfig,
          conditonValues: props.getSqlCondition(workScheduleConfig),
          title: workScheduleConfig.sActiveName,
          route: '/indexPage/commonList',
          formRoute: '/indexPage/commonList',
          formId: workScheduleConfig.sActiveId,
          key: sModelsId + workScheduleConfig.sId,
          sModelsType: 'search/workSchedule',
          bFilterProName: 'p_sWorkOrderId_pro',
          bFilterProValue: sWorkOrderId,
          // select: props.onSelect,
          // selectCancel: props.onSelectCancel,
        },
      },
      dispatch: props.dispatch,
      content: props.content,
      id: new Date().getTime().toString(),
      realizeHeight: props.realizeHeight, /* 拖动偏移高度 */
      bNotShowBtn: true,
      rowSelection: null,
    };
  }


  let selectedRowKey = {};
  if (commonUtils.isNotEmptyArr(teamSelectedRowKeys)) {
    selectedRowKey = teamSelectedRowKeys[0];
  }

  let teamDataNum = 0;
  if (commonUtils.isNotEmptyArr(props.teamData)) {
    // 取得导航按钮的行数
    if (props.teamData.length % 8 === 0) {
      teamDataNum = (props.teamData.length / 8);
    } else {
      teamDataNum = Math.ceil(props.teamData.length / 8);
    }
  }

  /* 增加Modal按钮样式 */
  const okProps = {};
  if (props.bChangeTimerEnable !== undefined) {
    okProps.disabled = !props.bChangeTimerEnable;
    // okProps.loading = !props.bChangeTimerEnable;
  }

  return (
    <Form style={{ height: '100%' }}>
      <Layout style={{ height: '100%' }} className="xly-productionPlan-list productionSchedule">
        <Header className={styles.header} style={{ backgroundColor: 'rgb(100, 100, 100)' }}>
          <Toolbar {...props} className="billBtnGroup" style={{ backgroundColor: '#646464', color: 'rgb(255,255,255)' }} />
        </Header>
        <Layout className={styles.clayout} style={{ height: '100%' }} >
          <div className="productionCard">
            <Spin spinning={Loading === undefined ? false : Loading}>
              <Card bordered={false}>
                <Row>
                  {
                    commonUtils.isNotEmptyArr(props.teamData) ? props.teamData.map((child) => {
                      const sType = commonUtils.isNotEmptyNumber(child.sType) ? child.sType.toString() : '';/* 0 - 全部单据 1-未排程 2- 已排程 */
                      const cardColor = sType === '0' ? 'allCard' : sType === '1' ? 'unCard' : 'defaultCard';
                      return (
                        <Col span={3} style={{ padding: '0px' }} className={selectedRowKey === child.sId ? 'cardSelectedColor' : commonUtils.isNotEmptyObject(child.cardSelectedColor) ? 'cardSelectedColor' : cardColor} >
                          <Card.Grid hoverable={false}style={gridStyle} onClick={props.onTabsCallback.bind(this, child)}>
                            <div className="card_flex">
                              <div className="left_card overflow-ellipsis" title={child.sMachineName}>{child.sMachineName}</div>
                              <div className="right_card">{`${child.dHour}h`}</div>
                            </div>
                          </Card.Grid>
                        </Col>);
                    }) : ''
                  }
                </Row>
              </Card>
            </Spin>
          </div>
          <div className={selfstyles.mainPlan}>
            <Layout className={['processList', 'processListTable']}>
              <Sider className="process">
                <a title={setResetSearch} {...addProps} onClick={resetSearchEnabled ? e => props.onResetTableSearch() : null}>{ resetSearchEnabled ? resetSearch.img : resetSearch.disableimg}</a>&nbsp;
                <a title={setTop} {...addProps} onClick={props.moveEnabled ? e => props.orderData(e, 'slave', 0) : null}>{ props.moveEnabled ? moveTop.img : moveTop.disableimg}</a>
                <a title={setUp} {...addProps} onClick={props.moveEnabled ? e => props.orderData(e, 'slave', 1) : null}>{ props.moveEnabled ? moveUp.img : moveUp.disableimg }</a>
                <a title={setDown} {...addProps} onClick={props.moveEnabled ? e => props.orderData(e, 'slave', 2) : null}>{props.moveEnabled ? moveDown.img : moveDown.disableimg }</a>
                <a title={setBottom} {...addProps} onClick={props.moveEnabled ? e => props.orderData(e, 'slave', 3) : null}>{props.moveEnabled ? moveBottom.img : moveBottom.disableimg }</a>&nbsp;&nbsp;
                <a title={setMachine} {...addProps} onClick={props.moveEnabled ? e => props.orderData(e, 'slaveInfo', 0) : null}>{props.moveEnabled ? changeMachine.img : changeMachine.disableimg }</a>  &nbsp;&nbsp;
                <a title="查看列表" {...addProps} onClick={props.bGantt ? e => props.changeGantt(e, 'list', 0) : null}>{props.bGantt ? showList.img : showList.disableimg }</a>  &nbsp;&nbsp;
                <a title="查看甘特图" {...addProps} onClick={!props.bGantt ? e => props.changeGantt(e, 'gantt', 0) : null}>{!props.bGantt ? showGantt.img : showGantt.disableimg }</a>&nbsp;&nbsp;
                <a title="齐套稽查" {...addProps} onClick={commonUtils.isEmptyObject(props.sortedInfo) ? e => props.onCheckModel(e, 'checkModel') : null}>
                  {props.checkModelStatus ? <LoadingOutlined style={{ fontSize: 16 }} spin /> : commonUtils.isEmptyObject(props.sortedInfo) ? showCheckModel.img : showCheckModel.disableimg }
                </a>&nbsp;&nbsp;
                <a title="重算时间" {...addProps} onClick={props.moveEnabled && commonUtils.isEmptyObject(props.sortedInfo) ? e => props.onShowTimerModal(e, 'changeTimer') : null}>{props.moveEnabled && commonUtils.isEmptyObject(props.sortedInfo) ? showTimer.img : showTimer.disableimg }</a>
              </Sider>
              {
                bGantt && commonUtils.isNotEmptyObject(charGanttData) ?
                  <Content style={{ height: 'calc( 100vh - 230px )' }} className={GanttStyles.ganttList} >
                    <div className="gantt-container" style={{ width: '100vm', height: '100%' }} >
                      <Gantt {...ganttProps} />
                      <div style={{ display: 'block' }} >
                        <MessageArea
                          messages={messages}
                        />
                      </div>
                    </div>
                  </Content> :
                  <Content
                    className="xly-normal-list productPlan"
                  >
                    {/* eslint-disable-next-line no-mixed-operators */}
                    <StaticEditTable {...tableProps} slaveInfo={tableInfoProps} setExpandedRowRender="Y" offsetHeight={`${(teamDataNum >= 2 ? 2 : teamDataNum) * 45 + 10}`} />
                  </Content>
              }
            </Layout>
          </div>
        </Layout>
        {
          props.isChangeMachine ?
            <AntdDraggableModal
              width={500}
              title="换机台"
              visible={props.isChangeMachine}
              onCancel={props.onCloseChangeMachine}
              onOk={props.onChangeMachine}
              okButtonProps={commonUtils.isNotEmptyObject(masterData) && (commonUtils.isNotEmptyStr(masterData.sMachineId) || (masterData.bSplit && commonUtils.isNotEmptyStr(masterData.iSplitNum))) ? { disabled: false } : { disabled: true }}
            >
              { commonUtils.isEmptyObject(masterConfig) ? '' : <ShowType {...machineShowTypeProps} /> }
              { commonUtils.isEmptyObject(masterConfig) ? '' : <ShowType {...teamShowTypeProps} /> }
              {/* { commonUtils.isEmptyObject(masterConfig) ? '' : <ShowType {...startShowTypeProps} /> } */}
              { commonUtils.isEmptyObject(masterConfig) ? '' : <ShowType {...splitShowTypeProps} /> }
              { commonUtils.isNotEmptyObject(masterConfig) && commonUtils.isNotEmptyObject(masterData) && masterData.bSplit ? <ShowType {...splitNumShowTypeProps} /> : '' }
            </AntdDraggableModal>
            : ''
        }
        {
          props.changeTimerVisible ?
            <AntdDraggableModal
              className={selfstyles.commonModal}
              width={500}
              title="重算时间"
              visible
              onCancel={props.onCloseModel.bind(this, 'changeTimerVisible')}
              onOk={props.onChangeTimerPro}
              okButtonProps={okProps}
            >
              { commonUtils.isEmptyObject(masterConfig) ? '' : <ShowType {...startShowTypeProps} /> }
            </AntdDraggableModal>
            : ''
        }
        {
          props.workScheduleVisible ?
            <AntdDraggableModal
              className="workScheduleModal"
              width={1300}
              title={commonUtils.isEmptyObject(searchWorkSchedule) ? searchWorkTitle : searchWorkSchedule.app.currentPane.title}
              visible={props.workScheduleVisible}
              onCancel={props.onCloseModel.bind(this, 'workScheduleVisible')}
              onSaveState={props.onSaveState}
              footer={null}
            >
              <CommonListSelect {...searchWorkSchedule} />
            </AntdDraggableModal> : null
        }
      </Layout>
    </Form>
  );
});

export default CommonBase(CommonProductionPlanEvent(ProductionSchedule));
