/* eslint-disable prefer-destructuring,no-await-in-loop,semi,no-unused-vars */
import React, { Component } from 'react';
import { message } from 'antd-v4'; // Form, Modal, InputNumber
// import reactComponentDebounce from 'react-component-debounce';
import moment from 'moment';
import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonBusiness from './commonBusiness'; /* 单据业务功能 */
import * as commonServices from '../../services/services'; /*   服务类   */
import commonConfig from '../../utils/config';
import * as commonFunc from './commonFunc'; /* 通用单据方法 */

/*
const { confirm } = Modal;
const FormItem = Form.Item;
const InputNumberA = reactComponentDebounce(800)(InputNumber);
*/

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.form = {}; /*   表单对象   */
    }

    componentWillReceiveProps(nextProps) {
      const {
        app, formData, currentId, masterData, searchSolution, sGroupByList, teamSelectedRowKeys, teamData,
      } = nextProps;
      const { teamFilterCondition } = this.props;
      let {
        isReceive, teamConfig, slaveConfig, slaveInfoConfig,
      } = nextProps;
      const { currentPane } = app;
      const { otherCondition } = currentPane;
      if (formData.length > 0 && commonUtils.isEmptyObject(teamConfig) && commonUtils.isEmptyArr(searchSolution)) {
        isReceive = false;
        const sId = currentId || nextProps.masterData?.sId || '';
        const masterConfig = formData.filter(item => !item.bGrd && item.sTbName === 'eleteam')[0];

        teamConfig = formData.filter(item => item.sTbName === 'Sp_Manufacture_ProductionPlanInfo_WorkCenter')[0];
        slaveConfig = formData.filter(item => item.sTbName === 'Sp_Manufacture_ProductionPlanInfo' && item.sGrd !== 'slaveInfo')[0];
        slaveInfoConfig = formData.filter(item => item.sTbName === 'Sp_Manufacture_ProductionPlanInfo' && item.sGrd === 'slaveInfo')[0];
        const productionPlanConfig = formData.filter(item => item.sTbName === 'MftProductionPlanSlave')[0];

        const teamColumn = commonFunc.getHeaderConfig(teamConfig);
        const slaveColumn = commonFunc.getHeaderConfig(slaveConfig);
        const slaveInfoColumn = commonFunc.getHeaderConfig(slaveInfoConfig);
        const productionPlanColumn = commonFunc.getHeaderConfig(productionPlanConfig);

        let currfilterCondition = [];
        if (commonUtils.isNotEmptyObject(masterData) && !commonUtils.isEmpty(masterData.sSearchSolutionId) && commonUtils.isNotEmptyArr(searchSolution)) {
          const iIndex = searchSolution.findIndex(item => item.sId === masterData.sSearchSolutionId);
          if (iIndex > -1 && !commonUtils.isEmpty(searchSolution[iIndex].sCondition)) {
            currfilterCondition = JSON.parse(searchSolution[iIndex].sCondition);
          }
        }
        this.handleGetData('team', teamConfig, currfilterCondition, undefined, '', false, sGroupByList);
        // this.handleGetData('slave', slaveConfig, [], undefined, '', false, undefined);
        // this.handleGetData('slaveInfo', slaveInfoConfig, [], undefined, '', false, undefined);

        this.props.onSaveState({
          masterConfig,
          teamConfig,
          teamColumn,
          slaveConfig,
          slaveColumn,
          slaveInfoConfig,
          slaveInfoColumn,
          productionPlanConfig,
          productionPlanColumn,
          sId,
          pageLoading: false,
          enabled: true,
          dragPermission: false,
          dragAndDropSwitch: false,
          isReceive,
          masterData: {},
          tableBtnEnabled: true,
          // stateOption: objValue,
        });
      } else if (commonUtils.isEmptyStr(teamSelectedRowKeys) && commonUtils.isEmptyArr(teamFilterCondition) && commonUtils.isNotEmptyArr(teamData) && !isReceive) {
        let iIndex = -1;
        if (otherCondition) {
          iIndex = otherCondition.findIndex(item => item.bFilterName === 'sMachineId');
        }
        if (iIndex !== -1) {
          const newIndex = teamData.findIndex(item => item.sMachineId === otherCondition[iIndex].bFilterValue);
          if (newIndex === -1) {
            this.handleCallBack({ ...teamData[0] });
          } else {
            this.handleCallBack({ ...teamData[newIndex] });
          }
        } else {
          this.handleCallBack({ ...teamData[0] });
        }
        this.props.onSaveState({ isReceive: true });
      } else if (commonUtils.isEmptyStr(teamSelectedRowKeys) && commonUtils.isEmptyArr(currentPane.filterCondition) && commonUtils.isEmptyArr(teamFilterCondition) && commonUtils.isNotEmptyArr(teamData) && !isReceive) {
        this.handleGetData('slave', slaveConfig, [], undefined, '', false, undefined);
        // this.handleGetData('slaveInfo', slaveInfoConfig, [], undefined, '', false, undefined);
        this.props.onSaveState({ isReceive: true, teamSelectedRowKeys: teamData[0].sId });
      }
    }

    shouldComponentUpdate(nextProps) {
      const {
        slaveColumn,
      } = nextProps;
      return commonUtils.isNotEmptyArr(slaveColumn);
    }

    componentDidUpdate(prevProps) {
      const {
        slaveSelectedRowKeys, moveEnabled, tableBtnEnabled,
      } = prevProps;
      if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys) && !moveEnabled && tableBtnEnabled) {
        this.props.onSaveState({ moveEnabled: true });
      } else if ((commonUtils.isEmptyArr(slaveSelectedRowKeys) && moveEnabled && tableBtnEnabled) || (moveEnabled && !tableBtnEnabled)) {
        this.props.onSaveState({ moveEnabled: false });
      }
    }

    onChangeMachine = async () => {
      const { sModelsId, masterData, slaveInfoSelectedRowKeys } = this.props;
      const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
      const value = {
        sProName: 'Sp_Manufacture_ProductionPlanInfo_ChangeMachine',
        paramsMap: {
          bSplit: masterData.bSplit,
          iSplitNum: masterData.iSplitNum,
          sMachineId: masterData.sMachineId,
          sTeamId: masterData.sTeamId,
          tStartDate: masterData.tStartDate,
          sProInParam: JSON.stringify({ params: { key: 'slaveInfo', value: { sId: slaveInfoSelectedRowKeys } } }),
        },
      };
      const dataReturn = (await commonServices.postValueService(this.props.app.token, value, url)).data;
      if (dataReturn.code === 1) {
        /*   数据查询成功   */
        this.handleRefresh();
        this.props.onSaveState({ isChangeMachine: false, masterData: { ...masterData, sMachineId: '', sTeamId: '' } });
      } else { /*   失败   */
        this.props.getServiceError(dataReturn);
      }
    }

    /**   获取表数据   */
    handleGetData = async (sName, slaveConfig, slaveFilterCondition, page, slaveOrderBy, clearSelectData, sGroupByListNew, nextProps, isWait) => {
      const { app } = commonUtils.isEmpty(nextProps) ? this.props : nextProps;
      const sGroupByList = sGroupByListNew !== undefined ? commonUtils.isEmptyArr(sGroupByListNew) ? null : sGroupByListNew : this.props.sGroupByList;
      const conditonValues = app.currentPane.conditonValues;
      const filterCondition = app.currentPane.filterCondition;
      let bFilter = [];
      if (!commonUtils.isEmptyArr(slaveFilterCondition)) {
        slaveFilterCondition[0].bFilterName = slaveFilterCondition[0].bFilterName.replace('_pro', '');
        bFilter.push(...slaveFilterCondition);
      }
      if (!commonUtils.isEmptyArr(filterCondition)) {
        bFilter.push(...filterCondition);
      }
      const addState = {};
      const pageNum = commonUtils.isEmpty(page) ? 1 : page;
      addState.pageNum = pageNum;
      addState.pageSize = ''; // commonConfig.pageSize;
      if (sName === 'team' && commonUtils.isNotEmptyArr(filterCondition)) {
        bFilter = [];
        const addFilter = {};
        addFilter.bFilterName = `${filterCondition[0].bFilterName}_pro`;
        addFilter.bFilterCondition = '=';
        addFilter.bFilterValue = filterCondition[0].bFilterValue;
        bFilter.push(addFilter);
      }
      const returnData = await this.props.handleGetDataSet({
        name: sName,
        configData: slaveConfig,
        condition: {
          ...addState, bFilter, sFilterOrderBy: slaveOrderBy, sSqlCondition: conditonValues, sGroupList: sGroupByList,
        },
        flag: true,
        clearSelectData,
        isWait,
      });
      this.props.onSaveState({ Loading: false });
      if (isWait) {
        return { ...returnData };
      }
    };

    // 搜索 查询
    handleGetSearchData = (config, filterCondition) => {
      const {
        teamConfig, sGroupByList, teamSelectedRowKeys,
      } = this.props;
      const iIndex = filterCondition.findIndex(item => item.bFilterName === 'sTeamId' && item.bFilterCondition === '=' && item.bFilterValue === teamSelectedRowKeys[0]);
      const filter = [];
      filterCondition.forEach((itme, i) => {
        if (iIndex !== i) { filter.push(itme); }
      });
      this.handleGetData('team', teamConfig, filter, undefined, '', false, sGroupByList);
    };

    handleGetSlaveData = (config, filterCondition) => {
      const {
        slaveConfig, slaveInfoConfig, teamData, teamSelectedRowKeys,
      } = this.props;
      const iIndex = filterCondition.findIndex(item => item.bFilterName === 'sTeamId' && item.bFilterCondition === '=' && item.bFilterValue === teamSelectedRowKeys[0]);
      const filter = [];
      filterCondition.forEach((itme, i) => {
        if (iIndex !== i) { filter.push(itme); }
      });

      const addFilter = {};
      addFilter.bFilterName = 'sTeamId';
      addFilter.bFilterCondition = '=';
      addFilter.bFilterValue = teamData[0].sId;
      filter.push(addFilter);

      this.handleGetData('slave', slaveConfig, filter, undefined, undefined);
      // this.handleGetData('slaveInfo', slaveInfoConfig, filter, undefined, undefined);
    };

    /** 主表控件是否全部显示 */
    handleToggle = () => {
      const { expand } = this.props;
      this.props.onSaveState({ expand: !expand });
    };

    /**   表单回带   */
    handleForm = (form) => {
      this.form = form;
    };

    /**   toolbar保存   */
    handleSaveData = async (params) => {
      const {
        token, sModelsId,
      } = this.props;
      const returnData = await commonBusiness.saveData({ token, value: params, sModelsId });
      if (commonUtils.isNotEmptyObject(returnData)) {
        this.handleRefresh();
        if (this.props.app.currentPane.refresh !== undefined) {
          this.props.app.currentPane.refresh();
        }
        return true;
      } else {
        return false;
      }
    };

    /** 保存校验 */
    handleValidateSave = () => {
      this.form.validateFields((err) => {
        /*   验证通过与不通过走不同的流程   */
        if (err) { /*   验证失败   */
          /*   直接渲染显示错误提示   */
          for (const key of Object.keys(err)) {
            message.error(err[key].errors[0].message);
          }
        } else { /*   验证成功   */
          const {
            slaveConfig, slaveData, slaveDelData, app, productionPlanConfig, productionPlanDelData, tableBtnEnabled, charGanttData, bGantt,
            slaveInfoData, slaveInfoDelData,
          } = this.props;
          const data = [];
          if (commonUtils.isEmptyArr(slaveData)) {
            message.error(commonFunc.showMessage(app.commonConst, 'slaveNotNull')); // 从表不能为空！
            return;
          } else {
            /* 如果是甘特图视图，则进入甘特图视图保存逻辑 */
            if (bGantt && commonUtils.isNotEmptyObject(charGanttData)) {
              const data = [];
              const addState = {}
              const charGanttDataFormate = [];
              charGanttData.data.forEach((val) => {
                val.start_date = moment(val.start_date).format('YYYY-MM-DD H:m');
                val.end_date = moment(val.end_date).format('YYYY-MM-DD H:m');
                charGanttDataFormate.push(val);
              })
              addState.name = 'slave';
              addState.sTable = 'MftProductionPlanSlave';
              addState.column = charGanttDataFormate;
              data.push(addState);
              this.handleSaveData({ data, sClientType: '1' });
              return;
            }
            const productionPlanData = [];
            const slaveFilter = slaveData.filter(item => item.sDivRowNew);
            if (commonUtils.isNotEmptyArr(slaveFilter)) {
              slaveFilter.forEach((item, i) => {
                const index = slaveData.findIndex(itemS => itemS.sSlaveId === item.sSlaveId);
                if (index <= slaveData.length) {
                  // slaveData[index].sDivRowNew = '';
                  slaveData[index + 1].sDivRow = item.sDivRowNew;
                  slaveData[index + 1].sDivRowNew = '';
                }
              });
            }
            for (const item of slaveData) {
              const {
                sSlaveId, handleType, iOrder, tStartDate, sMemo, dAdjustHour, sDivRowNew, sDivRow,
              } = item;
              if (commonUtils.isEmptyObject(sDivRowNew)) {
                const sIds = sSlaveId.split('-');
                sIds.forEach((newItem) => {
                  const addState = {};
                  addState.sId = newItem;
                  if (commonUtils.isEmpty(iOrder)) {
                    message.error('序号必填！');
                    return;
                  }
                  if (commonUtils.isEmpty(tStartDate)) {
                    message.error('时间必填！');
                    return;
                  }
                  addState.iOrder = iOrder;
                  /* 20210406 zhuzong要求排程保存时候 必传iOrder,tStartDate,sMemo,dAdjustHour 四个参数 */
                  addState.tStartDate = tStartDate;
                  // if (commonUtils.isNotEmptyObject(sMemo)) {
                  //   addState.sMemo = sMemo;
                  // }
                  // if (dAdjustHour !== undefined) {
                  //   addState.dAdjustHour = dAdjustHour;
                  // }
                  addState.sMemo = sMemo;
                  addState.dAdjustHour = dAdjustHour;
                  addState.handleType = handleType;
                  if (sDivRow) {
                    addState.sDivRow = sDivRow;
                  } else {
                    addState.sDivRow = '';
                  }
                  productionPlanData.push(addState);
                });
              }
            }
            data.push(commonBusiness.mergeData('productionPlan', productionPlanConfig.sTbName, productionPlanData, productionPlanDelData));
            data.push(commonBusiness.mergeData('slaveInfo', productionPlanConfig.sTbName, slaveInfoData, slaveInfoDelData));
          }
          if (!commonBusiness.validateTable(slaveConfig, slaveData)) {
            return;
          }
          // data.push(commonBusiness.mergeData('slave', 'MftProductionPlanSlave', slaveData, slaveDelData));
          this.handleSaveData({ data, sClientType: '1' });
        }
      });
    };

    /* 数据删除成功跳转到新路由即pane */
    handleDelDataSuccess = (props) => {
      const { app } = props;
      let { panes, currentPane } = app;
      /* 删除单据后退出当前路由后,标签panes变化后的集合 */
      panes = panes.filter(pane => pane.key !== currentPane.key);
      /* 跳转到panes集合的最后一个路由，因为panes集合一定含有主页路由所以panes的集合大于等于1 */
      currentPane = panes[panes.length - 1];
      this.props.onRemovePane(panes, currentPane);
    };

    /** 表格数据更改 */
    // name 不写完整的state名称作用为了要用到total // (name, changeValue, sId, dropDownData)
    handleTableChange = async (name, sFieldName, changeValue, sId, dropDownData) => {
      const { sModelsId } = this.props;
      this.props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, false);
      if (name === 'slave') {
        commonUtils.setStoreDropDownData(sModelsId, 'master', 'sTeamId', []);
        if (sFieldName === 'iOrder') {
          /* 修改汇总表数据后,slaveInfo表iOrder同步更改 */
          const { slaveInfoData, slaveData } = this.props;
          const iIndex = slaveData.findIndex(item => item.sId === sId);
          if (iIndex > -1) {
            const tableDataRow = slaveData[iIndex];
            let childrenData = [];
            childrenData = tableDataRow.childrenData;
            if (commonUtils.isNotEmptyArr(childrenData)) {
              childrenData.forEach((child) => {
                const index = slaveInfoData.findIndex(item => item.sId === child.sId);
                const addState = {};
                addState.handleType = 'update';
                addState.iOrder = tableDataRow.iOrder;
                if (index > -1) {
                  slaveInfoData[index] = { ...slaveInfoData[index], ...addState }
                }
              });
              this.props.onSaveState({ slaveData, slaveInfoData });
            }
          }
        }
      }
    };
    // 打印
    handleBtnPrint = (sActiveId, checked) => {
      const {
        app, sModelsId, slaveConfig, slaveSelectedRowKeys, slaveFilterCondition, reportData,
      } = this.props;
      const { token } = app;
      let slaveFilterConditionNew = slaveFilterCondition === undefined ? [] : [...slaveFilterCondition];

      let sids = '';
      slaveSelectedRowKeys.forEach((item, i) => {
        if (i === slaveSelectedRowKeys.length - 1) {
          sids = `${sids}${item}`;
        } else {
          sids = `${sids}${item},`;
        }
      });
      if (sids !== '') {
        slaveFilterConditionNew = [];
        const sidsNew = commonUtils.isNotEmptyObject(sids) ? sids.replace(/-/g, ',') : '';
        const addFilter = {};
        addFilter.bFilterName = 'sId';
        addFilter.bFilterCondition = 'in';
        addFilter.bFilterValue = sidsNew;
        slaveFilterConditionNew.push(addFilter);
      }

      const queryFilter = {};
      queryFilter[slaveConfig.sId] = { bFilter: slaveFilterConditionNew };

      const queryFilterJson = encodeURIComponent(JSON.stringify(queryFilter));
      /* 拿到打印报表名称 */
      let printReportName = 'report';
      if (commonUtils.isNotEmptyArr(reportData)) {
        const iIndex = reportData.findIndex(item => item.sId === sActiveId);
        if (iIndex > -1) {
          printReportName = reportData[iIndex].sReportName;
        }
      }
      const urlPrint = `${commonConfig.file_host}printReport/printPdf/${sActiveId}/${printReportName}.pdf?${checked ? 'fileType=.xlsx&' : ''}queryFilter=${queryFilterJson}&sModelsId=${sModelsId}&sMaintableId=${slaveConfig.sId}&token=${encodeURIComponent(token)}`;
      window.open(urlPrint);
    };
    /* 导出Excel */
    handleOut = () => {
      const {
        slaveConfig, sFilterOrderBy, slaveSelectedRowKeys, slaveFilterCondition, sGroupByList,
      } = this.props;

      const newfilterCondition = slaveFilterCondition === undefined ? [] : slaveFilterCondition;

      let sids = '';
      if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
        slaveSelectedRowKeys.forEach((item, i) => {
          if (i === slaveSelectedRowKeys.length - 1) {
            sids = `${sids}${item}`;
          } else {
            sids = `${sids}${item},`;
          }
        });
        const addFilter = {};
        addFilter.bFilterName = 'sId';
        addFilter.bFilterCondition = 'in';
        addFilter.bFilterValue = sids;
        newfilterCondition.push(addFilter);
      }

      let url = `${commonConfig.server_host}excel/export/${slaveConfig.sId}?sModelsId=${slaveConfig.sParentId}&token=${this.props.app.token}`;
      if (commonUtils.isNotEmptyArr(newfilterCondition)) {
        url = `${url}&bFilter=${encodeURIComponent(JSON.stringify(newfilterCondition))}`;
      }
      if (sFilterOrderBy !== undefined && sFilterOrderBy !== '' && Object.keys(sFilterOrderBy).length > 0) {
        url = `${url}&sFilterOrderBy=${encodeURIComponent(JSON.stringify(sFilterOrderBy))}`;
      }
      if (commonUtils.isNotEmptyArr(sGroupByList)) {
        url = `${url}&sGroupList=${encodeURIComponent(JSON.stringify(sGroupByList))}`;
      }
      window.open(url);
    };
    handleConfirmDataChange = (value) => {
      const {
        masterData,
      } = this.props;
      masterData.dOutsideQty = value;

      this.props.onSaveState({ masterData });
    };
    //  按钮操作
    handleButtonClick = (name) => {
      if (name === 'BtnRefresh') {
        this.handleRefresh();
      } else if (name === 'BtnOut') {
        this.handleOut();
      } else if (name === 'BtnDesignFunction') {
        this.handleDesignFunction();
      }
    };
    handleDesignFunction = () => {
      this.props.onSaveState({ visibleStatement: true });
    };
    handleUpdated = async (params) => {
      const { app, sModelsId } = this.props;
      const { token } = app;

      const url = `${commonConfig.server_host}productionPlan/getProcessOperation?sModelsId=${sModelsId}`;
      const { data } = await commonServices.postValueService(token, params, url);

      if (data.code === 1) {
        /*   数据查询成功   */
        return true;
      } else { /*   失败   */
        this.props.getServiceError(data);
        return false;
      }
    };

    handleMasterChange = (name, sFieldName, changeValue, sId, dropDownData, isWait) => {
      const { sModelsId } = this.props;
      if (sFieldName === 'sMachineId') {
        commonUtils.setStoreDropDownData(sModelsId, 'master', 'sTeamId', []);
      }
      if (isWait) {
        return this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, isWait);
      } else {
        this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, isWait);
      }
    };

    handleCalculate = () => {
      const { sModelsId, slaveData } = this.props;
      const materialsInfo = [];
      const slaveDataNew = [];
      slaveData.forEach(async (item) => {
        const index = materialsInfo.findIndex(obj => obj.sMaterialsId === item.sMaterialsId);
        item.bMaterialAdequate = 0;
        if (commonUtils.isNotEmptyStr(item.sMaterialsId) && index === -1) {
          const url = `${commonConfig.server_host}eleMaterialsStock/getEleMaterialsStoreCurrQty?sModelsId=${sModelsId}`;
          const body = {
            sMaterialsId: item.sMaterialsId, /*   查询条件   */
          };
          const dataReturn = (await commonServices.postValueService(this.props.app.token, body, url)).data;
          if (dataReturn.code === 1) {
            if (commonUtils.isNotEmptyArr(dataReturn.dataset.rows[0])) {
              const materials = dataReturn.dataset.rows[0];
              if (commonUtils.isNotEmptyNumber(materials.dAuxiliaryQty) && commonUtils.isNotEmptyNumber(item.dPrintQty) && materials.dAuxiliaryQty > item.dPrintQty) {
                item.bMaterialAdequate = 1;
                materialsInfo[index].dAuxiliaryQty = materialsInfo[index].sMaterialsId - item.dPrintQty;
              }
            }
          }
        } else if (commonUtils.isNotEmptyStr(item.sMaterialsId) && index === -1) {
          if (commonUtils.isNotEmptyNumber(materialsInfo[index].sMaterialsId) && commonUtils.isNotEmptyNumber(item.dPrintQty) && materialsInfo[index].sMaterialsId > item.dPrintQty) {
            item.bMaterialAdequate = 1;
            materialsInfo[index].dAuxiliaryQty = materialsInfo[index].sMaterialsId - item.dPrintQty;
          }
        }
        slaveDataNew.push(item);
      });
      this.props.onSaveState({ slaveData: slaveDataNew });
    };

    handleTitleChange = async (name, slavePagination, filters, sorter, extra) => {
      // const tableBtnEnabled = commonUtils.isNotEmptyObject(filters) && commonUtils.isEmptyObject(sorter);
      const addState = {}; // 搜索时不能使用排序保存，否则数据会出不来。
      if (commonUtils.isNotEmptyObject(sorter)) {
        const slaveData = [];
        extra.currentDataSource.forEach((item, iIndex) => {
          const slaveTableRow = { ...item, iOrder: iIndex + 1, handleType: 'update' };
          slaveData.push(slaveTableRow);
        });
        if (slaveData.length === this.props.slaveData.length) {
          addState.slaveData = slaveData;
        }
      }
      this.props.onSaveState({
        ...addState, slavePagination, pageLoading: false,
      });
      // this.props.onSaveState({
      //   tableBtnEnabled: false, pageLoading: true,
      // });
      // const { [`${name}Config`]: tableConfig, [`${name}FilterCondition`]: tableFilterCondition, sGroupByList } = this.props;
      // const sort = sorter.order === 'ascend' ? 'asc' : 'desc';
      // const slaveOrderBy = Object.keys(sorter).length > 0 ? { [sorter.columnKey]: sort } : ''; // 后端未支持空对象， 先用空表示
      // const addState = await this.handleGetData(name, tableConfig, tableFilterCondition, undefined, slaveOrderBy, '', sGroupByList, this.props, true);
      // if (addState === undefined) return;
      // const { [`${name}Data`]: tempData } = addState;
      // if (commonUtils.isNotEmptyArr(addState[`${name}Data`])) {
      //   addState[`${name}Data`].forEach((item, iIndex) => {
      //     addState[`${name}Data`][iIndex] = { ...item, iOrder: iIndex + 1, handleType: 'update' };
      //   });
      // }
      // this.props.onSaveState({ ...addState });
      // setTimeout(() => {
      //   /* 刷新commList页面数据 */
      //   this.props.onSaveState({ pageLoading: false });
      // }, 3600);
    };
    /**   处理选择行发生改变   */
    handleCallBack = (child) => {
      const {
        slaveConfig, slaveInfoConfig, teamFilterCondition, bGantt,
      } = this.props;
      const filter = [];
      let addFilter = {};
      if (child.sType === '1') {
        addFilter.bFilterName = 'sProcessId';
        addFilter.bFilterCondition = '=';
        addFilter.bFilterValue = child.sMachineId;
        filter.push(addFilter);
        addFilter = {};
        addFilter.bFilterName = 'sState';
        addFilter.bFilterCondition = '=';
        addFilter.bFilterValue = '0';
        filter.push(addFilter);
      } else if (child.sType === '2') {
        addFilter.bFilterName = 'sMachineId';
        addFilter.bFilterCondition = '=';
        addFilter.bFilterValue = child.sMachineId;
        filter.push(addFilter);
        addFilter = {};
        addFilter.bFilterName = 'date_format(tStartDate, \'%y-%m-%d\')';
        addFilter.bFilterCondition = '=';
        addFilter.bFilterValue = child.tStartDate;
        filter.push(addFilter);
      }
      if (commonUtils.isNotEmptyArr(teamFilterCondition)) {
        filter.push(...teamFilterCondition);
      }
      this.handleGetData('slave', slaveConfig, filter, undefined, '', false, undefined);
      /* 甘特图视图下 点击卡片刷新 */
      if (bGantt) {
        this.handleGanttChar('', filter)
      }
      // this.handleGetData('slaveInfo', slaveInfoConfig, filter, undefined, '', false, undefined);
      const rowKeys = [];
      rowKeys.push(child.sId);
      this.props.onSaveState({
        teamSelectedRowKeys: rowKeys,
      });
    };

    /* 获取甘特图数据 */
    handleGanttChar = async (ganttChart, slaveFilterCondition) => {
      const {
        token, sModelsId, formRoute,
      } = this.props;
      const char = {};
      if (commonUtils.isNotEmptyObject(ganttChart)) {
        char.sProcedureName = ganttChart.sProcedureName;
        char.paramsMap = ganttChart.paramsMap;
      } else {
        char.sProcedureName = 'Sp_Process_CommonGtChar';
        char.paramsMap = {
        };
      }
      let charGanttData = {};
      const value = {
        sProName: char.sProcedureName,
        paramsMap: char.prodParamsMap,
        bFilter: slaveFilterCondition,
      };
      const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}&sName=${formRoute}`;
      const { data: returnData } = await commonServices.postValueService(token, value, url);
      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);
            this.props.onSaveState({ charGanttData });
          }
        }
      } else {
        message.error(returnData.msg);
      }
    };

    /* 获取稽查模型数据 */
    handleCheckModel = async (chart, slaveFilterCondition, other) => {
      const { app, sModelsId } = this.props;
      const obj = {};
      if (commonUtils.isNotEmptyObject(obj)) {
        obj.sProcedureName = chart.sProcedureName;
        obj.paramsMap = chart.paramsMap;
      } else {
        obj.sProcedureName = 'Sp_Manufacture_GetAPSstate';
        obj.paramsMap = {
        };
      }
      const value = {
        sProName: obj.sProcedureName,
        bFilter: slaveFilterCondition,
      };
      if (other?.iFlag === 1) {
        value.iFlag = 1;
      }

      const url = `${commonConfig.server_host}procedureCall/doGenericProcedureCall?sModelsId=${sModelsId}`;
      const returnData = (await commonServices.postValueService(app.token, value, url)).data;
      if (returnData.code === 1) {
        message.success(returnData.msg);
        this.handleButtonClick('BtnRefresh');
        this.props.onSaveState({ bCheckModel: true })
      } else {
        this.props.getServiceError({ ...returnData, fn: () => this.handleCheckModel(chart, slaveFilterCondition, { iFlag: 1 }) });
      }
    };

    /* 重算时间调用接口 执行存储过程 */
    handleChangeTimer = async (other) => {
      const {
        app, sModelsId, slaveFilterCondition, slaveSelectedRowKeys, slaveData, masterData,
      } = this.props;
      let value = {};
      if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
        this.props.onSaveState({ bChangeTimerEnable: false })
        const slaveSelectedData = slaveData.filter(item => slaveSelectedRowKeys.includes(item.sSlaveId));
        const minSelectedData = this.arrayMin(slaveSelectedData); /* iOrder最小的 */
        if (commonUtils.isNotEmptyArr(minSelectedData) && commonUtils.isNotEmptyObject(minSelectedData.sMachineId)) {
          value = {
            sProName: 'Sp_Manufacture_SetTime',
            sProInParam: JSON.stringify({
              sMachineId: minSelectedData.sMachineId,
              iOrder: minSelectedData.iOrder,
              tCStartTime: masterData.tStartDate,
            }),
          };
          if (other?.iFlag === 1) {
            value.iFlag = 1;
          }
          const url = `${commonConfig.server_host}procedureCall/doGenericProcedureCall?sModelsId=${sModelsId}`;
          const returnData = (await commonServices.postValueService(app.token, value, url)).data;
          if (returnData.code === 1) {
            message.success(returnData.msg);
            this.handleButtonClick('BtnRefresh');
            this.props.onSaveState({ changeTimerVisible: false, bChangeTimerEnable: true })
          } else {
            this.props.getServiceError({ ...returnData, fn: () => this.handleChangeTimer({ iFlag: 1 }) });
          }
        } else {
          message.error('不能重置时间!');
        }
      } else {
        message.error('请选择一行数据!');
      }
    };

    // 查找数组中最小值
    arrayMin = (arrs) => {
      let min = arrs[0];
      for (let i = 1, ilen = arrs.length; i < ilen; i += 1) {
        if (arrs[i].iOrder < min.iOrder) {
          min = arrs[i];
        }
      }
      return min;
    }

    /*
    handleRefresh = async () => {
      const {
        clearArray, slaveConfig, slaveInfoConfig, teamFilterCondition, slaveFilterCondition,
      } = this.props;
      this.props.onSaveState({
        clearArray: [], searchText: '', teamSelectedData: [], slaveSelectedRowKeys: [], slaveSelectedData: [], slaveInfoSelectedRowKeys: [], slaveInfoSelectedData: [], tableBtnEnabled: true,
      }); // teamSelectedRowKeys: [],
      this.handleGetData('slave', slaveConfig, slaveFilterCondition, undefined, '', false, undefined);
      this.handleGetData('slaveInfo', slaveInfoConfig, slaveFilterCondition, undefined, '', false, undefined);

      if (!commonUtils.isEmpty(clearArray)) {
        for (const item of clearArray) {
          const { confirm, clearFilters } = item;
          confirm();
          clearFilters();
        }
      }
      this.props.onSaveState({
        loading: false,
      });
    }
*/
    handleRefresh = async () => {
      const {
        clearArray, teamConfig, teamFilterCondition, slaveFilterCondition, teamSelectedRowKeys,
      } = this.props;
      let { expKeys } = this.props;
      const addState = await this.handleGetData('team', teamConfig, teamFilterCondition, undefined, '', false, undefined, this.props, true);
      if (addState === undefined) return;
      this.props.onSaveState({
        ...addState,
        clearArray: [],
        searchText: '',
        teamSelectedData: [],
        slaveSelectedRowKeys: [],
        slaveSelectedData: [],
        slaveInfoData: [], /* 刷新后清除slaveInfoData */
        slaveInfoSelectedRowKeys: [],
        slaveInfoSelectedData: [],
        tableBtnEnabled: true,
        machineEnabled: false,
        sortedInfo: {},
      });
      const { teamData } = addState;
      const newIndex = teamData.findIndex(item => item.sId === teamSelectedRowKeys[0]);
      if (newIndex === -1) {
        this.handleCallBack({ ...teamData[0] });
      } else {
        this.handleCallBack({ ...teamData[newIndex] });
      }

      if (!commonUtils.isEmpty(clearArray)) {
        for (const item of clearArray) {
          const { confirm, clearFilters } = item;
          confirm();
          clearFilters();
        }
      }
      /* 刷新后关闭所有expKeys */
      expKeys = [];
      /* 刷新后清除slaveInfoData */
      this.props.onSaveState({
        loading: false, expKeys,
      });
    }

    handleResetTableSearch = () => {
      this.props.onSaveState({ clearArray: [] });
      this.handleRefresh();
    }
    // 进行存储过程按钮存储过程参数解析拼接 根据存储过程按钮参数配置进行解析，配置是json格式 {"sproName":"cal_sss","inMap":"master.sSlaveId,slave.sId"}
    handleBtnEent = (btnConfig, btnName, sValue) => {
      const { masterData } = this.props;
      const sButtonParam = btnConfig.sButtonParam;
      const btn = JSON.parse(sButtonParam);
      const sProName = btn.sproName;
      const inParams = [];
      const inMap = btn.inMap;
      const inlist = inMap.split(',');

      const masterArr = [];
      const slaveArr = [];
      const slaveInfoArr = [];
      const controlArr = [];
      const materialsArr = [];
      const processArr = [];

      if (inlist.length > 0) {
        inlist.forEach((item) => {
          const itemArr = item.split('.');
          if (itemArr.length > 0) {
            const sname = itemArr[0];
            const stype = itemArr[1];
            if (commonUtils.isNotEmptyStr(sname) && sname === 'master') {
              masterArr.push(stype);
            }
            if (commonUtils.isNotEmptyStr(sname) && sname === 'slave') {
              slaveArr.push(stype);
            }
            if (commonUtils.isNotEmptyStr(sname) && sname === 'slaveInfo') {
              slaveInfoArr.push(stype);
            }
            if (commonUtils.isNotEmptyStr(sname) && sname === 'control') {
              controlArr.push(stype);
            }
            if (commonUtils.isNotEmptyStr(sname) && sname === 'materials') {
              materialsArr.push(stype);
            }
            if (commonUtils.isNotEmptyStr(sname) && sname === 'process') {
              processArr.push(stype);
            }
          }
        });

        if (commonUtils.isNotEmptyArr(masterArr) && commonUtils.isNotEmptyObject(masterData)) {
          const addState = {};
          addState.key = 'master';
          const val = [];
          const currVal = {};
          masterArr.forEach((filed) => {
            currVal[`${filed}`] = masterData[`${filed}`];
          });
          val.push(currVal);
          addState.value = val;
          inParams.push({ ...addState });
        }
        if (commonUtils.isNotEmptyArr(slaveArr)) {
          const addState = this.handleProParams('slave', slaveArr);
          if (commonUtils.isNotEmptyObject(addState)) {
            inParams.push({ ...addState });
          }
        }
        if (commonUtils.isNotEmptyArr(slaveInfoArr)) {
          const addState = this.handleProParams('slaveInfo', slaveInfoArr);
          if (commonUtils.isNotEmptyObject(addState)) {
            inParams.push({ ...addState });
          }
        }
        if (commonUtils.isNotEmptyArr(controlArr)) {
          const addState = this.handleProParams('control', controlArr);
          if (commonUtils.isNotEmptyObject(addState)) {
            inParams.push({ ...addState });
          }
        }
        if (commonUtils.isNotEmptyArr(materialsArr)) {
          const addState = this.handleProParams('materials', materialsArr);
          if (commonUtils.isNotEmptyObject(addState)) {
            inParams.push({ ...addState });
          }
        }
        if (commonUtils.isNotEmptyArr(processArr)) {
          const addState = this.handleProParams('process', processArr);
          if (commonUtils.isNotEmptyObject(addState)) {
            inParams.push({ ...addState });
          }
        }
      }

      this.handleProcedureCall(btnConfig, sProName, JSON.stringify({ params: inParams, changeValue: sValue }));
    };
    // 根据配置解析拼接具体参数
    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;
      }
    };
    // 存储过程按钮调用存储过程
    handleProcedureCall = async (btnConfig, proName, proInParam, other) => {
      const { app, sModelsId, sCurrMemoProps } = this.props;
      const value = { sProName: proName, sProInParam: proInParam };
      if (other?.iFlag === 1) {
        value.iFlag = 1;
      }
      const url = `${commonConfig.server_host}procedureCall/doGenericProcedureCall?sModelsId=${sModelsId}`;
      const returnData = (await commonServices.postValueService(app.token, value, url)).data;
      /**
       * 修改日期：2021-03-26
       * 修改人：吕杰
       * 区域：以下 2 行
       * BUG：
       * 说明：执行完接口调用后关闭弹窗
       * 原代码：
       */
      sCurrMemoProps.bVisibleMemo = false;
      this.props.onSaveState({ loading: false, sCurrMemoProps });
      if (returnData.code === 1) {
        message.success(returnData.msg);
        this.handleButtonClick('BtnRefresh');
      } else {
        this.props.getServiceError({ ...returnData, fn: () => this.handleProcedureCall(btnConfig, proName, proInParam, { iFlag: 1 }) });
      }
    }
    /* 点击展开图标时，调用接口获取嵌套字表数据 */
    handleOnExpand = async (expanded, record) => {
      const { sModelsId, expKeys } = this.props;
      let { slaveInfoData } = this.props;
      const { sSlaveId } = record;
      /* 添加移除展开的sId */
      let newExp = commonUtils.isNotEmptyArr(expKeys) ? expKeys : [];
      if (expanded) {
        if (commonUtils.isNotEmptyObject(sSlaveId)) {
          newExp.push(record.sSlaveId);
        }
      } else {
        newExp = newExp.filter(item => item !== record.sSlaveId);
      }
      this.props.onSaveState({ expKeys: newExp });
      let childrenData = [];
      if (commonUtils.isNotEmptyArr(slaveInfoData) && commonUtils.isNotEmptyObject(sSlaveId)) {
        childrenData = slaveInfoData.filter(item => sSlaveId.split('-').includes(item.sId));
      }
      if (expanded && commonUtils.isEmptyArr(childrenData)) {
        if (commonUtils.isNotEmptyObject(sSlaveId)) {
          const planLoadingSate = {};
          planLoadingSate.sId = sSlaveId;
          planLoadingSate.planLoading = true;
          this.props.onSaveState({ planLoadingSate });
          const { token } = this.props;
          const url = `${commonConfig.server_host}workOrderPlan/getProductionPlanInfo?sModelsId=${sModelsId}`;
          const value = { sSlaveId };
          const dataReturn = (await commonServices.postValueService(token, value, url)).data;
          if (dataReturn.code === 1) {
            const returnData = dataReturn.dataset.rows;
            if (commonUtils.isNotEmptyArr(returnData)) {
              childrenData = returnData;
              if (commonUtils.isEmptyArr(slaveInfoData)) {
                slaveInfoData = [];
              }
              childrenData.forEach((child) => {
                // const iIndex = slaveInfoData.findIndex(item => item.sId === child.sId);
                // if (iIndex === -1) {
                //   slaveInfoData.push(child);
                // }
                slaveInfoData.push(child);
              });
            }
            planLoadingSate.planLoading = false;
            this.props.onSaveState({
              planLoadingSate, slaveInfoData,
            });
          } else {
            this.props.getServiceError(dataReturn);
            planLoadingSate.planLoading = false;
            this.props.onSaveState({ planLoadingSate });
          }
        }
      }
    }
    handlePartNameClick =(sName, showConfig, record) => {
      if (commonUtils.isNotEmptyObject(sName) && commonUtils.isNotEmptyObject(showConfig) && commonUtils.isNotEmptyObject(record)) {
        this.props.onSaveState({ workScheduleConfig: showConfig, workScheduleRecord: record, workScheduleVisible: true });
      }
    }
    handleCloseModel = (modelVisible) => {
      this.props.onSaveState({ [modelVisible]: false });
    };
    render() {
      const { masterData, sModelsType, app  } = this.props;
      const imgSrc = commonBusiness.handleAddIcon(masterData, sModelsType, app );
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onToggle={this.handleToggle}
          onSaveData={this.handleSaveData}
          onGetData={this.handleGetSearchData}
          onGetDataInfo={this.handleGetSlaveData}
          onSubmit={this.handleValidateSave}
          onReturnForm={this.handleForm}
          onSearchUpDown={this.handleSearchUpDown}
          onCancel={this.handleCancel}
          onDataChange={this.handleTableChange}
          onBtnPrint={this.handleBtnPrint}
          onChange={this.handleMasterChange}
          onButtonClick={this.handleButtonClick}
          imgSrc={imgSrc}
          style={{ height: '100%' }}
          onTabsCallback={this.handleCallBack}
          onChangeMachine={this.onChangeMachine}
          onResetTableSearch={this.handleResetTableSearch}
          onTitleChange={this.handleTitleChange}
          onBtnEent={this.handleBtnEent}
          onExpand={this.handleOnExpand}
          onGanttChar={this.handleGanttChar}
          onCheckModel={this.handleCheckModel}
          onPartNameClick={this.handlePartNameClick}
          onCloseModel={this.handleCloseModel}
          onChangeTimerPro={this.handleChangeTimer}
        />
      );
    }
  };
};
