/* eslint-disable */
/* eslint-disable prefer-destructuring,no-await-in-loop,no-unused-vars */
import React, { Component } from 'react';
import { message } from 'antd-v4'; // InputNumber Form, Modal,
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 {
        formData, workCenterData, machineData, searchSolution, masterData,
      } = nextProps;
      let {
        masterConfig, isReceive,
      } = nextProps;
      if (formData.length > 0 && commonUtils.isEmptyObject(masterConfig) && searchSolution !== undefined) {
        isReceive = false;
        masterConfig = formData.filter(item => !item.bGrd && item.sTbName === 'mftproductionplan')[0];
        const slaveConfig = formData.filter(item => item.bGrd && item.sTbName === 'mftproductionplan')[0];
        const slaveInfoConfig = formData.filter(item => item.sTbName === 'Sp_productionplan_ControlProcess')[0];
        const slaveColumn = commonFunc.getHeaderConfig(slaveConfig);
        const slaveInfoColumn = commonFunc.getHeaderConfig(slaveInfoConfig);
        const iPageSize = commonUtils.isNotEmptyObject(slaveConfig) && commonUtils.isNotEmptyNumber(slaveConfig.iPageSize) && slaveConfig.iPageSize !== 0 ?
          slaveConfig.iPageSize : commonConfig.pageSize;
        let filterCondition = [];
        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)) {
            filterCondition = JSON.parse(searchSolution[iIndex].sCondition);
          }
        }
        this.handleGetData('slave', slaveConfig, filterCondition, undefined, undefined, false, undefined, nextProps);
        // this.handleGetData('slaveInfo', slaveInfoConfig, filterCondition, undefined, undefined, false, undefined, nextProps);
        this.handleGetProdData('workCenter', 'Sp_Productionplan_Pie_Char', {});
        this.props.onSaveState({
          masterConfig,
          slaveConfig,
          slaveColumn,
          slaveInfoConfig,
          slaveInfoColumn,
          filterCondition,
          enabled: true,
          pageLoading: false,
          moveEnabled: false,
          tableBtnEnabled: true,
          bGantt:false,
          isReceive,
          iPageSize,
        });
      } else if (commonUtils.isNotEmptyArr(workCenterData) && commonUtils.isEmptyObject(machineData) && !isReceive) {
        const addFilter = {};
        addFilter.bFilterName = 'sWorkCenterId';
        addFilter.bFilterCondition = '=';
        addFilter.bFilterValue = workCenterData[0].sWorkCenterId;
        const filterArr = [];
        filterArr.push(addFilter);
        // { bFilter: JSON.stringify(filterArr) }{ bFilter: JSON.stringify(filterArr) };
        this.handleGetProdData('machine', 'Sp_Productionplan_sColumnarStack_Char', { bFilter: JSON.stringify(filterArr) });
        this.props.onSaveState({
          workCenterSelectedRowKeys: [workCenterData[0].sWorkCenterId ? workCenterData[0].sWorkCenterId : workCenterData[1].sWorkCenterId], isReceive: true,
        });
        // for (let i = 0; i < workCenterData.length; i += 1) {
        //   if (workCenterData[i].sWorkCenterId) {
        //     this.props.onSaveState({
        //       workCenterSelectedRowKeys: [workCenterData[i].sWorkCenterId ? workCenterData[0].sWorkCenterId : workCenterData[1].sWorkCenterId], isReceive: true,
        //     });
        //     break;
        //   }
        // }
      }
    }

    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 });
      }
    }
    /**   获取表数据   */
    handleGetData = async (sName, slaveConfig, slaveFiletrCondition, 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;
      const bFilter = [];
      if (!commonUtils.isEmptyArr(slaveFiletrCondition)) {
        bFilter.push(...slaveFiletrCondition);
      }
      if (!commonUtils.isEmptyArr(filterCondition)) {
        bFilter.push(...filterCondition);
      }

      const addState = {};
      const pageNum = commonUtils.isEmpty(page) ? 1 : page;
      addState.pageNum = pageNum;
      addState.pageSize = '';
      const returnData = await this.props.handleGetDataSet({
        name: sName,
        configData: slaveConfig,
        condition: {
          bFilter, sFilterOrderBy: slaveOrderBy, sSqlCondition: conditonValues, sGroupList: sGroupByList, ...addState,
        },
        flag: true,
        clearSelectData,
        isWait,
      });
      if (isWait) {
        return { ...returnData };
      }
    };

    // 搜索 查询
    handleGetSearchData = async (name, slaveConfig, filterCondition) => {
      // 搜索时将数据变动置空，按钮全部读取配置
      this.props.onSaveState({ pageLoading: true, dataChanged: undefined });
      const addState = await this.handleGetData(name, slaveConfig, filterCondition, undefined, undefined, false, undefined, this.props, true);
      if (addState === undefined) return;
      this.props.onSaveState({ ...addState, pageLoading: false });
    };

    // handlePaginationChange = (page) => {
    //   const { slaveConfig, slaveFilterCondition, slaveOrderBy } = this.props;
    //   this.props.handleGetDataSet({
    //     name: 'slave',
    //     configData: slaveConfig,
    //     condition: {
    //       pageNum: page, pageSize: commonConfig.pageSize, bFilter: slaveFilterCondition, sFilterOrderBy: slaveOrderBy,
    //     },
    //   });
    // };

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

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

    handleGetProdData = async (sName, prodName, prodParamsMap, rtFlage) => {
      const { app, sModelsId } = this.props;
      const value = { sProName: prodName, paramsMap: prodParamsMap };
      const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
      const returnData = (await commonServices.postValueService(app.token, value, url)).data;
      if (returnData.code === 1) {
        const outData = returnData.dataset.rows[0].dataSet.outData[0];
        if (outData.sCode === -1) {
          message.error(outData.sReturn);
        } else {
          const proData = returnData.dataset.rows[0].dataSet.proData;
          const xyData = commonUtils.isEmpty(outData.sReturn) ? [] : JSON.parse(outData.sReturn);
          if (rtFlage) {
            return { [`${sName}Data`]: proData, [`${sName}CharData`]: xyData };
          } else {
            this.props.onSaveState({ [`${sName}Data`]: proData, [`${sName}CharData`]: xyData });
          }
        }
      } else {
        this.props.getServiceError(returnData);
      }
    };
    /**   toolbar保存   */
    handleSaveData = async (params) => {
      const {
        token, sModelsId, app, slaveSelectedRowKeys,
      } = this.props;
      const returnData = await commonBusiness.saveData({ token, value: params, sModelsId });
      if (commonUtils.isNotEmptyObject(returnData)) {
        this.handleRefresh();
        const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
        const value = {
          sProName: 'Sp_productionMainPlan_BtnPost',
          paramsMap: {
            sProInParam: JSON.stringify({ params: { key: 'slaveInfo', value: { sId: slaveSelectedRowKeys } } }),
          },
        };
        const returnDataPost = (await commonServices.postValueService(app.token, value, url)).data;
        if (returnDataPost.code === 1) {
          const outData = returnDataPost.dataset.rows[0].dataSet.outData[0];
          if (outData.sCode === -1) {
            message.error(outData.sReturn);
            return false;
          }
        } else {
          this.props.getServiceError(returnDataPost);
          return false;
        }
        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, slaveInfoConfig, slaveInfoData, slaveInfoDelData, app, slaveInfoForSaveConfig,
          } = this.props;
          if (commonUtils.isEmptyArr(slaveData)) {
            message.error(commonFunc.showMessage(app.commonConst, 'slaveNotNull')); // 从表不能为空！
            this.props.onSaveState({
              loading: false,
            });
            return;
          }
          if (!commonBusiness.validateTable(slaveConfig, slaveData)) {
            this.props.onSaveState({
              loading: false,
            });
            return;
          }
          // if (commonUtils.isEmptyArr(slaveInfoData)) {
          //   message.error(commonFunc.showMessage(app.commonConst, 'slaveNotNull')); // 从表不能为空！
          //   this.props.onSaveState({
          //     loading: false,
          //   });
          //   return;
          // }
          // if (!commonBusiness.validateTable(slaveInfoConfig, slaveInfoData)) {
          //   this.props.onSaveState({
          //     loading: false,
          //   });
          //   return;
          // }
          const data = [];
          data.push(commonBusiness.mergeData('slave', slaveConfig.sTbName, slaveData, slaveDelData));
          data.push(commonBusiness.mergeData('slaveInfo', 'mftworkorderprocess', slaveInfoData, slaveInfoDelData));
          this.handleSaveData({ data, sClientType: '1' });
        }
      });
    };

    /** 表格数据更改 */
    // name 不写完整的state名称作用为了要用到total // (name, changeValue, sId, dropDownData)
    handleTableChange = async (name, sFieldName, changeValue, sId, dropDownData) => {
      // 埋入数据修监听点
      this.props.onSaveState({
        dataChanged: true,
      });
      this.props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, false);
    };
    // 打印
    handleBtnPrint = (sActiveId, checked) => {
      const {
        app, sModelsId, slaveConfig, slaveSelectedRowKeys, slaveFilterCondition, reportData,
      } = this.props;
      const { token } = app;
      const newfilterCondition = slaveFilterCondition === undefined ? [] : [...slaveFilterCondition];

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

      const queryFilter = {};
      queryFilter[slaveConfig.sId] = { bFilter: newfilterCondition };
      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 = (itag) => {
      if (itag === 'BtnUnifiedPlanning') {
        let unifiedPlanningConfig = {};
        const iIndex = this.props.masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === itag);
        if (iIndex > -1) {
          unifiedPlanningConfig = this.props.masterConfig.gdsconfigformslave[iIndex];
          this.handleBtnChoose('unifiedPlanning', 'BtnUnifiedPlanning', unifiedPlanningConfig);
        }
      } else if (itag === 'BtnRefresh') {
        this.handleRefresh();
      } else if (itag === 'BtnOut') {
        this.handleOut();
      } else if (itag === 'BtnDesignFunction') {
        this.handleDesignFunction();
      }
      this.handleGetProdData('workCenter', 'Sp_Productionplan_Pie_Char', {});
      const { workCenterSelectedRowKeys, workCenterData } = this.props;
      if (commonUtils.isNotEmptyArr(workCenterData)) {
        const addFilter = {};
        addFilter.bFilterName = 'sWorkCenterId';
        addFilter.bFilterCondition = '=';
        addFilter.bFilterValue = commonUtils.isEmpty(workCenterSelectedRowKeys) ? workCenterData[0].sWorkCenterId : workCenterSelectedRowKeys;
        const filterArr = [addFilter];
        this.handleGetProdData('machine', 'Sp_Productionplan_sColumnarStack_Char', { bFilter: JSON.stringify(filterArr) });
      }
    };

    handleDesignFunction = () => {
      this.props.onSaveState({ visibleStatement: true });
    };

    handleBtnChoose = async (name, sControlName, chooseConfig) => {
      const { token } = this.props;
      const url = `${commonConfig.server_host}/gdsmodule/getGdsmoduleById/${chooseConfig.sActiveId}?sModelsId=${chooseConfig.sActiveId}`;
      const dataReturn = (await commonServices.getService(token, url)).data;
      if (dataReturn.code === 1) {
        const [returnData] = dataReturn.dataset.rows;
        this.props.onSaveState({ [`${name}ChooseVisible`]: true, [`${name}ChooseData`]: returnData, [`${name}Config`]: chooseConfig });
      } else {
        this.props.getServiceError(dataReturn);
      }
    };
    /**   处理选择行发生改变   */
    handleTableSelectRowChange = (name, selectedRowKeys) => {
      /*   外置处理业务   */
      const { slaveInfoData } = this.props;
      const addState = {};
      const slaveInfoSelectedRowKeys = [];
      if (name === 'slave') {
        // selectedRowKeys.includes(item)
        const slaveInfoselectData = slaveInfoData.filter(item => selectedRowKeys.includes(item.sId));
        if (slaveInfoselectData.length > 0) {
          slaveInfoselectData.forEach((item) => {
            slaveInfoSelectedRowKeys.push(item.sSlaveId);
          });
        }
        addState.enabled = true;
        addState.slaveInfoSelectedRowKeys = slaveInfoSelectedRowKeys;
      } else if (name === 'slaveInfo') {
        addState.enabled = true;
        addState.slaveSelectedRowKeys = [];
      }
      this.props.onSaveState({
        [`${name}SelectedRowKeys`]: selectedRowKeys, searchUpDownData: {}, ...addState,
      });
    };

    handleMasterChange = (name, sFieldName, changeValue, sId, dropDownData, isWait) => {
      if (isWait) {
        return this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, isWait);
      } else {
        this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, isWait);
      }
    };

    handleSwitchChange = (value) => {
      this.props.onSaveState({ dragAndDropSwitch: value });
    };

    // 进行存储过程按钮存储过程参数解析拼接 根据存储过程按钮参数配置进行解析，配置是json格式 {"sproName":"cal_sss","inMap":"master.sSlaveId,slave.sId"}
    // handleBtnEent = async (btnConfig) => {
    //   const { masterData } = this.props;
    //   const sButtonParam = btnConfig.sButtonParam;
    //   // const sButtonParam = '{"sproName":"cal_sss","inMap":"master.sSlaveId,slave.sId"}';
    //   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(sProName, JSON.stringify({ params: inParams }));
    // };
    // // 根据配置解析拼接具体参数
    // 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 (proName, proInParam) => {
    //   const { app, sModelsId } = this.props;
    //   const value = { sProName: proName, sProInParam: proInParam };
    //   const url = `${commonConfig.server_host}procedureCall/doGenericProcedureCall?sModelsId=${sModelsId}`;
    //   const returnData = (await commonServices.postValueService(app.token, value, url)).data;
    //   if (returnData.code === 1) {
    //     this.handleRefresh();
    //   } else {
    //     this.props.getServiceError(returnData);
    //   }
    // }
    handleChartClick = (chartName, data) => {
      const {
        dispatch, masterConfig, workCenterSelectedRowKeys, machineCharData, bProductionPlanOutside,
      } = this.props;
      if (bProductionPlanOutside) { /* 跳转到发外排程 */
        const filterData = masterConfig.gdsconfigformslave.filter(item => item.sControlName.includes('JumpTo.chartOutside'));
        const sActiveId = filterData[0].sActiveId;
        const filterArr = [];
        const otherConditionArr = [];
        if (commonUtils.isNotEmptyArr(filterData)) {
          dispatch({
            type: 'content/onRouter',
            payload: {
              url: `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`, /*   接口地址   */
              filterCondition: filterArr,
              otherCondition: otherConditionArr,
            },
          });
        }
      } else { /* 跳转到生产排程 */
        const sMachineName = data[machineCharData.xName];
        let { sActiveId } = masterConfig.gdsconfigformslave.filter(item => item.sControlName.includes(chartName))[0];
        sActiveId = sActiveId === '1' ? commonUtils.isEmpty(data.sFormId) ? data.sSrcFormId : data.sFormId : sActiveId;
        const filterArr = [];
        filterArr.push({ bFilterName: 'sWorkCenterId', bFilterCondition: '=', bFilterValue: workCenterSelectedRowKeys[0] });
        const otherConditionArr = [];
        otherConditionArr.push({ bFilterName: 'sMachineId', bFilterCondition: '=', bFilterValue: data[`sMachineId${sMachineName}`] });
        const treeKey = data[`sMachineId${sMachineName}`] + workCenterSelectedRowKeys[0];
        const sWorkCenterName = this.props.workCenterData.filter(o => o.sWorkCenterId === workCenterSelectedRowKeys[0])[0].sWorkCenterName;
        dispatch({
          type: 'content/onRouter',
          payload: {
            url: `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`, /*   接口地址   */
            filterCondition: filterArr,
            otherCondition: otherConditionArr,
            copyTo: {
              treeKey,
              sWorkCenterName: sWorkCenterName
            }
          },
        });
      }
    };
    handleRefresh = () => {
      const {
        slaveConfig, slaveInfoConfig, slaveFilterCondition, slaveInfoFilterCondition,
      } = this.props;
      const { expKeys } = this.props;
      this.props.onSaveState({
        sortedInfo: {}, clearArray: [], searchText: '', slaveSelectedRowKeys: [], slaveSelectedData: [], slaveInfoSelectedRowKeys: [], slaveInfoSelectedData: [], tableBtnEnabled: true,
      });
      console.log('回刷', 1111);
      this.handleGetData('slave', slaveConfig, slaveFilterCondition, undefined, undefined, true, undefined, this.props).finally(() => {
        /* 刷新后关闭所有expKeys */
        // expKeys = [];
        this.props.onSaveState({
          loading: false,
          expKeys: [],
          slaveInfoData: [],
        });
      });
      // this.handleGetData('slaveInfo', slaveInfoConfig, slaveInfoFilterCondition, undefined, undefined, true, undefined, this.props);
      const { clearArray } = this.props;
      if (!commonUtils.isEmpty(clearArray)) {
        for (const item of clearArray) {
          const { confirm, clearFilters } = item;
          confirm();
          clearFilters();
        }
      }
      /* 刷新后关闭所有expKeys */
      // expKeys = [];
      this.props.onSaveState({
         expKeys,
      });
    }

    /* 导出Excel */
    // handleOut = () => {
    //   const {
    //     slaveConfig, slaveFilterCondition, slaveOrderBy, sGroupByList,
    //   } = this.props;
    //   let url = `${commonConfig.server_host}excel/export/${slaveConfig.sId}?sModelsId=${slaveConfig.sParentId}&token=${this.props.app.token}`;
    //   if (commonUtils.isNotEmptyArr(slaveFilterCondition)) {
    //     url = `${url}&bFilter=${encodeURIComponent(JSON.stringify(slaveFilterCondition))}`;
    //   }
    //   if (slaveOrderBy !== undefined && slaveOrderBy !== '' && Object.keys(slaveOrderBy).length > 0) {
    //     url = `${url}&sFilterOrderBy=${encodeURIComponent(JSON.stringify(slaveOrderBy))}`;
    //   }
    //   if (commonUtils.isNotEmptyArr(sGroupByList)) {
    //     url = `${url}&sGroupList=${encodeURIComponent(JSON.stringify(sGroupByList))}`;
    //   }
    //   window.open(url);
    // };
    handleTitleChange = async (name, slavePagination, filters, sorter, extra) => {
      // 点击分页的时候不需要埋点 current
      let dataChanged = false;
      if (
        (slavePagination.total === this.props.slavePagination.total)
        &&
        (slavePagination.current === this.props.slavePagination.current)
        &&
        (slavePagination.pageSize === this.props.slavePagination.pageSize)
      ) {
        // 埋入数据修监听点
        dataChanged = true;
      }
      // this.props.onSaveState({
      //   pageLoading: true, //tableBtnEnabled: false,
      // });
      const tableBtnEnabled = commonUtils.isEmptyObject(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;
        }
      }
      // 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, slavePagination, pageLoading: false, tableBtnEnabled, dataChanged,
      });
    };

    handleSelectCancel = () => {
      this.props.onSaveState({ unifiedPlanningChooseVisible: false });
    }
    // 进行存储过程按钮存储过程参数解析拼接 根据存储过程按钮参数配置进行解析，配置是json格式 {"sproName":"cal_sss","inMap":"master.sSlaveId,slave.sId"}
    handleBtnEent = (btnConfig) => {
      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 }));
    };
    // 根据配置解析拼接具体参数
    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 } = 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;
      if (returnData.code === 1) {
        message.success(returnData.msg);
        this.handleButtonClick('BtnRefresh');
      } else {
        this.props.onSaveState({ loading: false });
        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 { sId } = record;
      const sProductionPlanId = sId;
      /* 添加移除展开的sId */
      let newExp = commonUtils.isNotEmptyArr(expKeys) ? expKeys : [];
      if (expanded) {
        newExp.push(record.sId);
      } else {
        newExp = newExp.filter(item => item !== record.sId);
      }
      this.props.onSaveState({ expKeys: newExp });
      let childrenData = [];
      /* 查看是否已经获取到明细表数据 */
      // if (commonUtils.isNotEmptyArr(slaveInfoData)) {
      //   childrenData = slaveInfoData.filter(item => item.sProductionPlanId === sProductionPlanId);
      // }
      if (expanded && commonUtils.isEmptyArr(childrenData)) {
        if (commonUtils.isNotEmptyObject(sProductionPlanId)) {
          const planLoadingSate = {};
          planLoadingSate.sId = sProductionPlanId;
          planLoadingSate.planLoading = true;
          this.props.onSaveState({ planLoadingSate });
          const { token } = this.props;
          const url = `${commonConfig.server_host}workOrderPlan/getControlProcess/${sProductionPlanId}?sModelsId=${sModelsId}`;
          const dataReturn = (await commonServices.getService(token, 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);
                }
              });
            }
            planLoadingSate.planLoading = false;
            this.props.onSaveState({
              planLoadingSate, slaveInfoData,
            });
          } else {
            this.props.getServiceError(dataReturn);
            planLoadingSate.planLoading = false;
            this.props.onSaveState({ planLoadingSate });
          }
        }
      }
    }

    handleViewClick = (name, sName, record, index, myConfig) => {
      /* 生产主计划点击机台跳转到生产排程 */
      if (sName === 'sMachineName') {
        const { slaveInfoConfig, dispatch } = this.props;
        const { sMachineName, sMachineId, sWorkCenterId } = record;
        const filterData = slaveInfoConfig.gdsconfigformslave.filter(item => item.sName === 'sMachineName');
        if (commonUtils.isNotEmptyArr(filterData)) {
          let { sActiveId } = filterData[0];
          sActiveId = sActiveId === '1' ? commonUtils.isEmpty(record.sFormId) ? record.sSrcFormId : record.sFormId : sActiveId;
          const filterArr = [];
          filterArr.push({ bFilterName: 'sWorkCenterId', bFilterCondition: '=', bFilterValue: sWorkCenterId });
          const otherConditionArr = [];
          otherConditionArr.push({ bFilterName: 'sMachineId', bFilterCondition: '=', bFilterValue: sMachineId });
          // filterArr.push({ bFilterName: 'sMachineId', bFilterCondition: '=', bFilterValue: sMachineId });
          const treeKey = record.sMachineId + record.sWorkCenterId;
          const sWorkCenterName = record.sWorkCenterName;
          console.log(record, 'record');

          dispatch({
            type: 'content/onRouter',
            payload: {
              url: `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`, /*   接口地址   */
              filterCondition: filterArr,
              otherCondition: otherConditionArr,
              copyTo: {
                treeKey,
                sWorkCenterName: sWorkCenterName,
                sWorkOrderProcessId: record.sWorkOrderProcessId
              }
            },
          });
        }
      } else if (sName === 'myTableConfig') {
        this.handleQuickViewClick(name, sName, record, index, myConfig);
      } else {
        this.props.onViewClick(name, sName, record, index);
      }
    }
    /* 获取表格数据 */
    handleGetTableConfig = async (name, sModelsId) => {
      if(commonUtils.isNotEmptyObject(sModelsId)) {
        const newConfig = await this.props.onGetTableConfig(name, sModelsId);
        if(commonUtils.isNotEmptyObject(newConfig)) {
          const newColumn = commonFunc.getHeaderConfig(newConfig);
          this.props.onSaveState({[`${[name]}Config`]: newConfig, [`${[name]}Column`]: newColumn })
        }
      }
    }
    /* 获取表格数据 */
    handleGetTableConfig = async (name, sModelsId) => {
      if(commonUtils.isNotEmptyObject(sModelsId)) {
        const newConfig = await this.props.onGetTableConfig(name, sModelsId);
        if(commonUtils.isNotEmptyObject(newConfig)) {
          const newColumn = commonFunc.getHeaderConfig(newConfig);
          this.props.onSaveState({[`${[name]}Config`]: newConfig, [`${[name]}Column`]: newColumn })
        }
      }
    }
    /* 快捷键跳转 */
    handleQuickViewClick = async (name, sName, record, index , myConfigArr) => {
      const {
        slaveConfig,
        slaveData,
        dispatch,
        slaveFilterCondition,
        slavePagination,
        slaveOrderBy,
        sModelsType,
        formRoute,
        treeFilterCondition,
        app,
        iPageSize,
        sModelsId,
        // slaveSelectedData,
        // masterData,
        // employeeConfig,
      } = this.props;
      console.log('myConfigArr',myConfigArr)
      let picArr = [];
      if(commonUtils.isNotEmptyArr(myConfigArr)) {
        picArr = myConfigArr;
      }

      if (picArr.length > 0) {
        const getConfig = this.handleGetTableConfig;
        const tableDataRow = record;
        const iIndex = index;
        const [{ sActiveId }] = picArr;
        let [{ sActiveKey }] = picArr;
        const sFormId = sActiveId === '1' ? commonUtils.isEmpty(tableDataRow.sFormId) ? tableDataRow.sSrcFormId : tableDataRow.sFormId : sActiveId;
        if (commonUtils.isNotEmptyObject(sActiveKey) && sActiveKey.includes('.')) { /* 接口按钮跳转 如果有slave.对应字段 则需要取出对应字段 */
          const index = sActiveKey.lastIndexOf('.');
          sActiveKey = sActiveKey.substring(index + 1, sActiveKey.length);
        }
        const sNameUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sFormId}?sModelsId=${sFormId}&sName=${formRoute}`;
        const filterCondition = [];
        const conditionValues = this.props.getSqlCondition(picArr[0], name, tableDataRow);
        if (!commonUtils.isEmpty(conditionValues)) {
          Object.keys(conditionValues).forEach((item) => {
            if ((item === 'tStartDate_pro' || item.substring(0, 1) === 'p')) {
              if (!commonUtils.isEmpty(conditionValues[item]) && conditionValues[item].length >= 2) {
                const tStartDate = moment(conditionValues[item][0]).format(this.sDateFormat);
                const tEndDate = moment(conditionValues[item][1]).add(1, 'days').format(this.sDateFormat);
                filterCondition.push({
                  bFilterName: item,
                  bFilterCondition: '=',
                  bFilterValue: `${tStartDate},${tEndDate}`,
                });
              }
            } else if ((item === 'mStartDate_pro' || item.substring(0, 1) === 'm')) {
              if (!commonUtils.isEmpty(conditionValues[item])) {
                const tStartDate = moment(conditionValues[item]).startOf('month').format(this.sDateFormat);
                const tEndDate = moment(conditionValues[item]).endOf('month').add(1, 'days').format(this.sDateFormat);
                filterCondition.push({
                  bFilterName: `t${item.substring(1, item.length)}`,
                  bFilterCondition: '=',
                  bFilterValue: `${tStartDate},${tEndDate}`,
                });
              }
            } else if (item.substring(0, 1) === 't') {
              filterCondition.push({
                bFilterName: item,
                bFilterCondition: '=',
                bFilterValue: moment(conditionValues[item]).format(this.sDateFormat),
              });
            } else {
              filterCondition.push({
                bFilterName: item,
                bFilterCondition: '=',
                bFilterValue: conditionValues[item],
              });
            }
          });
        }
        this.props.dispatch({
          type: 'content/onRouter',
          payload: {
            url: sNameUrl,
            refresh: getConfig.bind(this, name, sModelsId), /*   刷新方法   */
            sTabId: commonUtils.createSid(),
            // sParentId: this.state.sTabId,
            urlDataType: 'newPane',
            checkedId: myConfigArr[0].sId,
            sName: myConfigArr[0].sName,
            bFilter: slaveFilterCondition,
            pageSize: commonConfig.pageSize,
            pages: slavePagination,
            currentData: slaveData,
            conditonValues: conditionValues,
            newKey: tableDataRow[sActiveKey],
            currentIndex: iIndex,
            filterCondition,
          },
        });
      }
    };
    /* 获取稽查模型数据 */
    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_GetPlanAPSstate';
        obj.paramsMap = {
        };
      }
      const value = {
        sProName: obj.sProcedureName,
        bFilter: slaveFilterCondition,
      };
      if (other?.iFlag === 1) {
        value.iFlag = 1;
      }
      this.props.onSaveState({ pageLoading: true });
      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 }) });
      }
    };
    handleCloseModel = (modelVisible) => {
      this.props.onSaveState({ [modelVisible]: false });
    };
    handlePartNameClick =(sName, showConfig, record) => {
      if (commonUtils.isNotEmptyObject(sName) && commonUtils.isNotEmptyObject(showConfig) && commonUtils.isNotEmptyObject(record)) {
        this.props.onSaveState({ workScheduleConfig: showConfig, workScheduleRecord: record, workScheduleVisible: true });
      }
    }
    /* 获取甘特图数据 */
    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_WorkOrder_GtCharAll';
        char.paramsMap = {
        };
      }
      let charGanttData = {};
      const value = {
        sProName: char.sProcedureName,
        paramsMap: char.prodParamsMap,
        bFilter: slaveFilterCondition,
      };
      this.props.onSaveState({ pageLoading: true });
      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);
      }
    };

    render() {
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onToggle={this.handleToggle}
          onSaveData={this.handleSaveData}
          onGetData={this.handleGetSearchData.bind(this, 'slave')}
          onGetDataInfo={this.handleGetSearchData.bind(this, 'slaveInfo')}
          onSubmit={this.handleValidateSave}
          // onTableSelectRowChange={this.handleTableSelectRowChange}
          onReturnForm={this.handleForm}
          onSearchUpDown={this.handleSearchUpDown}
          onDataChange={this.handleTableChange}
          onBtnPrint={this.handleBtnPrint}
          onChange={this.handleMasterChange}
          onButtonClick={this.handleButtonClick}
          onSwitchChange={this.handleSwitchChange}
          onGetProdData={this.handleGetProdData}
          onGetChartClick={this.handleChartClick}
          onGetBtnEnabled={this.handleBtnEnabled}
          onRefresh={this.handleRefresh}
          onTitleChange={this.handleTitleChange}
          onSelectCancel={this.handleSelectCancel}
          style={{ height: '100%' }}
          onExpand={this.handleOnExpand}
          onViewClick={this.handleViewClick}
          onCheckModel={this.handleCheckModel}
          onCloseModel={this.handleCloseModel}
          onPartNameClick={this.handlePartNameClick}
          onGanttChar={this.handleGanttChar}
          // onBtnEent={this.handleBtnEent}
        />
      );
    }
  };
};
