/* eslint-disable */

import React, { Component, useEffect, useState, useRef } from "react";
import { Form } from "@ant-design/compatible";
// import "@ant-design/compatible/assets/index.css";
import {
  Row,
  Col,
  Checkbox,
  Layout,
  Spin,
  Tabs,
  Avatar,
  Button,
  message,
  Table,
  Upload,
  Radio,
  Space,
  Modal,
  List,
  Input,
  Divider,
  Collapse,
} from "antd-v4";
import {
  UploadOutlined,
  RightOutlined,
  DoubleRightOutlined,
  PlusOutlined,
  DeleteOutlined
} from "@ant-design/icons";
import CommonNewSales from "@/components/Common/CommonNewTabBillEvent"; /* 继承销售模块业务功能 */
import * as commonFunc from "@/components/Common/commonFunc"; /* 通用单据方法 */ /* 通用单据方法 */
import Toolbar from "@/components/Common/ToolBar/ToolBarNew";
import StaticEditTable from "@/components/Common/CommonTable"; /* 可编辑表格 */
import styles from "@/index.less";
import AssignmentField from "./AssignmentField";
import CommonView from "@/components/Common/CommonView";
import CommonViewTable from "@/components/Common/CommonViewTable";
import CommonBase from "@/components/Common/CommonBase"; /* 获取配置及数据 */
import * as commonBusiness from "@/components/Common/commonBusiness"; /* 单据业务功能 */
import commonConfig from "@/utils/config";
import * as commonUtils from "@/utils/utils"; /* 通用方法 */
import * as commonServices from "@/services/services"; /*   服务类   */
import AddIcon from "@/assets/add.svg";
import DisableAddIcon from "@/assets/disableadd.svg";
import CopyIcon from "@/assets/copy.svg";
import CopyAllIcon from "@/assets/copyall.svg";
import DisableCopyIcon from "@/assets/disablecopy.svg";
import DisableCopyAllIcon from "@/assets/disablecopyall.svg";
import DelIcon from "@/assets/delete.svg";
import DisableDelIcon from "@/assets/disabledelete.svg"; /* 获取配置及数据 */
import AntdDraggableModal from "@/components/Common/AntdDraggableModal";
import CommonListSelect from "./CommonListSelect";
import CommonViewDragable from "@/components/Common/CommonViewDragable";
import CommonListSelectFlex from "@/components/Common/CommonListSelectFlex";
import ContextMenuModal from '@/components/Common/ContextMenuModal';

const width = "18px";
const height = "18px";
const setAdd = {
  title: "增加",
  width: { width },
  height: { height },
  img: <img src={AddIcon} alt="添加" width={width} height={height} />,
  disableimg: (
    <img src={DisableAddIcon} alt="删除" width={width} height={height} />
  )
};
const setCopy = {
  title: "复制",
  width: { width },
  height: { height },
  img: <img src={CopyIcon} alt="复制" width="20px" height="20px" />,
  disableimg: (
    <img src={DisableCopyIcon} alt="复制" width="20px" height="20px" />
  )
};
const setCopyAll = {
  title: "复制部件",
  width: { width },
  height: { height },
  img: <img src={CopyAllIcon} alt="复制部件" width="16px" height="16px" />,
  disableimg: (
    <img src={DisableCopyAllIcon} alt="复制部件" width="16px" height="16px" />
  )
};
const setDelete = {
  title: "删除",
  width: { width },
  height: { height },
  img: <img src={DelIcon} alt="删除" width={width} height={height} />,
  disableimg: (
    <img src={DisableDelIcon} alt="删除" width={width} height={height} />
  )
};

const { Header, Content } = Layout;
const { TabPane } = Tabs;
const { Panel } = Collapse;
let _this;
class CommonNewBill extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentTab: "10",
      colTabKey: 12,
      activeKey: ['1', '2'],
      processTableId: `processTableId_${commonUtils.createSid()}`,
    };
    _this = this;
    this.commonViewHeight = 260;
    this.maxTableNum = 12;
  }

  componentWillReceiveProps() {
    if (this.commonViewRef) {
      const commonViewHeight =
        this.commonViewRef.getBoundingClientRect().height + 147 + 30;
      if (commonViewHeight > 177) {
        this.commonViewHeight = commonViewHeight;
      }
    }

    if (!this.hasSeletLastTab) {
      const {
        formData = [],
        onlySlave,
        onlySlave0,
        onlySlave1,
        onlyslave2,
        onlyslave3,
        onlyslave4,
        onlyslave5,
        onlyslave6,
        onlyslave7,
        onlyslave8,
        onlyslave9,
        onlyslave10,
        masterConfig = {},
        sModelsId,
      } = this.props;

      if (commonUtils.isNotEmptyArr(formData)) {
        let defaultTab = null;

        const { gdsconfigformslave = [] } = masterConfig;
        if (commonUtils.isNotEmptyArr(gdsconfigformslave)) {
          const iIndex = gdsconfigformslave.findIndex(
            item =>
              item.bVisible &&
              item.sControlName &&
              item.sControlName.substring(0, 1) === "z" &&
              item.sDefault
          );
          if (iIndex !== -1) {
            const defaultShowName = gdsconfigformslave[iIndex].showName;
            const fomrDataIndex = formData.findIndex(
              item => item.showName === defaultShowName
            );
            const tabKeyList = [
              "10",
              "20",
              "30",
              "40",
              "50",
              "60",
              "70",
              "80",
              "90",
              "100",
              "110",
              "150"
            ];
            if (fomrDataIndex > 0) {
              defaultTab = tabKeyList[fomrDataIndex - 1];
            }
          }
        }

        if (defaultTab) {
          this.hasSeletLastTab = true;
          this.setState({ currentTab: defaultTab });
          return;
        }

        let currentTab = null;
        if (onlySlave) {
          currentTab = "10";
        }
        if (onlySlave0) {
          currentTab = "20";
        }
        if (onlySlave1) {
          currentTab = "30";
        }
        if (onlyslave2) {
          currentTab = "40";
        }
        if (onlyslave3) {
          currentTab = "50";
        }
        if (onlyslave4) {
          currentTab = "60";
        }
        if (onlyslave5) {
          currentTab = "70";
        }
        if (onlyslave6) {
          currentTab = "80";
        }
        if (onlyslave7) {
          currentTab = "90";
        }
        if (onlyslave8) {
          currentTab = "100";
        }
        if (onlyslave9) {
          currentTab = "110";
        }
        if (onlyslave10) {
          currentTab = "150";
        }
        if(sModelsId === '12710101117172075846130') {
          currentTab =  "10";
        }
        if (currentTab) {
          this.hasSeletLastTab = true;
          this.setState({ currentTab });
        }
      }
    }
  }

  componentDidUpdate() {
    if (window.refreshTabFlag) {
      clearTimeout(this.flagTimer);
      this.flagTimer = setTimeout(() => {
        window.refreshTabFlag = 0;
        this.props.onSaveState({ randomFlag: new Date().getTime() });
      }, 500);
    }
  }

  isSColorSerialMemo = React.createRef();

  resetSColorSerialMemo = () => {
    this.isSColorSerialMemo.current = false;
  }

  /**   行选择   */
  onRowClick = (name, record) => {
    if (name === "slave0Child1") {
      this.props.onSaveState({ slave0SelectedRowKeys:[], slave0Child1SelectedRowKeys: [record.sId]})
    }
  };

  onChange = checkedValues => {
    this.props.onSaveState({
      dataPersonArray: checkedValues
    });
  };
  getMenuStatus = menu => {
    if (menu.sControlName === "BtnImport") {
      return !this.props.enabled;
    }
  };

  /**   图片上传后执行函数    */
  handleUploadChange = (info, name) => {
    const { file } = info;
    if (file.response && file.response.code === 1) {
      const sPicturePath = file.response.dataset.rows[0].savePathStr;
      const uploadInfo = {
        sPicturePath,
        sFileName: file.name
      };
      const tableDataRow = this.props.onDataRowAdd(name, true);
      const {
        [`${name}Column`]: tableColumn,
        masterData,
        [`${name}Data`]: tableData
      } = this.props;
      tableColumn.forEach(slaveChild => {
        const ckey = slaveChild.dataIndex;
        if (ckey === "sProductNo" || ckey === "sProductName") {
          tableDataRow[ckey] =
            masterData[ckey] !== undefined ? masterData[ckey] : "";
        } else if (ckey === "iOrder") {
          tableDataRow[ckey] = "";
        } else if (file.response && file.response.code === 1) {
          if (uploadInfo[ckey] !== undefined) {
            tableDataRow[ckey] = uploadInfo[ckey];
          }
        }
      });
      tableData.push(tableDataRow);
      this.props.onSaveState({ [`${name}Data`]: tableData, enabled: true });
    } else if (file.response && file.response.code === -1) {
      message.error(file.response.msg);
    }
  };
  handleUploadPropsSales = () => {
    const { masterData, sModelsType } = this.props;
    if (commonUtils.isNotEmptyObject(masterData)) {
      const sCustomerId = commonUtils.isEmptyStr(masterData.sCustomerId)
        ? undefined
        : masterData.sCustomerId;
      let existCustomerId = false;
      if (
        sModelsType.includes("sales/") &&
        commonUtils.isNotEmptyStr(sCustomerId)
      ) {
        existCustomerId = true;
      } else if (!sModelsType.includes("sales/")) {
        existCustomerId = true;
      }
      return {
        disabled: !this.props.enabled || !existCustomerId /*   是否可用   */,
        style: {
          display: commonUtils.convertBooleanToDisplayBlock(true)
        } /*   是否显示   */
      };
    }
  };

  handleOk = async (flag, tmpCheck, isWait) => {
    const {
      sModelsId,
      masterData,
      app,
      checkConditions,
      sCheckModelId,
      checkPersonData,
      currentId,
      masterConfig,
      slaveConfig,
      checkConfig
    } = this.props;
    const { currentPane } = app;
    const bCkxTmpCheck = app.systemData.filter(
      item => item.sName === "CkxTmpCheck"
    )[0].sValue;
    if (bCkxTmpCheck === "1") {
      const returnData = await this.props.onDataAudit(flag, tmpCheck, isWait);
      if (returnData.code === 1) {
        if (returnData.dataset.rows[0].dataSet.outData[0].sCode === 1) {
          this.props.onGetData(masterConfig, slaveConfig, checkConfig);
          message.success(returnData.msg);
        } else {
          message.error(returnData.dataset.rows[0].dataSet.outData[0].sReturn);
        }
      } else {
        /*   失败   */
        this.props.getServiceError(returnData);
      }
    } else {
      const dataPersonArray = commonUtils.isEmptyObject(
        this.props.dataPersonArray
      )
        ? []
        : this.props.dataPersonArray;
      if (commonUtils.isEmptyObject(dataPersonArray)) {
        checkPersonData.forEach(item => {
          dataPersonArray.push(item.sUserId);
        });
      }
      const dataPersonString = dataPersonArray.join(",");
      const url = `${
        commonConfig.server_host
      }business/getProData?sModelsId=${sModelsId}`;
      const value = {
        sProName: "Sp_System_AutoSendCheckMsg",
        paramsMap: {
          sFormGuid: sModelsId,
          sBillKey: currentPane.sProcName,
          sTbName: masterConfig.sTbName,
          sGuid: masterData.sId,
          sBillNo: masterData.sBillNo,
          sCheckCondition: checkConditions,
          sMemo: "",
          sCheckModelGuid: sCheckModelId,
          sCheckPerson: dataPersonString
        }
      };

      const returnData = (await commonServices.postValueService(
        app.token,
        value,
        url
      )).data;
      if (returnData.code === 1) {
        const noCheckMsg = commonFunc.showMessage(
          app.commonConst,
          "NoCheckMsg"
        ); /* 您有消息待审核 */
        if (returnData.dataset.rows[0].dataSet.outData[0].sCode === 1) {
          this.props.handleSendSocketMessage(
            "examine",
            "showImg",
            currentId,
            dataPersonString,
            noCheckMsg,
            null
          );
          const urlCanCheckBill = `${
            commonConfig.server_host
          }checkModel/getCanCheckBill?sModelsId=${sModelsId}`;
          const valueCanCheckBill = {
            sCheckModelId,
            checkPersonData,
            sBillId: masterData.sId
          };
          const returnCanCheckBill = (await commonServices.postValueService(
            app.token,
            valueCanCheckBill,
            urlCanCheckBill
          )).data;
          if (returnCanCheckBill.code === 1) {
            if (returnCanCheckBill.dataset.rows[0].iCount === 1) {
              this.props.onDataAudit(1, 1);
              this.props.onSaveState({
                visible: false
              });
              return;
            }
          } else {
            /*   失败   */
            this.props.getServiceError(returnCanCheckBill);
          }
          this.props.handleSendSocketMessage(
            "reflush",
            "showImg",
            currentId,
            dataPersonString,
            noCheckMsg,
            null
          );
          message.success(returnData.msg);
        } else {
          message.error(returnData.dataset.rows[0].dataSet.outData[0].sReturn);
        }
      } else {
        /*   失败   */
        this.props.getServiceError(returnData);
      }
    }
    this.props.onSaveState({
      visible: false
    });
  };

  handleCancel = () => {
    this.props.onSaveState({
      visible: false
    });
  };
  handleTableModal = async () => {
    const {
      sModelsId,
      controlData,
      masterData,
      slaveData,
      controlConfig,
      slaveSelectedRowKeys,
      enabled,
      slaveConfig
    } = this.props;
    const addState = {};
    if (this.props.sModelsType === "sales/salesOrder") {
      const iSlaveIndex = slaveData.findIndex(
        item => item.sId === slaveSelectedRowKeys[0]
      );
      const iIndex = controlData.findIndex(
        item => item.sSlaveId === slaveSelectedRowKeys[0]
      );
      if (iIndex === -1 && iSlaveIndex > -1 && enabled) {
        const allTableData = {};
        allTableData.master = masterData;
        allTableData.slaveData = slaveData;
        let dropdownProductClassifyId;
        const slaveIndex = slaveConfig.gdsconfigformslave.findIndex(
          item => item.sName === "sProductClassifyId"
        );
        if (slaveIndex > -1) {
          const sqlDropDownData = await this.props.getSqlDropDownData(
            sModelsId,
            "slave",
            slaveConfig.gdsconfigformslave[slaveIndex]
          );
          dropdownProductClassifyId = sqlDropDownData.dropDownData;
        }
        if (commonUtils.isEmptyArr(dropdownProductClassifyId)) {
          const iIndex = slaveConfig.gdsconfigformslave.findIndex(
            item => item.sName === "sProductClassifyName"
          );
          if (iIndex > -1) {
            const sqlDropDownData = await this.props.getSqlDropDownData(
              sModelsId,
              "slave",
              slaveConfig.gdsconfigformslave[iIndex]
            );
            dropdownProductClassifyId = sqlDropDownData.dropDownData;
          }
        }
        if (commonUtils.isNotEmptyArr(dropdownProductClassifyId)) {
          const iProductClassifyIdIndex = dropdownProductClassifyId.findIndex(
            item => item.sId === slaveData[iSlaveIndex].sProductClassifyId
          );
          if (
            commonUtils.isNotEmptyObject(
              dropdownProductClassifyId[iProductClassifyIdIndex]
            )
          ) {
            const sAllPartsName =
              dropdownProductClassifyId[iProductClassifyIdIndex].sAllPartsName;
            if (commonUtils.isNotEmptyStr(sAllPartsName)) {
              const sAssignFieldObj = sAllPartsName.split(",");
              for (const child of sAssignFieldObj) {
                const tableDataRowAdd = commonFunc.getDefaultData(
                  controlConfig,
                  allTableData
                );
                tableDataRowAdd.handleType = "add";
                tableDataRowAdd.sId = commonUtils.createSid();
                tableDataRowAdd.sParentId =
                  masterData && masterData.sId ? masterData.sId : null;
                tableDataRowAdd.sSlaveId = slaveSelectedRowKeys[0];
                tableDataRowAdd.key = tableDataRowAdd.sId;
                tableDataRowAdd.bDefault = false;
                tableDataRowAdd.iOrder = 0;
                tableDataRowAdd.sPartsName = child;
                tableDataRowAdd.dPartsQty = slaveData[iSlaveIndex].dProductQty;
                controlData.push(tableDataRowAdd);
              }
            }
          }
        }
        addState.controlData = controlData;
      }

      if (controlData !== undefined) {
        const iControlIndex = controlData.findIndex(
          item => item.sSlaveId === slaveSelectedRowKeys[0]
        );
        if (iControlIndex > -1) {
          addState.controlSelectedRowKeys = [controlData[iControlIndex].sId];
        }
      }
    }

    this.props.onSaveState({
      visibleModal: true,
      ...addState
    });
  };
  handleTableChooseProcess = () => {
    const { processConfig } = this.props;
    const iIndex = processConfig.gdsconfigformslave.findIndex(
      item => item.sControlName === "BtnChooseProcess"
    );

    if (iIndex > -1) {
      this.props.onBtnChoose(
        "process",
        "BtnChooseProcess",
        processConfig.gdsconfigformslave[iIndex]
      );
    }
  };
  handleCancelModal = modelVisible => {
    this.props.onSaveState({
      [modelVisible]: false
    });
  };
  handleOkModal = () => {
    const {
      controlData,
      slave0Data,
      processData,
      sModelsId,
      slaveData,
      slaveSelectedRowKeys,
      materialsConfig,
      processConfig
    } = this.props;
    const ctData = controlData.filter(
      item =>
        item.handleType !== "del" && item.sSlaveId === slaveSelectedRowKeys[0]
    );
    const mtData = slave0Data.filter(
      item =>
        item.handleType !== "del" && item.sSlaveId === slaveSelectedRowKeys[0]
    );
    const pData = processData.filter(
      item =>
        item.handleType !== "del" &&
        item.sSlaveId === slaveSelectedRowKeys[0] &&
        item.sType === "2"
    );
    if (commonUtils.isNotEmptyArr(ctData)) {
      let mDetail = "";
      let pDetail = "";
      const slaveIndex = slaveData.findIndex(
        item => item.sId === slaveSelectedRowKeys[0]
      );
      ctData.forEach(async (controlItem, n) => {
        if (commonUtils.isNotEmptyObject(controlItem.sPartsName)) {
          const qz = n === 0 ? "" : " ";
          if (commonUtils.isNotEmptyObject(controlItem.sPartsName)) {
            const yDetail = `${mDetail}${qz}#${controlItem.sPartsName}:`;
            const gDetail = `${pDetail}${qz}#${controlItem.sPartsName}:`;
            let imDetail = "";
            let ipDetail = "";
            const materials = mtData.filter(
              materialsItem => materialsItem.sControlId === controlItem.sId
            );
            let materialsIdDropDown;
            const materialsIndex = materialsConfig.gdsconfigformslave.findIndex(
              item => item.sName === "sMaterialsName"
            );
            if (materialsIndex > -1) {
              const sqlDropDownData = await this.props.getSqlDropDownData(
                sModelsId,
                "materials",
                materialsConfig.gdsconfigformslave[materialsIndex]
              );
              materialsIdDropDown = sqlDropDownData.dropDownData;
            }
            materials.forEach((mItem, i) => {
              const fh = i === 0 ? "" : ",";
              if (materialsIdDropDown) {
                const materialsIdIndex = materialsIdDropDown.findIndex(
                  item => item.sId === mItem.sMaterialsId
                );
                if (materialsIdIndex > -1) {
                  imDetail = `${imDetail}${fh} ${
                    materialsIdDropDown[materialsIdIndex].sMaterialsName
                  }`;
                }
              }
            });
            // processPropsType
            const process = pData.filter(
              processItem => processItem.sControlId === controlItem.sId
            );
            let processIdDropDown;
            const processIndex = processConfig.gdsconfigformslave.findIndex(
              item => item.sName === "sProcessName"
            );
            if (processIndex > -1) {
              const sqlDropDownData = await this.props.getSqlDropDownData(
                sModelsId,
                "process",
                processConfig.gdsconfigformslave[processIndex]
              );
              processIdDropDown = sqlDropDownData.dropDownData;
            }
            process.forEach((pItem, i) => {
              const fh = i === 0 ? "" : ",";
              if (processIdDropDown) {
                const processIdIndex = processIdDropDown.findIndex(
                  item => item.sId === pItem.sProcessId
                );
                if (processIdIndex > -1) {
                  ipDetail = `${ipDetail}${fh} ${
                    processIdDropDown[processIdIndex].sProcessName
                  }`;
                }
              }
            });
            if (commonUtils.isNotEmptyObject(imDetail)) {
              mDetail = `${yDetail}${imDetail}`;
            }
            if (commonUtils.isNotEmptyObject(ipDetail)) {
              pDetail = `${gDetail}${ipDetail}`;
            }
          }
        }
      });
      slaveData[slaveIndex].sMaterialsMemo = mDetail;
      slaveData[slaveIndex].sProcessMemo = pDetail;
      slaveData[slaveIndex].handleType = commonUtils.isEmpty(
        slaveData[slaveIndex].handleType
      )
        ? "update"
        : slaveData[slaveIndex].handleType;
    } else if (
      commonUtils.isNotEmptyArr(controlData) &&
      commonUtils.isEmptyArr(ctData)
    ) {
      const sSlaveId = controlData[0].sSlaveId;
      const slaveIndex = slaveData.findIndex(item => item.sId === sSlaveId);
      slaveData[slaveIndex].sMaterialsMemo = "";
      slaveData[slaveIndex].sProcessMemo = "";
      slaveData[slaveIndex].handleType = commonUtils.isEmpty(
        slaveData[slaveIndex].handleType
      )
        ? "update"
        : slaveData[slaveIndex].handleType;
    }
    this.props.onSaveState({
      visibleModal: false,
      controlData,
      slave0Data,
      processData,
      slaveData
    });
  };
  /** 控制选择控制表时，显示部件工序与成品工序 */
  handleFilterSlaveData = (name, dataIndex, value, record) => {
    return (
      commonUtils.isNotEmptyStr(record.sSlaveId) &&
      record.sSlaveId
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase())
    );
  };
  /** 控制选择控制表时，显示部件工序与成品工序 */
  handleFilterData = () => {
    return true;
  };
  /* 控制表过滤材料表 工序表数据 */
  handleGetFilterData = name => {
    const {
      [`${name}Data`]: data,
      controlSelectedRowKeys,
      slaveSelectedRowKeys
    } = this.props;
    if (data !== undefined) {
      const newArr = data.filter(item => {
        if (name === "control") {
          return (
            commonUtils.isNotEmptyStr(item.sSlaveId) &&
            item.sSlaveId
              .toString()
              .toLowerCase()
              .includes(slaveSelectedRowKeys.toString())
          );
        } else {
          return (
            commonUtils.isNotEmptyStr(item.sControlId) &&
            item.sControlId
              .toString()
              .toLowerCase()
              .includes(controlSelectedRowKeys.toString()) &&
            commonUtils.isNotEmptyStr(item.sSlaveId) &&
            item.sSlaveId
              .toString()
              .toLowerCase()
              .includes(slaveSelectedRowKeys.toString())
          );
        }
      });
      return newArr.length;
    }
  };
  /**   添加表格空行   */
  handleTableAdd = async (name, flag) => {
    if (name === "materials") {
      const { slave0Data: processData, slave0SelectedRowKeys: processSelectedRowKeys,} = this.props;
      const tableData = this.props[`${name}Data`];
      tableDataRow = this.props.onDataRowAdd(name, true);
      tableDataRow.sControlId = this.props.slave0Child1SelectedRowKeys[0];
      let processRow = {};
      if(commonUtils.isNotEmptyArr(processData) && commonUtils.isNotEmptyArr(processSelectedRowKeys)){ /* 没有工序选中行 则不进行数据过滤 */
        const iIndex = processData.findIndex(item => processSelectedRowKeys.includes(item.sId));
        if(iIndex > -1) {
          processRow = processData[iIndex];
          tableDataRow.sProcessId = processRow.sProcessId; /* 工序ID */
          tableDataRow.sProcessTbId = processRow.sId; /* 工序表格ID */
        }
      }
      tableData.push(tableDataRow);
      this.props.onSaveState({
        [`${name}Data`]: tableData,
        [`${name}SelectedRowKeys`]: [tableDataRow.sId]
      });
    } else {
      this.props.onDataRowAdd(name, flag);
    }

    return;


    /*   外置处理业务   */
    const {
      sModelsId,
      sModelsType,
      gdsformconst,
      slaveData,
      controlData,
      controlSelectedRowKeys,
      [`${name}Data`]: tableData,
      slaveSelectedRowKeys,
      slaveConfig
    } = this.props;
    let tableDataRow = {};
    if (name === "control") {
      tableDataRow = this.props.onDataRowAdd(name, true);
      if (commonUtils.isEmptyObject(tableDataRow)) {
        return;
      }
      let dPartsQty = 0;
      if (commonUtils.isNotEmptyArr(slaveData)) {
        slaveData.forEach(item => {
          dPartsQty +=
            commonUtils.isNull(item.dProductQty, 0) +
            commonUtils.isNull(item.dGiveQty, 0) +
            commonUtils.isNull(item.dStockupQty, 0);
        });
        // const productIdDropDown = commonUtils.getStoreDropDownData(sModelsId, 'slave', 'sProductName');
        let productIdDropDown;
        const slaveIndex = slaveConfig.gdsconfigformslave.findIndex(
          item => item.sName === "sProductName"
        );
        if (slaveIndex > -1) {
          const sqlDropDownData = await this.props.getSqlDropDownData(
            sModelsId,
            "slave",
            slaveConfig.gdsconfigformslave[slaveIndex]
          );
          productIdDropDown = sqlDropDownData.dropDownData;
        }
        if (productIdDropDown) {
          const iProductIdIndex = productIdDropDown.findIndex(
            item => item.sId === slaveData[0].sProductId
          );
          if (iProductIdIndex > -1) {
            tableDataRow.sPartsName =
              productIdDropDown[iProductIdIndex].sProductName;
          }
        }
      }
      const iSlaveIndex = slaveData.findIndex(
        item => item.sId === slaveSelectedRowKeys[0]
      );
      if (iSlaveIndex > -1) {
        if (sModelsType === "sales/salesOrder") {
          if (!commonUtils.isEmpty(slaveData[iSlaveIndex].dProductQty)) {
            tableDataRow.dPartsQty =
              commonUtils.isNull(slaveData[iSlaveIndex].dProductQty, 0) +
              commonUtils.isNull(slaveData[iSlaveIndex].dGiveQty, 0);
          }
        } else {
          tableDataRow.dPartsQty = dPartsQty;
        }
        tableDataRow.sSlaveId = slaveData[iSlaveIndex].sId;
      }
      tableData.push(tableDataRow);
      this.props.onSaveState({
        [`${name}Data`]: tableData,
        [`${name}SelectedRowKeys`]: [tableDataRow.sId]
      });
    } else if (name === "materials" || name === "process") {
      tableDataRow = this.props.onDataRowAdd(name, true);
      if (commonUtils.isEmptyArr(controlSelectedRowKeys)) {
        const msg = commonFunc.showMessage(gdsformconst, "pleaseChooseParts");
        message.warn(msg === "" ? "请选择部件" : msg); // 请选择部件
        return;
      }
      const iIndex = controlData.findIndex(
        item => item.sId === controlSelectedRowKeys[0]
      );
      const iSlaveIndex = slaveData.findIndex(
        item => item.sId === slaveSelectedRowKeys[0]
      );
      if (iIndex > -1 && iSlaveIndex > -1) {
        if (commonUtils.isEmpty(controlData[iIndex].sPartsName) === "") {
          message.warn(
            commonFunc.showMessage(gdsformconst, "partsNameNotNull")
          ); // 部件名称不能为空
          return;
        }
        tableDataRow.sSlaveId = slaveData[iSlaveIndex].sId;
        tableDataRow.sControlId = controlData[iIndex].sId;
        tableDataRow.sPartsName = controlData[iIndex].sPartsName;
      }
      tableData.push(tableDataRow);
      this.props.onSaveState({
        [`${name}Data`]: tableData,
        [`${name}SelectedRowKeys`]: [tableDataRow.sId]
      });
    } else {
      this.props.onDataRowAdd(name, flag);
    }
  };
  /**   删除表格数据   */
  otherTableDel = (name, tableSelectedRowKeys) => {
    const tableData = this.props[`${name}Data`];
    let tableDelData = this.props[`${name}DelData`];
    tableDelData = commonUtils.isEmptyArr(tableDelData) ? [] : tableDelData;
    for (const sId of tableSelectedRowKeys) {
      /*   看看删除集合和从表中是否都存在该条数据   */
      let tableDataIndex = tableData.findIndex(item => item.sControlId === sId);
      while (tableDataIndex > -1) {
        /*   删除从表中的数据并存入删除集合中   */
        const slaveDataFilter = tableData[tableDataIndex];
        tableData.splice(tableDataIndex, 1);
        slaveDataFilter.handleType = "del";
        tableDelData.push(slaveDataFilter);
        tableDataIndex = tableData.findIndex(item => item.sControlId === sId);
      }
    }
    return {
      [`${name}Data`]: tableData,
      [`${name}DelData`]: tableDelData,
      [`${name}SelectedRowKeys`]: []
    };
  };
  /**   删除表格数据   */
  handleTableDel = (name, isWait, tableSelectedRowKeys) => {
    if (name === "control") {
      const tableSelectedRowKeys = this.props[`${name}SelectedRowKeys`];
      if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) {
        const materialsReturnData = this.otherTableDel(
          "materials",
          tableSelectedRowKeys
        );
        const processReturnData = this.otherTableDel(
          "process",
          tableSelectedRowKeys
        );
        const controlReturnData = this.props.onDataRowDel(
          name,
          isWait,
          tableSelectedRowKeys
        );
        this.props.onSaveState({
          ...materialsReturnData,
          ...processReturnData,
          ...controlReturnData
        });
        return true;
      } else {
        return false;
      }
    } else {
      return this.props.onDataRowDel(name, isWait, tableSelectedRowKeys);
    }
  };
  /**   销售订单删除从表数据时也删除控制材料工序表数据   */
  handleSlaveTableDel = (name, isWait, tableSelectedRowKeys) => {
    const { sModelsType, controlData, processData, materialsData } = this.props;
    if (sModelsType === "sales/salesOrder" && name === "slave") {
      const controlDataDel = controlData.filter(
        item => item.sSlaveId === tableSelectedRowKeys[0]
      );
      const controlDataSelectedRowKeys = [];
      if (!commonUtils.isEmpty(controlDataDel)) {
        for (const item of controlDataDel) {
          const materialsDataSelectedRowKey = item.sId;
          controlDataSelectedRowKeys.push(materialsDataSelectedRowKey);
        }
        if (commonUtils.isNotEmptyArr(controlDataSelectedRowKeys)) {
          this.props.onDataRowDel(
            "control",
            isWait,
            controlDataSelectedRowKeys,
            true
          );
        }
        const materialsDataDel = materialsData.filter(
          item => item.sSlaveId === tableSelectedRowKeys[0]
        );
        const materialsDataSelectedRowKeys = [];
        if (!commonUtils.isEmpty(materialsDataDel)) {
          for (const item of materialsDataDel) {
            const materialsDataSelectedRowKey = item.sId;
            materialsDataSelectedRowKeys.push(materialsDataSelectedRowKey);
          }
        }
        if (commonUtils.isNotEmptyArr(materialsDataSelectedRowKeys)) {
          this.props.onDataRowDel(
            "materials",
            isWait,
            materialsDataSelectedRowKeys,
            true
          );
        }
        const processDataDel = processData.filter(
          item => item.sSlaveId === tableSelectedRowKeys[0]
        );
        const processDataSelectedRowKeys = [];
        if (!commonUtils.isEmpty(processDataDel)) {
          for (const item of processDataDel) {
            const processDataSelectedRowKey = item.sId;
            processDataSelectedRowKeys.push(processDataSelectedRowKey);
          }
        }
        if (commonUtils.isNotEmptyArr(processDataSelectedRowKeys)) {
          this.props.onDataRowDel(
            "process",
            isWait,
            processDataSelectedRowKeys,
            true
          );
        }
      }
    }
    return this.props.onDataRowDel(name, isWait, tableSelectedRowKeys);
  };
  handleSelect = async (name, selectConfig, selectData) => {
    const {
      [`${name}Data`]: tableData,
      [`${name}Config`]: tableConfig,
      masterData,
      masterConfig,
      controlSelectedRowKeys,
      sModelsId,
      token,
      app
    } = this.props;
    const tableSelectedRowKeys = [];
    if (name === "productProcessInfo") {
      if (commonUtils.isNotEmptyArr(selectData)) {
        let slaveData = [];
        let controlData = [];
        let materialsData = [];
        let processData = [];
        let sConfigMasterIdSlave = "";
        let sConfigMasterIdControl = "";
        let sConfigMasterIdMaterials = "";
        let sConfigMasterIdProcess = "";
        const selectRowData = selectData[0];
        const sConfigIdString = masterConfig.gdsconfigformslave.filter(
          item => item.sName === "sConfigId"
        )[0].showDropDown;
        if (commonUtils.isNotEmptyStr(sConfigIdString)) {
          const sConfigId = JSON.parse(sConfigIdString);
          sConfigMasterIdSlave = sConfigId.sConfigMasterIdSlave;
          sConfigMasterIdControl = sConfigId.sConfigMasterIdControl;
          sConfigMasterIdMaterials = sConfigId.sConfigMasterIdMaterials;
          sConfigMasterIdProcess = sConfigId.sConfigMasterIdProcess;
        }
        if (commonUtils.isEmptyStr(sConfigMasterIdSlave)) {
          message.warning(
            commonFunc.showMessage(app.commonConst, "slaveParameterErro")
          );
        }
        if (commonUtils.isEmptyStr(sConfigMasterIdControl)) {
          message.warning(
            commonFunc.showMessage(app.commonConst, "controlParameterErro")
          );
        }
        if (commonUtils.isEmptyStr(sConfigMasterIdMaterials)) {
          message.warning(
            commonFunc.showMessage(app.commonConst, "materialsParameterErro")
          );
        }
        if (commonUtils.isEmptyStr(sConfigMasterIdProcess)) {
          message.warning(
            commonFunc.showMessage(app.commonConst, "processParameterErro")
          );
        }
        const slaveUrl = `${
          commonConfig.server_host
        }business/getBusinessDataByFormcustomId/${sConfigMasterIdSlave}?sModelsId=${sModelsId}`;
        const value = { sSqlCondition: { sParentId: selectRowData.sId } };
        const slaveReturnData = (await commonServices.postValueService(
          token,
          value,
          slaveUrl
        )).data;
        if (slaveReturnData.code === 1) {
          slaveData = slaveReturnData.dataset.rows[0].dataSet;
          slaveData.forEach(item => {
            item.handleType = "add";
            item.sId = commonUtils.createSid();
            item.sParentId = masterData.sId;
          });
        } else {
          this.props.getServiceError(slaveReturnData);
        }

        const controlUrl = `${
          commonConfig.server_host
        }business/getBusinessDataByFormcustomId/${sConfigMasterIdControl}?sModelsId=${sModelsId}`;
        const controlReturnData = (await commonServices.postValueService(
          token,
          value,
          controlUrl
        )).data;
        if (controlReturnData.code === 1) {
          controlData = controlReturnData.dataset.rows[0].dataSet;
          controlData.forEach(item => {
            item.handleType = "add";
            item.sId = commonUtils.createSid();
            item.sParentId = masterData.sId;
          });
        } else {
          this.props.getServiceError(controlReturnData);
        }
        const materialsUrl = `${
          commonConfig.server_host
        }business/getBusinessDataByFormcustomId/${sConfigMasterIdMaterials}?sModelsId=${sModelsId}`;
        const materialsReturnData = (await commonServices.postValueService(
          token,
          value,
          materialsUrl
        )).data;
        if (materialsReturnData.code === 1) {
          materialsData = materialsReturnData.dataset.rows[0].dataSet;
          materialsData.forEach(item => {
            item.handleType = "add";
            item.sId = commonUtils.createSid();
            item.sParentId = masterData.sId;
          });
        } else {
          this.props.getServiceError(materialsReturnData);
        }
        const processUrl = `${
          commonConfig.server_host
        }business/getBusinessDataByFormcustomId/${sConfigMasterIdProcess}?sModelsId=${sModelsId}`;
        const processReturnData = (await commonServices.postValueService(
          token,
          value,
          processUrl
        )).data;
        if (processReturnData.code === 1) {
          processData = processReturnData.dataset.rows[0].dataSet;
          processData.forEach(item => {
            item.handleType = "add";
            item.sId = commonUtils.createSid();
            item.sParentId = masterData.sId;
          });
        } else {
          this.props.getServiceError(processReturnData);
        }
        this.props.onSaveState({
          processData,
          materialsData,
          controlData,
          slaveData,
          [`${name}ChooseVisible`]: false,
          [`${name}SelectedRowKeys`]: tableSelectedRowKeys
        });
      }
    } else {
      const { controlData, slaveData, slaveSelectedRowKeys } = this.props;
      const iIndex = commonUtils.isNotEmptyArr(controlSelectedRowKeys)
        ? controlData.findIndex(item => item.sId === controlSelectedRowKeys[0])
        : -1;
      if (commonUtils.isNotEmptyArr(selectData)) {
        selectData.forEach(item => {
          const newCopyTo = {};
          newCopyTo.master = masterData;
          if (iIndex > -1) {
            newCopyTo.control = controlData[iIndex];
          }
          let tableDataRow = commonFunc.getDefaultData(tableConfig, newCopyTo); // 取默认值
          tableDataRow = {
            ...tableDataRow,
            ...commonFunc.getAssignFieldValue(
              selectConfig.sAssignField,
              item,
              newCopyTo
            )
          }; // 取赋值字段
          tableDataRow.handleType = "add";
          tableDataRow.sId = commonUtils.createSid();
          tableDataRow.sParentId = masterData.sId;
          if (this.props.sModelsType === "sales/salesOrder") {
            const iSlaveIndex = commonUtils.isNotEmptyArr(slaveSelectedRowKeys)
              ? slaveData.findIndex(
                  item => item.sId === slaveSelectedRowKeys[0]
                )
              : -1;
            if (iSlaveIndex > -1) {
              tableDataRow.sSlaveId = slaveData[iSlaveIndex].sId;
            }
          }
          if (iIndex > -1 && tableDataRow.sType !== "3") {
            tableDataRow.sControlId = controlData[iIndex].sId;
            tableDataRow.sPartsName = controlData[iIndex].sPartsName;
            tableData.push(tableDataRow);
          } else if (tableDataRow.sType === "3") {
            tableData.push(tableDataRow);
          }
          tableSelectedRowKeys.push(tableDataRow.sId);
        });
      }
      const tableDataNew = this.sortData(controlData, tableData);
      this.props.onSaveState({
        [`${name}Data`]: tableDataNew,
        [`${name}ChooseVisible`]: false,
        [`${name}SelectedRowKeys`]: tableSelectedRowKeys
      });
    }
  };

  sortData = (tableData, processData) => {
    processData.sort((g1, g2) => {
      const iIndex1 =
        tableData.findIndex(item => item.sId === g1.sControlId) === -1
          ? 999
          : tableData.findIndex(item => item.sId === g1.sControlId);
      let sPartOrder1 = `0000${iIndex1}`;
      sPartOrder1 = sPartOrder1.substring(sPartOrder1.length - 3);
      let sOrder1 = `000${g1.iOrder}`;
      sOrder1 = sOrder1.substring(sOrder1.length - 3);

      const iIndex2 =
        tableData.findIndex(item => item.sId === g2.sControlId) === -1
          ? 999
          : tableData.findIndex(item => item.sId === g2.sControlId);
      let sPartOrder2 = `0000${iIndex2}`;
      sPartOrder2 = sPartOrder2.substring(sPartOrder2.length - 3);
      let sOrder2 = `000${g2.iOrder}`;
      sOrder2 = sOrder2.substring(sOrder2.length - 3);
      return (
        parseInt(sPartOrder1 + g1.sType + sOrder1, 10) -
        parseInt(sPartOrder2 + g2.sType + sOrder2, 10)
      );
    });
    return processData;
  };
  /**   上传后执行函数    */
  handleBeforeUpload = () => {};

  handleTabChange = key => {
    setTimeout(() => {
      this.setState({
        currentTab: key
      });
    }, 0);
  };


  handleActiveKey = (value) => {
    this.setState({
      colTabKey: value,
      activeKey: value
    });
  }


  handleMenuClick = e => {
    let { sId } = this.props.masterData;
    const Type = e.key;
    const { token } = this.props.app;
    const { sType } = this.props.app.userinfo;
    if (Type === "formSlave") {
      /* 根据从表勾选数据 生成从表数据 */
      const { slaveSelectedRowKeys } = this.props;
      if (commonUtils.isEmptyObject(slaveSelectedRowKeys)) {
        message.warn("请选择数据");
        return;
      }
      sId = slaveSelectedRowKeys;
    }
    const downloadUrl = `${
      commonConfig.server_host
    }sqlfile/scriptSqlDownload?methodName=${Type}&sId=${sId}&token=${token}&sType=${sType}`;
    window.open(downloadUrl);
    this.props.onSaveState({
      downloadUrl
    });
  };
  handleSlaveInit = async name => {
    const { app, masterData, [`${name}Data`]: slaveData } = this.props;
    if (masterData.sName !== null && masterData.sName !== undefined) {
      message.warn("该节点不能初始化！");
      return;
    }
    const comfiled = {
      path: "gdsconfigform",
      pathTwo: "Gdsconfigformmaster",
      pathSlave: "Gdsconfigformslave",
      pathCustom: "Customslave",
      pathInit: "GdsconfigformslaveByMaster",
      pathSlaveSelect: "gdsmodule",
      pathSlaveSelectTwo: "SelectFormData"
    };
    const url = `${commonConfig.server_host}${comfiled.path}/get${
      comfiled.pathInit
    }?sParentId=${masterData.sId}&sTbName=${masterData.sTbName}&sType=${
      masterData.sType
    }`;
    const dataReturn = (await commonServices.getService(
      this.props.app.token,
      url
    )).data;
    if (dataReturn.code === 1) {
      /*   数据查询成功   */
      if (commonUtils.isNotEmptyArr(dataReturn.dataset.rows)) {
        const tempData = dataReturn.dataset.rows;
        const initData = [];
        tempData.forEach(item => {
          item.handleType = "add";
          initData.push(item);
        });
        const newData = [...slaveData, ...initData];
        this.props.onSaveState({ slaveData: newData, enabled: true });
        message.success("初始化成功！");
      } else {
        message.warn("当前表格无需初始化！");
      }
    } else {
      /*   失败   */
      this.props.getServiceError(dataReturn);
    }
  };
  handleCopyRow = (name, toname) => {
    this.props.onCopyRow(name, toname);
  };
  handleCopy2Custom = () => {
    let toname = "slave2";
    for (let i = 0; i < 10; i++) {
      const slaveConfigName = `slave${i}Config`;
      const slaveConfig = this.props[slaveConfigName];
      if (slaveConfig && commonUtils.isNotEmptyObject(slaveConfig)) {
        if (slaveConfig.sTbName === "gdsconfigformcustomslave") {
          toname = `slave${i}`;
          break;
        }
      }
    }
    this.props.onCopyRow("slave", toname);
  };
  /**   添加行   */
  handleAddRow = (name, index) => {
    this.props.onDataRowAdd(name, null, index);
  };
  /**   删除行   */
  handleDelRow = name => {
    const { [`${name}SelectedRowKeys`]: tableSelectedRowKeys } = this.props;
    if (this.props.onDataRowDel(name, false, tableSelectedRowKeys)) {
      message.success("删除成功！");
    }
  };

  /* 字段双击弹出 */
  handleFieldDoubleClick = (sValue, showConfig, tbName) => {
    const {
      [`${tbName}SelectedRowKeys`]: tableSelectedRowKeys,
      [`${tbName}Data`]: tableData
    } = this.props;
    if (
      commonUtils.isNotEmptyObject(showConfig) &&
      showConfig.sName === "sAssignField"
    ) {
      let tableDataRow = {};
      if (commonUtils.isNotEmptyArr(tableData)) {
        const tableFilterData = tableData.filter(item =>
          tableSelectedRowKeys.includes(item.sId)
        );
        if (commonUtils.isNotEmptyArr(tableFilterData)) {
          tableDataRow = tableFilterData[0];
        }
      }
      const sAssignFieldColumn = [
        {
          sId: commonUtils.createSid(),
          sParentId: tableDataRow.sId,
          dataIndex: "sNewName",
          title: "现字段",
          width: "220px",
          editable: true,
          bNotSort: true
        },
        {
          sId: commonUtils.createSid(),
          sParentId: tableDataRow.sId,
          dataIndex: "sOldName",
          title: "源字段",
          width: "220px",
          editable: true,
          bNotSort: true
        }
      ];
      const sAssignFieldData = [];
      if (
        commonUtils.isNotEmptyObject(tableDataRow) &&
        commonUtils.isNotEmptyObject(sValue)
      ) {
        const selectedRowKeys = [];
        const sAssignFieldDataTemp = sValue.split(",");
        sAssignFieldDataTemp.forEach(index => {
          const aAssignFieldObj = {};
          const splitData = index.split(":");
          if (commonUtils.isNotEmptyArr(splitData)) {
            aAssignFieldObj.sId = commonUtils.createSid();
            aAssignFieldObj.sNewName = splitData[0];
            aAssignFieldObj.sOldName = splitData[1];
            sAssignFieldData.push(aAssignFieldObj);
          }
          selectedRowKeys[0] = sAssignFieldData[0].sId;
        });
        const { enabled } = this.props;
        this.props.onSaveState({
          sAssignFieldColumn,
          visibleAssignmentField: true,
          sAssignFieldData,
          sAssignFieldName: tbName,
          sAssignFieldRowId: tableDataRow.sId /* 选中行的sId */,
          enabled
        });
      } else {
        this.props.onSaveState({
          sAssignFieldColumn,
          visibleAssignmentField: true,
          sAssignFieldData: [],
          sAssignFieldName: tbName,
          sAssignFieldRowId: tableDataRow.sId /* 选中行的sId */
        });
      }
    }
  };
  /* 拿到赋值字段 */
  handleGetsAssignField = (data, sFieldName) => {
    if (sFieldName === "sAssignField") {
      const {
        sAssignFieldRowId,
        sAssignFieldName
      } = this.props; /* 双击弹出赋值窗体的行ID */
      const { [`${sAssignFieldName}Data`]: tableData } = this.props;
      if (commonUtils.isNotEmptyArr(tableData)) {
        const iIndex = tableData.findIndex(
          item => item.sId === sAssignFieldRowId
        );
        const newData = {};
        /* 将数组变成赋值字符串 */
        let sAssignFieldStr = "";
        const len = data.length;
        data.forEach((item, index) => {
          sAssignFieldStr += `${item.sNewName}:${item.sOldName}`;
          if (index !== len - 1) {
            sAssignFieldStr += ",";
          }
        });
        newData.sAssignField = sAssignFieldStr;
        newData.handleType = commonUtils.isEmpty(tableData[iIndex].handleType)
          ? "update"
          : tableData[iIndex].handleType;
        tableData[iIndex] = { ...tableData[iIndex], ...newData };
        this.props.onSaveState({ [`${sAssignFieldName}Data`]: tableData });
      }
    }
  };

  handleUploadPropsSales = () => {
    const { masterData, sModelsType } = this.props;
    if (commonUtils.isNotEmptyObject(masterData)) {
      const sCustomerId = commonUtils.isEmptyStr(masterData.sCustomerId)
        ? undefined
        : masterData.sCustomerId;
      let existCustomerId = false;
      if (
        sModelsType.includes("sales/") &&
        commonUtils.isNotEmptyStr(sCustomerId)
      ) {
        existCustomerId = true;
      } else if (!sModelsType.includes("sales/")) {
        existCustomerId = true;
      }
      return {
        disabled: !this.props.enabled || !existCustomerId /*   是否可用   */,
        style: {
          display: commonUtils.convertBooleanToDisplayBlock(true)
        } /*   是否显示   */
      };
    }
  };

  handleUploadChangeFile = async info => {
    const { file } = info;
    const {
      masterData,
      sModelsId,
      app,
      token,
      sModelsType,
      slaveConfig,
      slaveData
    } = this.props;
    if (file.response) {
      if (file.response.code === 1) {
        /*   数据查询成功   */
        const errorInfo = file.response.dataset.rows[0].nocanbeInsert;
        if (commonUtils.isNotEmptyObject(errorInfo)) {
          // message.error(errorInfo[0].sReason);
          const importErrorData = errorInfo;
          this.props.onSaveState({
            showImportErrorVisible: true,
            importData: importErrorData
          });
          return;
        }
        /* 把之前存放的数据删除 */
        const slaveDelData = [];
        if (commonUtils.isNotEmptyArr(slaveData)) {
          slaveData.forEach(item => {
            if (commonUtils.isEmptyObject(item.handleType)) {
              item.handleType = "del";
              slaveDelData.push(item);
            }
          });
        }
        const returnData = file.response.dataset.rows[0].canbeInsert;
        let iCount = 0;
        let productIdDropDown;
        if (
          productIdDropDown === undefined &&
          commonUtils.isNotEmptyArr(returnData)
        ) {
          /* 无论导入多少条数据 都只调用1次接口,获取产品下拉数据集 */
          const iIndex = slaveConfig.gdsconfigformslave.findIndex(
            item => item.sName === "sProductName"
          );
          if (iIndex > -1) {
            const sqlDropDownData = await this.props.getSqlDropDownData(
              sModelsId,
              "slave",
              slaveConfig.gdsconfigformslave[iIndex],
              returnData[0]
            );
            productIdDropDown = sqlDropDownData.dropDownData;
          }
        }
        await returnData.forEach(async tableDataRow => {
          tableDataRow.handleType = "add";
          tableDataRow.sId = commonUtils.createSid();
          tableDataRow.sParentId = masterData.sId;
          tableDataRow.key = tableDataRow.sId;
          /* 若导入模板没有序号，则序号从1自增 */
          if (commonUtils.isEmptyObject(tableDataRow.iOrder)) {
            iCount += 1;
            tableDataRow.iOrder = iCount;
          }
          for (const child of Object.keys(tableDataRow)) {
            const index = child.indexOf("_sRealValue_");
            if (index > -1) {
              const property = child.substring(0, child.length - 12);
              tableDataRow[property] = tableDataRow[child];
            }
          }
          if (productIdDropDown !== undefined) {
            const iProductIdIndex = productIdDropDown.findIndex(
              item =>
                (item.sId === tableDataRow.sProductId ||
                  item.sNId === tableDataRow.sProductId) &&
                item.sProductStyle === tableDataRow.sProductStyle
            );
            if (
              iProductIdIndex === -1 &&
              commonUtils.isNotEmptyObject(sModelsType) &&
              sModelsType.includes("sales/salesOrder")
            ) {
              /* 只有销售模块生成新产品 盘点 ，期间 不生成新的产品 */
              tableDataRow.sProductId = tableDataRow.sProductName;
              tableDataRow.sProductInfo = JSON.stringify({
                sProductId: tableDataRow.sProductName,
                sProductName: tableDataRow.sProductName,
                sProductStyle: tableDataRow.sProductStyle,
                sProductUnit: tableDataRow.sProductUnit,
                sProductNo: tableDataRow.sProductNo,
                sCustomerProductNo: tableDataRow.sCustomerProductNo,
                sProductClassifyId: tableDataRow.sProductClassifyId,
                sProductClassifyName: tableDataRow.sProductClassifyName
              });
            }
          }
          if (!tableDataRow.dNProductPrice) {
            tableDataRow.dNProductPrice = tableDataRow.dProductForeignPrice;
          }
          const models =
            sModelsType.includes("sales/") ||
            sModelsType.includes("manufacture/") ||
            sModelsType.includes("quotation/") ||
            sModelsType.includes("productStock/")
              ? "Product"
              : "Materials";
          if (
            sModelsType.includes("purchase/") ||
            sModelsType.includes("quotation/") ||
            sModelsType.includes("manufacture/") ||
            sModelsType.includes("materialsStock/") ||
            sModelsType.includes("outside/")
          ) {
            tableDataRow = await this.props.onMaterialsChange(
              tableDataRow,
              sModelsId,
              masterData,
              {},
              "dAuxiliaryQty",
              app,
              token,
              models
            );
            tableDataRow = commonBusiness.getCalculateAllMoney(
              app,
              models,
              "dAuxiliaryQty",
              masterData,
              tableDataRow
            );
          } else {
            tableDataRow = commonBusiness.getCalculateAllMoney(
              app,
              models,
              "dProductQty",
              masterData,
              tableDataRow
            );
          }
        });
        this.props.onSaveState({ slaveData: returnData, slaveDelData });
      } else {
        /*   失败s   */
        this.props.getServiceError(file.response);
      }
    }
  };

  handleSelectRowChange = async (name, selectedKeys) => {
    const { slave0Child1Data, [`${name}Data`]: tableData } = this.props;

    let addState = this.props.onTableSelectRowChange(name, selectedKeys, true);
    const { [`${name}Config`]: config = {} } = this.props;
    if (config.showName === "工艺评审") {
      //...
    }
    if (name === 'slave') {
      if (selectedKeys.length > 0) {
        const iSlaveIndex = tableData.findIndex(item => item.sId === selectedKeys[0]);
        const iControlIndex = slave0Child1Data?.findIndex(
          controlItem => {
            const sCombinedMemoArr = JSON.parse(controlItem.sCombinedMemo);
            const sCombinedMemoFilterArr = sCombinedMemoArr.filter(item => item.dCombineQty > 0 && item.sProductNo === tableData[iSlaveIndex].sProductNo);
            return controlItem.sProductCardId === tableData[0].sBomId &&
              commonUtils.isNotEmptyArr(sCombinedMemoFilterArr)
          });
        if (iControlIndex > -1) {
          addState.slave0Child1SelectedRowKeys = [slave0Child1Data[iControlIndex].sId];
          _this.controlFilterData = [slave0Child1Data[iControlIndex]];
        }
        addState.slave0SelectedRowKeys = [];
      }

    }
    if(name ==='slave0Child1' && config.showName === "合格率评审") {
      addState.slave0SelectedRowKeys = []; /* 部件表选中时 清空工序的选中 */
    } else if(name ==='slave0') {
      addState.materials1SelectedRowKeys = []; /* 工序选中时，油墨选中清空 */
    }
    this.props.onSaveState(addState);
  };

  handleReturnForm = form => {
    this.form = form;
    this.props.onReturnForm(form);
  };

  handleValidateSave = () => {
    this.form.validateFields(async err => {
      /*   验证通过与不通过走不同的流程    */
      if (err) {
        /*   验证失败   */
        /*   直接渲染显示错误提示   */
        for (const key of Object.keys(err)) {
          message.error(err[key].errors[0].message);
        }
        this.props.onSaveState({
          loading: false
        });
      } else {
        const { app } = this.props;
        /*   验证成功   */
        // 遍历出所有表格名称
        const configNameList = Object.keys(this.props)
          .filter(
            item =>
              (item && item.startsWith("slave") && item.endsWith("Config")) ||
              item.includes("revision") ||
              item.includes("materials")
          )
          .map(item => item.replace("Config", ""));
        configNameList.unshift("master");

        // 验证表格数据
        let validateFlag = true;

        for (let i = 0; i < configNameList.length; i++) {
          const tbName = configNameList[i];
          const {
            [`${tbName}Config`]: tableConfig,
            [`${tbName}Data`]: tableData
          } = this.props;
          const validateFun =
            tbName === "master"
              ? commonBusiness.validateMaster
              : commonBusiness.validateTable;

          validateFlag =
            commonUtils.isNotEmptyArr(tableData) &&
            commonUtils.isNotEmptyObject(tableConfig)
              ? validateFun(tableConfig, tableData, this.props)
              : true;
          if (!validateFlag) {
            break;
          }
          if (tableConfig && tableConfig.bNotCanEmpty) {
            validateFlag = false;
            if (commonUtils.isEmptyArr(tableData)) {
              message.error(
                commonFunc.showMessage(app.commonConst, "slaveNotNull")
              ); // 表格不能为空！
            }
          }
          if (!validateFlag) {
            break;
          }
        }

        if (!validateFlag) {
          this.props.onSaveState({
            loading: false
          });
          return;
        }

        this.props.onSaveState({
          loading: false
        });

        const data = [];
        configNameList.forEach(tbName => {
          const {
            [`${tbName}Config`]: tableConfig,
            [`${tbName}Data`]: tableData,
            [`${tbName}DelData`]: tableDelData
          } = this.props;
          if (tableConfig && tableConfig.sTbName && tableConfig.sSqlStr !== "noQuery") {
            const tableDataNew = tbName === "master" ? [tableData] : tableData;
            data.push(
              commonBusiness.mergeData(
                tbName,
                tableConfig.sTbName,
                tableDataNew,
                tableDelData
              )
            );
          }
        });

        /* 塞入材料数据 */
        // 获取材料表格（工序物料）
        const iMIndex = configNameList.findIndex(item => item === 'materials');   /* 判断是否包含materials */
        let materialsTableName;
        const slaveNameArr2 = Object.keys(this.props).filter(
          key =>
            key &&
            key.includes("Config") &&
            commonUtils.isNotEmptyObject(this.props[key]) &&
            this.props[key].sTbName === "salsalesordermaterials" &&
            (this.props[key].showName === "工序物料" || this.props[key].showName === "全部材料")
        );

        if (slaveNameArr2.length && iMIndex === -1) {
          materialsTableName = slaveNameArr2[0].split("Config")[0];
          const {
            [`${materialsTableName}Config`]: tableMaterialsConfig,
            [`${materialsTableName}Data`]: tableMaterialsData,
            [`${materialsTableName}DelData`]: tableMaterialsDelData
          } = this.props;
          if (tableMaterialsConfig && tableMaterialsConfig.sTbName  && tableMaterialsConfig.sSqlStr !== "noQuery") {
            const tableMaterialsDataNew =
              materialsTableName === "master"
                ? [tableMaterialsData]
                : tableMaterialsData;
            data.push(
              commonBusiness.mergeData(
                materialsTableName,
                tableMaterialsConfig.sTbName,
                tableMaterialsDataNew,
                tableMaterialsDelData
              )
            );
          }
        }

        this.props.onSaveData({
          data,
          sClientType: "1",
          sSysLogSrcId: this.props.masterData.sId
        });
      }
    });
  };

  handleToolBarClick = e => {
    const { item = {} } = e;
    const { props = {} } = item;
    const { name } = props;
    if (name === "选择工艺卡") {
      this.handleChooseProcessCard();
      return true;
    }
    return false;
  };

  handleChooseProcessCard = () => {
    const { addStateMap } = this.props;
    const configName = Object.keys(addStateMap).find(
      key => addStateMap[key].sTbName === "salsalesordercontrol"
    );
    const processConfigName = Object.keys(addStateMap).find(
      key => addStateMap[key].sTbName === "salsalesorderprocess"
    );
    if (configName && processConfigName) {
      const tableName = configName.replace("Config", "");
      const tableData = this.props[tableName + "Data"];

      const processTableName = processConfigName.replace("Config", "");
      const processTableData = this.props[processTableName + "Data"];

      const productCardRadios = tableData.reduce((result, item) => {
        const { sProductCardId, sProductCardNo, sId } = item;
        const iIndex = result.findIndex(item => item.value === sProductCardId);

        if (iIndex === -1) {
          if (!this.currentProductCardValue) {
            this.currentProductCardValue = `${sProductCardId}-${sId}`;
          }
          const line1 = <div>{`工艺卡-${sProductCardNo}`}</div>;
          let line2 = "";

          const processTableFilterData = processTableData.filter(
            item => item.sControlId === sId
          );

          if (processTableFilterData.length) {
            line2 = (
              <div>
                {<span>工艺流程：</span>}
                {processTableFilterData.map((item, index) => {
                  if (index !== processTableFilterData.length - 1) {
                    return (
                      <span>
                        {item.sProcessName}
                        <RightOutlined />
                      </span>
                    );
                  } else {
                    return <span>{item.sProcessName}</span>;
                  }
                })}
              </div>
            );
          }

          result.push(
            <Radio value={`${sProductCardId}-${sId}`}>
              {line1}
              {line2}
            </Radio>
          );
        }
        return result;
      }, []);
      const _this = this;
      Modal.confirm({
        title: "选择工艺卡",
        // icon: <ExclamationCircleOutlined />,
        content: (
          <Radio.Group
            onChange={({ target: { value } }) => {
              this.currentProductCardValue = value;
            }}
            defaultValue={this.currentProductCardValue}
          >
            <Space direction="vertical">{productCardRadios}</Space>
          </Radio.Group>
        ),
        okText: "确认",
        cancelText: "取消",
        onOk() {
          const [sProductCardId, sId] = _this.currentProductCardValue.split(
            "-"
          );
          const sValue = {
            sProductCardId
          };
          _this.handleToForceComplete(sValue, sId);
        }
      });
    }
  };

  handleToForceComplete = async (sValue, sId) => {
    const { app, sModelsId, formRoute, masterConfig } = this.props;

    const { token } = app;
    let iIndex = -1;
    if (masterConfig && Array.isArray(masterConfig.gdsconfigformslave)) {
      iIndex = masterConfig.gdsconfigformslave.findIndex(
        item =>
          item.sControlName === "BtnForceComplete" ||
          item.sControlName === "BtnNoPurchase"
      );
    }
    if (iIndex < 0) return;
    const btnConfig = masterConfig.gdsconfigformslave[iIndex];
    const sRelation = btnConfig.sRelation;
    const url = `${
      commonConfig.server_host
    }bill/billForceComplete?sModelsId=${sModelsId}&sName=${formRoute}`;
    const values = { sqlParam: sRelation, sId, sReason: sValue };

    const masterReturn = (await commonServices.postValueService(
      token,
      values,
      url
    )).data;
    if (masterReturn.code === 1) {
      message.success(masterReturn.msg);
      this.props.onButtonClick("BtnRefresh");
    } else {
      this.props.getServiceError(masterReturn);
    }
  };

  handleCancelProductCombinationChooseModal = () => {
    this.props.onSaveState({ productCombinationVisible: false });
  };

  handleSelectProductCombination = () => {
    const {
      slave0Child1Data: controlData, sCombinationsControlId, packData, enabled, app,
    } = this.props;
    let { packSelectedRowKeys: selectedRowKeys } = this.props;
    let sCombinedMemo = '';
    const tableCombineSelectedData = [];
    // selectedRowKeys = commonUtils.isNotEmptyArr(selectedRowKeys) ? selectedRowKeys : [];
    const maxArr = [];
    const maxMap = new Map();
    let dSumCombineQty = 0;
    for (const tableDataRow of packData) {
      const {
        sId, sProductNo, dCombineQty, dProductQty, dFactProductQty, sCombinePartsName,
      } = tableDataRow;
      if (dCombineQty > 0) { /* 排版数大于0时,把数据带回到控制表 */
        const jsonObj = {};
        jsonObj.sId = sId;
        jsonObj.sProductNo = sProductNo; /* 产品编号 */
        jsonObj.dCombineQty = commonUtils.isNotEmptyNumber(dCombineQty) ? dCombineQty : 0; /* 排版数 */
        jsonObj.dProductQty = commonUtils.isNotEmptyNumber(dProductQty) ? dProductQty : 0; /* 生产数 */
        jsonObj.dFactProductQty = commonUtils.isNotEmptyNumber(dFactProductQty) ? dFactProductQty : 0; /* 实际生产数 */
        jsonObj.sCombinePartsName = sCombinePartsName; /* 合版部件名称 */
        dSumCombineQty += dCombineQty;
        tableCombineSelectedData.push(jsonObj);
        maxMap.set(Math.floor(dProductQty / dCombineQty), jsonObj);
        maxArr.push(Math.floor(dProductQty / dCombineQty));
      }
    }
    /* 没勾选的合版数据 合拼排版数置为0 */
    // const packNoChooseData = packData.filter(item => item.sControlId === sCombinationsControlId && !selectedRowKeys.includes(item.sId));
    // if (commonUtils.isNotEmptyArr(packNoChooseData) && packNoChooseData.length > 0) {
    //   packNoChooseData.forEach((item) => {
    //     const iIndex = packData.findIndex(child => child.sId === item.sId);
    //     if (iIndex > -1) {
    //       packData[iIndex].dCombineQty = 0;
    //       packData[iIndex].handleType = commonUtils.isEmpty(packData[iIndex].handleType) ? 'update' : packData[iIndex].handleType;
    //     }
    //   });
    // }

    let iMax = 0;
    if (commonUtils.isNotEmptyArr(maxArr)) {
      iMax = Math.max(...maxArr);
    }
    sCombinedMemo = commonUtils.isNotEmptyArr(tableCombineSelectedData) ? JSON.stringify(tableCombineSelectedData) : ''; /* JSON对象转换为字符串存放到合版信息中 */
    const iControlIndex = controlData.findIndex(item => item.sId === sCombinationsControlId);
    if (iControlIndex > -1 && enabled) {
      const addState = {};
      const maxObj = maxMap.get(iMax);
      let { handleType } = controlData[iControlIndex];
      handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType;
      addState.handleType = handleType;
      addState.sCombinedMemo = sCombinedMemo;
      addState.dPartsQty = maxObj.dProductQty;
      addState.dSinglePQty = commonUtils.isNotEmptyObject(maxObj) ? maxObj.dCombineQty : 0;
      addState.iCombineNum = dSumCombineQty;
      controlData[iControlIndex] = { ...controlData[iControlIndex], ...addState };
      console.log('maxObj', maxObj);
    }

    console.log('controlData确定', controlData);
    this.props.onSaveState({
      productCombinationVisible: false,
      packData,
      slave0Child1Data:controlData,
    });
  };

  handleGetHeight = (minusNum = 0, bHalf) => {
    let commonViewHeight = this.commonViewHeight;
    if (bHalf) {
      return `calc((100vh - ${commonViewHeight}px) / 2 - ${minusNum}px)`;
    } else {
      return `calc(100vh - ${commonViewHeight + minusNum}px)`;
    }
  };

  handleGetTableTypesNew = name => {
    const { dataRelationJson = {} } = this.props;
    let result = {};
    const relateName = dataRelationJson[name];
    if (relateName) {
      result = {
        name: relateName,
        data: this.props[`${relateName}Data`],
        selectedRowKeys: this.props[`${relateName}SelectedRowKeys`]
      };
    }
    return result;
  };

  handleTableFilterData = (name, data, record) => {
    if (name === "slave") {
      const { bSecondMainMaterials }  = this.props;
      let slaveInfoDataNew = [];
      if (commonUtils.isNotEmptyArr(data)) {
        const bMaterials =
          Object.keys(record).includes("sMaterialsId") &&
          Object.keys(record).includes("sMaterialsStyle");
        if (bMaterials) {
          if(bSecondMainMaterials) { /* 二级工单材料过滤 */
            slaveInfoDataNew = data.filter(
              item =>
                `${item.sMaterialsId}${item.sMaterialsStyle}` ===
                `${record.sMaterialsId}${record.sMaterialsStyle}` &&
                 item.sMaterialStructure === '2'
                && (commonUtils.isEmpty(record.sControlId) || `${item.sOrderControlId}` === `${record.sControlId}`)
            );
          }else {  /* 一级工单材料过滤 */
            slaveInfoDataNew = data.filter(
              item =>
                `${item.sMaterialsId}${item.sMaterialsStyle}` ===
                `${record.sMaterialsId}${record.sMaterialsStyle}` &&
                item.sMaterialStructure === '1'
                && (commonUtils.isEmpty(record.sControlId) || `${item.sOrderControlId}` === `${record.sControlId}`)
            );
          }
        } else {
          slaveInfoDataNew = data.filter(
            item => item.sSqlConditionId === record.sSqlConditionId
          );
        }
      }
      return slaveInfoDataNew;
    }
  };

  /*
  过滤替代料 根据子从表数据源过滤替代料数据
   */
  handleFilterMaterialData = (name, dataIndex, value, record) => {
    // const { slave3Child0InfoSelectedRowKeys } = this.props;
    const { slave3Child0SelectedRowKeys } = this.props;
    if (value === undefined) {
      return true;
    }
    if (name === "slave3Child0Child0") {
      return (
        commonUtils.isNotEmptyObject(record.sParentMaterialsId) &&
        commonUtils.isNotEmptyArr(slave3Child0SelectedRowKeys) &&
        slave3Child0SelectedRowKeys.includes(record.sSrcMaterialsTbId)
      );
    }
  };

  handleViewChoose = (name, sName, record) => {
    if (sName === "sParams") {
      const slaveSelectOneData = record;
      const sProcessParamsSelects = [];
      let sParamData = [];
      let paramType = "";
      if (commonUtils.isNotEmptyObject(slaveSelectOneData)) {
        paramType = slaveSelectOneData.sWorkOrderParam;
      }
      if (commonUtils.isEmpty(paramType)) {
        message.warn("无工艺参数！");
        return;
      }
      /* 工序参数以表格形式展示 列 */
      const sParamConfig = {
        bisMutiSelect: false,
        bMutiSelect: false
      };
      const gdsconfigformslave = [
        {
          sId: commonUtils.createSid(),
          sName: "sId",
          showName: "主键",
          bVisible: false,
          iFitWidth: 200
        },
        {
          sId: commonUtils.createSid(),
          sName: "bSelfCbx",
          showName: "选择",
          bVisible: true,
          iFitWidth: 37
        },
        {
          sId: commonUtils.createSid(),
          sName: "sParamKey",
          showName: "参数主键",
          bVisible: false,
          iFitWidth: 200
        },
        {
          sId: commonUtils.createSid(),
          sName: "sParamName",
          showName: "参数名",
          bVisible: true,
          iFitWidth: 230
        },
        {
          sId: commonUtils.createSid(),
          sName: "sParamValue",
          showName: "参数值",
          bVisible: true
        }
      ];
      sParamConfig.gdsconfigformslave = gdsconfigformslave;
      const sParamColumn = commonFunc.getHeaderConfig(sParamConfig);
      if (commonUtils.isNotEmptyObject(paramType)) {
        /* 要把数据以表格的形式显示出来 */
        let sParamJsonObj = commonUtils.convertStrToObj(paramType, []);

        for (const key of Object.keys(sParamJsonObj)) {
          if (
            key.includes("sParam") &&
            !key.includes("DropDown") &&
            !key.includes("Default")
          ) {
            const obj = {};
            obj.sId = commonUtils.createSid();
            obj.sParamKey = key;
            obj.sParamName = sParamJsonObj[key];
            /* 找到数字 找到下拉数据源 */
            const num = key.replace(/[^\d]/g, "").trim();
            if (Number(num)) {
              const number = Number(num);
              const sParamDropDownKey = `sParamDropDown${number}`;
              obj.sDropDownData = sParamJsonObj[sParamDropDownKey]; /* 下拉 */
              const sParamDefaultKey = `sParamDefault${number}`;
              obj.sParamValue = sParamJsonObj[sParamDefaultKey]; /* 默认值 */
            }
            sParamData.push(obj);
          }
        }
        /* 将sParam1中的数据 还原到sParamData数据中 */
        if (commonUtils.isNotEmptyObject(record.sParams)) {
          let selectedData = [];
          try {
            selectedData = JSON.parse(record.sParams);
          } catch (e) {
            try {
              selectedData = JSON.parse(record.sParams.replace(/'/g, '"'));
            } catch (error) {
              selectedData = [];
            }
          }

          if (commonUtils.isNotEmptyArr(selectedData)) {
            selectedData.forEach(itemS => {
              const iIndex = sParamData.findIndex(
                item => item.sParamName === itemS.sParamName
              );
              if (iIndex > -1) {
                const addState = {};
                addState.sParamValue = itemS.sParamValue;
                addState.bSelfCbx = itemS.bSelfCbx;
                sParamData[iIndex] = { ...sParamData[iIndex], ...addState };
              }
            });
          }

          /* 如果数据集有一个是非选中的则非选中状态 否则全选 */
          if (commonUtils.isNotEmptyArr(sParamColumn)) {
            const iIndex = sParamColumn.findIndex(
              item => item.dataIndex === "bSelfCbx"
            );
            if (iIndex > -1) {
              const filterData = sParamData.filter(item => !item.bSelfCbx);
              if (commonUtils.isNotEmptyArr(filterData)) {
                sParamColumn[iIndex] = {
                  ...sParamColumn[iIndex],
                  bCheckAll: false
                };
              } else {
                sParamColumn[iIndex] = {
                  ...sParamColumn[iIndex],
                  bCheckAll: true
                };
              }
            }
          }
        }
      }
      this.props.onSaveState({
        processTableName: name,
        processRecord: record,
        sProcessParamsSelects,
        sParamsModalVisible: true,
        sParamConfig,
        sParamColumn,
        sParamData,
        sParamModalType: "sWork"
      });
    } else if (sName === "sColorSerialMemo") {
      this.isSColorSerialMemo.current = true;
      const { slave0Data: tableData, enabled } = this.props;
      const { sId } = record; /* 控制表主键 */
      const sisColorSelectedRowKeys = [];
      let jsonData = [];
      const iIndex = tableData.findIndex(item => item.sId === sId);
      if (iIndex > -1) {
        const sColorSerialMemo = tableData[iIndex].sColorSerialMemo;

        if (commonUtils.isNotEmptyObject(sColorSerialMemo)) {
          try {
            jsonData = JSON.parse(sColorSerialMemo);
          } catch (e) {
            try {
              jsonData = JSON.parse(sColorSerialMemo.replace(/'/g, '"'));
            } catch (ex) {
              // console.log('ex', ex);
            }
          }
          jsonData.forEach(item => {
            sisColorSelectedRowKeys.push(item.sId);
          });
        }
      }
      this.props.onSaveState({
        processTableName: name,
        sisColorChooseVisible: true,
        processSelectedRowId: sId /* 工序表选中行sId */,
        enabled,
        sisColorSelectedRowKeys,
        sisColorSelectedData: jsonData
      });
    } else if (name === 'slave0Child1' && sName === 'sCombinedMemo') { /* 打开合版信息蓝色链接逻辑体 */
      const { formData, slaveData, slave0Child1Data: controlData} = this.props;
      const addState = {};
      const packConfig = formData.find(item => item.sTbName === "salsalesordercontrolcombine" && item.showName === '销售合版表' ); /* 销售合版表 */
      const name= 'pack';
      if(commonUtils.isNotEmptyObject(packConfig)) { /* 特殊处理更新材料信息 */
        addState[`${name}Config`] = packConfig;
        addState[`${name}Column`] = commonFunc.getHeaderConfig(packConfig);
        addState[`${name}PageSize`] =
          commonUtils.isNotEmptyNumber(packConfig.iPageSize) && packConfig.iPageSize !== 0
            ? packConfig.iPageSize
            : packConfig.pageSize;
      }
      /* 拿从表的选中行 */
      const slaveRow = handleGetSelectedData(this.props,'slave');
      const sSlaveCombinedMemo = slaveRow?.sCombinedMemo;
      const sControlCombinedMemo = record.sCombinedMemo;
      let jsonArr = [];
      let sControlCombinedMemoArr = [];
      if(sControlCombinedMemo && commonUtils.isJSON(sControlCombinedMemo)) {
        sControlCombinedMemoArr = JSON.parse(sControlCombinedMemo);
      }

      if(sSlaveCombinedMemo && commonUtils.isJSON(sSlaveCombinedMemo)) {
        const sSlaveCombinedMemoArr = JSON.parse(sSlaveCombinedMemo);
        if(commonUtils.isNotEmptyArr(sSlaveCombinedMemoArr)) {
          sSlaveCombinedMemoArr.forEach((item) => {
            item.dProductQty = item.dModifyProductQty;
            delete item.dRealQty;
            delete item.dReCombinedQty;
            delete item.dReMergeProductionQty;
            item.sControlId = record.sId;
            item.sPartsName = record.sPartsName;
            const iCombinedIndex = sControlCombinedMemoArr.findIndex(combinedItem => combinedItem.sProductNo === item.sProductNo);
            item.dCombineQty = iCombinedIndex > -1 ? sControlCombinedMemoArr[iCombinedIndex].dCombineQty : 0;
            jsonArr.push(item);
          })
        }
      }

      if(commonUtils.isNotEmptyArr(slaveData)) {
        slaveData.forEach((item) => {
          const tableRow = JSON.parse(JSON.stringify(item));
          const iIndex = jsonArr.findIndex(row => row.sProductId === tableRow.sProductId);
          tableRow.sControlId = record.sId;
          tableRow.sPartsName = record.sPartsName;
          const iCombinedIndex = sControlCombinedMemoArr.findIndex(combinedItem => combinedItem.sProductNo === item.sProductNo);
          tableRow.dCombineQty = iCombinedIndex > -1 ? sControlCombinedMemoArr[iCombinedIndex].dCombineQty :  0;
          delete tableRow.sCombinedMemo;
          if(iIndex > -1) {
            tableRow.dProductQty = commonUtils.convertFixNum(commonUtils.isNull(jsonArr[iIndex].dProductQty, 0), 2) +
              commonUtils.convertFixNum(commonUtils.isNull(tableRow.dProductQty, 0), 2);
            jsonArr[iIndex] = tableRow;
          } else {
            jsonArr.push(tableRow);
          }
        })
      }

      if (commonUtils.isNotEmptyArr(controlData)) {
        // 取合版数最大产出数
        const maxArr = [];
        const maxMap = new Map();
        let sumArea = 0;
        for (const tableDataRow of jsonArr) {
          const { dCombineQty, dProductQty: dProductQtyOld } = tableDataRow;
          const dProductQty = (dProductQtyOld - commonUtils.isNull(tableDataRow.dRealQty, 0) - commonUtils.isNull(tableDataRow.dReCombinedQty, 0) - commonUtils.isNull(tableDataRow.dReMergeProductionQty, 0));
          if (dCombineQty > 0) { /* 排版数大于0时,把数据带回到控制表 */
            maxMap.set(Math.floor(dProductQty / dCombineQty), tableDataRow);
            maxArr.push(Math.floor(dProductQty / dCombineQty));
            tableDataRow.dArea = tableDataRow.dProductLength * tableDataRow.dProductWidth > 0 ? Math.round(tableDataRow.dProductLength * tableDataRow.dProductWidth * dCombineQty, 2) : 0;
            sumArea += tableDataRow.dArea;
          }
        }
        let iMax = 0;
        if (commonUtils.isNotEmptyArr(maxArr)) {
          iMax = Math.max(...maxArr);
        }
        const maxObj = maxMap.get(iMax);
        for (const tableDataRow of jsonArr) {
          if (tableDataRow.dCombineQty > 0) { /* 排版数大于0时,把数据带回到控制表 */
            tableDataRow.dFactProductQty = Math.floor((maxObj.dProductQty - commonUtils.isNull(maxObj.dRealQty, 0) - commonUtils.isNull(maxObj.dReCombinedQty, 0) - commonUtils.isNull(maxObj.dReMergeProductionQty, 0)) /  maxObj.dCombineQty * tableDataRow.dCombineQty);
            tableDataRow.dCombineCoefficient = sumArea > 0 ? Math.round(tableDataRow.dArea / sumArea * 100, 2) : 0;
          }
        }

        for (const tableDataRow of sControlCombinedMemoArr) {
          if (tableDataRow.dCombineQty > 0 && jsonArr.findIndex(item => item.sProductNo === tableDataRow.sProductNo) <= -1) { // 排版数大于0时,不存在的合版信息也加入
            delete tableDataRow.dProductQty;
            jsonArr.push(tableDataRow);
          }
        }

        const sCombinedMemo = commonUtils.isNotEmptyArr(jsonArr) && jsonArr.filter(item => item.dCombineQty > 0).length > 0 ? JSON.stringify(jsonArr.filter(item => item.dCombineQty > 0)) : ''; /* JSON对象转换为字符串 */
        const iControlIndex = controlData.findIndex(item => item.sId === record.sId);
        if (iControlIndex > -1) {
          controlData[iControlIndex].sCombinedMemo = sCombinedMemo;
          controlData[iControlIndex].handleType =  commonUtils.isEmpty(record.handleType) ? 'update' : record.handleType;
        }
        addState.slave0Child1Data = controlData;
        addState.packData = jsonArr;
        addState.sCombinationsControlId = record.sId;
      }
      console.log('addState打开', addState);
      this.props.onSaveState({
        productCombinationVisible: true,
        ...addState,
      });
    }
  };

  handleCostomChange = async (name, showConfig, other) => {
    const {
      app,
      sModelsId,
      [`${name}Data`]: tableData,
      [`${name}SelectedRowKeys`]: tableSelectedRowKeys,
      masterData,
      slave1Child0Config,
      slave2Child0Config,
      slave2Child0InfoConfig,
      slave6Child1Config,
      slave6Child1InfoConfig,
    } = this.props;
    const confirmSetting = commonFunc.showLocalMessage(this.props, 'confirmSetting', '请配置按钮的存储过程');
    const confirmSettingParam = commonFunc.showLocalMessage(this.props, 'confirmSettingParam', '请先操作参数运算');
    const iIndex =
      commonUtils.isNotEmptyObject(tableSelectedRowKeys) &&
      commonUtils.isNotEmptyArr(tableData)
        ? tableData.findIndex(item => tableSelectedRowKeys.includes(item.sId))
        : -1;
    let slaveRow = {};
    if (iIndex > -1) {
      slaveRow = tableData[iIndex];
    } else if (commonUtils.isNotEmptyArr(tableData) && tableData.length > 0) {
      slaveRow = tableData[0];
    }
    if (
      commonUtils.isNotEmptyObject(showConfig) &&
      showConfig.sControlName &&
      showConfig.sControlName.includes("BtnCustom.dSplitworkQty")
    ) {
      if (masterData.bFirstCalc !== 1) {
        message.error(confirmSettingParam);
        return;
      }
      this.props.onSaveState({ pageLoading: true });
      /* 拆分工单单据 - 拆分工单 生成工单 */
      const sButtonParam = showConfig.sButtonParam;
      if (
        commonUtils.isNotEmptyObject(sButtonParam) &&
        commonUtils.isJSON(sButtonParam)
      ) {
        const proObj = JSON.parse(sButtonParam);
        const proName = proObj.sproName;
        const sRowData = slaveRow;
        const value = {
          sProName: proName,
          sProInParam: JSON.stringify({ params: sRowData })
        };
        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.props.onSaveState({ pageLoading: false });
          const conditonValues = this.props.onGetSqlConditionValues(slave1Child0Config);
          const addState1 = await this.props.handleGetDataSet({
            name: 'slave1Child0', configData: slave1Child0Config, condition: { sSqlCondition: { ...conditonValues, sParentId: masterData.sId } }, isWait: true,
          });
          this.props.onSaveState({
            ...addState1
          });
          // this.props.onButtonClick("BtnRefresh");
        } else {
          this.props.onSaveState({ pageLoading: false });
          this.props.getServiceError({
            ...returnData,
            fn: () => this.handleCostomChange(name, showConfig, { iFlag: 1 })
          });
        }
      } else {
        message.error(confirmSetting);
      }
    } else if (
      commonUtils.isNotEmptyObject(showConfig) &&
      showConfig.sControlName &&
      (showConfig.sControlName.includes("BtnCustom.tEstimateCompletDate") ||
        showConfig.sControlName.includes("BtnCustom.tRecalculatedDate"))
    ) {
      /* 单生管评审单据 - 生管评审 - 交期推算 */
      const {
        app,
        sModelsId,
        [`${name}Data`]: tableData,
        slaveSelectedRowKeys: tableSelectedRowKeys
      } = this.props;
      const index =
        commonUtils.isNotEmptyObject(tableSelectedRowKeys) &&
        commonUtils.isNotEmptyArr(tableData)
          ? tableData.findIndex(item => tableSelectedRowKeys.includes(item.sId))
          : -1;
      slaveRow = index > -1 ? tableData[index] : slaveRow;
      const controlRow = handleGetSelectedData(this.props, 'slave0Child1'); /* 控制表当前选中行 */
      const sButtonParam = showConfig.sButtonParam;
      if (
        commonUtils.isNotEmptyObject(sButtonParam) &&
        commonUtils.isJSON(sButtonParam)
      ) {
        const proObj = JSON.parse(sButtonParam);
        const proName = proObj.sproName;
        let sRowData = slaveRow;
        //取第一条BOM的id
        sRowData = { ...sRowData, sBomId: tableData[0].sBomId };
        const value = {
          sProName: proName,
          sProInParam: JSON.stringify({ params: sRowData, control: controlRow })
        };
        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);
          if (showConfig.sControlName.includes("BtnCustom.tEstimateCompletDate")) {
            const conditonValues1 = this.props.onGetSqlConditionValues(slave2Child0Config);
            const addState1 = await this.props.handleGetDataSet({
              name: 'slave2Child0', configData: slave2Child0Config, condition: { sSqlCondition: { ...conditonValues1, sParentId: masterData.sId } }, isWait: true,
            });
            const conditonValues2 = this.props.onGetSqlConditionValues(slave2Child0InfoConfig);
            const addState2 = await this.props.handleGetDataSet({
              name: 'slave2Child0Info', configData: slave2Child0InfoConfig, condition: { sSqlCondition: { ...conditonValues2, sParentId: masterData.sId } }, isWait: true,
            });
            tableData[index].handleType = commonUtils.isEmpty(tableData[index].handleType) ? "update" : tableData[index].handleType;
            tableData[index].tEstimateCompletDate = returnData.dataset?.rows[0].dataSet?.proData[0].tEstimateCompletDate;
            this.props.onSaveState({
              ...addState1, ...addState2,
            });
          } else if (showConfig.sControlName.includes("BtnCustom.tRecalculatedDate")) {
            const conditonValues1 = this.props.onGetSqlConditionValues(slave6Child1Config);
            const addState1 = await this.props.handleGetDataSet({
              name: 'slave6Child1', configData: slave6Child1Config, condition: { sSqlCondition: { ...conditonValues1, sParentId: masterData.sId } }, isWait: true,
            });
            const conditonValues2 = this.props.onGetSqlConditionValues(slave6Child1InfoConfig);
            const addState2 = await this.props.handleGetDataSet({
              name: 'slave6Child1Info', configData: slave6Child1InfoConfig, condition: { sSqlCondition: { ...conditonValues2, sParentId: masterData.sId } }, isWait: true,
            });
            tableData[index].handleType = commonUtils.isEmpty(tableData[index].handleType) ? "update" : tableData[index].handleType;
            tableData[index].tRecalculatedDate = returnData.dataset?.rows[0].dataSet?.proData[0].tRecalculatedDate;
            this.props.onSaveState({
              ...addState1, ...addState2, [`${name}Data`]: tableData
            });
          }

          // this.props.onButtonClick("BtnRefresh");
        } else {
          this.props.getServiceError({
            ...returnData,
            fn: () => this.handleCostomChange(name, showConfig, { iFlag: 1 })
          });
        }
      } else {
        message.error(confirmSetting);
      }
    }
  };

  handleGetParamsValue = ({ sName, sValue, record = {} }) => {
    const jsonData = commonUtils.convertStrToObj(sValue, []);
    if (sName === "sParams") {
      const { sWorkOrderParam: sWorkOrderParamStr } = record;
      const sWorkOrderParam = commonUtils.convertStrToObj(
        sWorkOrderParamStr,
        {}
      );
      const sWorkOrderData =
        jsonData.find(item => item.sParamType === "sWorkOrder") || {};
      const { data = {} } = sWorkOrderData;
      const result = [];
      Object.keys(data).forEach(key => {
        if (sWorkOrderParam[key] !== undefined) {
          result.push(`${sWorkOrderParam[key]}: ${data[key]}`);
        }
      });
      return result.join(";");
    }

    return sValue;
  };

  // 刷新工单交期
  handleRefreshGdjq = async() => {
    const { currentId, slave2Child0Config, slave2Child0InfoConfig } =  this.props;
    const sId = currentId || this.props.masterData?.sId || '';
    const conditonValues1 = this.props.onGetSqlConditionValues(slave2Child0Config);
    let returnData1 = await this.props.handleGetDataSet({
      name: "slave2Child0",
      configData: slave2Child0Config,
      condition: { sSqlCondition: { ...conditonValues1, sParentId: sId } },
      isWait: true,
    });

    const conditonValues2 = this.props.onGetSqlConditionValues(slave2Child0Config);
    let returnData2 = await this.props.handleGetDataSet({
      name: "slave2Child0Info",
      configData: slave2Child0InfoConfig,
      condition: { sSqlCondition: { ...conditonValues2, sParentId: sId } },
      isWait: true,
    });

    this.props.onSaveState({
      ...returnData1,
      ...returnData2
    });
  }

  handleSelectCommonPopup = (currentPaneName, selectConfig, selectData, tbName) => {
    if (selectConfig?.sControlName?.includes('popupSingle')
      && selectConfig?.sControlName?.includes('edit')
    ) {
      this.handleRefreshGdjq();
      return;
    }

    this.props.onSelectCommonPopup (currentPaneName, selectConfig, selectData, tbName);
    const { slave1Config } = this.props;
    if(selectConfig.sControlName && selectConfig.sControlName === 'BtnPopup.dSplitworkQty') { /* 拆分工单 */
      const iIndex = slave1Config.gdsconfigformslave.findIndex(item => item.sControlName === 'BtnCustom.dSplitworkQty');
      if (iIndex > -1) {
        this.handleCostomChange(tbName, slave1Config.gdsconfigformslave[iIndex], { iFlag: 1 });
      }

    }
  }

  // 删除全部材料
  handleDelAllMaterials = (filterData, bPartDel) => {
    const { materialsSelectedRowKeys = [] } = this.props;
    const partFilterData = filterData.filter(item => materialsSelectedRowKeys.includes(item.sId));
    if (bPartDel) {
      if (!partFilterData.length) {
        message.info("请先选择要删除的数据！");
        return;
      }
    }

    const delAll = () => {
      const sIds = filterData.map(item => item.sId);
      this.props.onDataRowDel("materials", false, sIds);
    }

    const delPart = () => {
      const sIds = partFilterData.map(item => item.sId);
      this.props.onDataRowDel("materials", false, sIds);
    }

    Modal.confirm({
      title: `确认要删除${bPartDel ? "选中" : "全部"}吗？`,
      onOk() {
        bPartDel ? delPart() : delAll();
      },
      okText: '确定',
      cancelText: '取消'
    });

  }

  // ----------------------------数据修改回带wend  ---------------------------- //

  render() {
    const {
      pageLoading,
      visible,
      checkConditions,
      checkPersonData,
      app
    } = this.props;
    const checkCondition = commonFunc.showMessage(
      app.commonConst,
      "checkCondition"
    ); /* 审核条件 */
    const checkSmemo = commonFunc.showMessage(
      app.commonConst,
      "checkSmemo"
    ); /* 备注 */
    const columns = [
      {
        title: checkCondition,
        dataIndex: "condition",
        key: "condition"
      },
      {
        title: checkSmemo,
        dataIndex: "sMemo",
        key: "sMemo"
      }
    ];
    const btnSure = commonFunc.showMessage(
      app.commonConst,
      "btnSure"
    ); /* 确认 */
    const check = commonFunc.showMessage(app.commonConst, "check"); /* 审核 */
    const BtnClose = commonFunc.showMessage(
      app.commonConst,
      "BtnClose"
    ); /* 关闭 */
    const checkPerson = commonFunc.showMessage(
      app.commonConst,
      "checkPerson"
    ); /* 审核人 */
    return (
      <div>
        <Spin spinning={pageLoading}>
          <div>
            <BillComponent
              {...this.props}
              {...this.state}
              isSColorSerialMemo={this.isSColorSerialMemo}
              resetSColorSerialMemo= {this.resetSColorSerialMemo}
              onSaveCurrentTab={currentTab => {
                this.setState({ currentTab });
              }}
              onUploadChangeFile={this.handleUploadChangeFile} /* xls文件导入 */
              onTabChange={this.handleTabChange}
              onActiveKey={this.handleActiveKey}
              onUploadChange={this.handleUploadChange}
              getMenuStatus={this.getMenuStatus}
              onBeforeUpload={this.handleBeforeUpload}
              onUploadPropsSales={this.handleUploadPropsSales}
              onDataRowModal={this.handleTableModal}
              onDataRowDel={this.handleSlaveTableDel}
              handleMenuClick={this.handleMenuClick}
              handleSlaveInit={this.handleSlaveInit}
              handleCopy2Custom={this.handleCopy2Custom}
              handleCopyRow={this.handleCopyRow}
              handleAddRow={this.handleAddRow}
              handleDelRow={this.handleDelRow}
              getSlaveInfos={this.getSlaveInfos}
              onGetsAssignField={this.handleGetsAssignField}
              handleFieldDoubleClick={this.handleFieldDoubleClick}
              onSelectRowChange={this.handleSelectRowChange}
              onRowClick ={this.onRowClick}
              onReturnForm={this.handleReturnForm}
              onSubmit={this.handleValidateSave}
              onToolBarClick={this.handleToolBarClick}
              onGetHeight={this.handleGetHeight}
              onGetTableTypesNew={this.handleGetTableTypesNew}
              onTableFilterData={this.handleTableFilterData}
              onFilterData={this.handleFilterMaterialData}
              onCostomChange={this.handleCostomChange}
              onViewChoose={this.handleViewChoose}
              onGetParamsValue={this.handleGetParamsValue}
              onDataRowAdd={this.handleTableAdd}
              onCancelProductCombinationChooseModal={this.handleCancelProductCombinationChooseModal}
              onSelectProductCombination={this.handleSelectProductCombination}
              onSelectCommonPopup={this.handleSelectCommonPopup}
              onDelAllMaterials={this.handleDelAllMaterials}
            />
            {visible ? (
              <AntdDraggableModal
                title={check}
                visible={visible}
                onCancel={this.handleCancel}
                footer={[
                  <Button key="back" onClick={this.handleCancel}>
                    {BtnClose}
                  </Button>,
                  <Button
                    key="submit"
                    type="primary"
                    onClick={this.handleOk.bind(this, 1, 1, true)}
                  >
                    {btnSure}
                  </Button>
                ]}
              >
                <Table
                  columns={columns}
                  dataSource={checkConditions}
                  bordered
                  pagination={false}
                  className={styles.checkTable}
                />
                <div style={{ float: "left", width: "15%" }}>{checkPerson}</div>
                <div style={{ float: "left", width: "60%" }}>
                  <Checkbox.Group
                    style={{ width: "100%" }}
                    onChange={this.onChange}
                  >
                    <Row>
                      {commonUtils.isNotEmptyObject(checkPersonData)
                        ? checkPersonData.map(item => {
                            return (
                              <Col span={8}>
                                <Checkbox value={item.sUserId}>
                                  {item.sUserName}
                                </Checkbox>
                              </Col>
                            );
                          })
                        : ""}
                    </Row>
                  </Checkbox.Group>
                </div>
              </AntdDraggableModal>
            ) : (
              ""
            )}
          </div>
        </Spin>
      </div>
    );
  }
}

const BillComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData, masterConfig } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form, masterConfig);
    return obj;
  }
})(props => {
  const { form, onReturnForm, masterData } = props;
  /*   回带表单   */
  onReturnForm(form);
  /*   获取AssignmentField中的props   */
  const assignmentFieldProps = {
    visibleAssignmentField: props.visibleAssignmentField /*   是否展示   */,
    sAssignFieldData: props.sAssignFieldData /*   数据   */,
    sAssignFieldColumn: props.sAssignFieldColumn /* 表头   */,
    selectedRowKeys: props.selectedRowKeys /* 选中   */,
    sAssignFieldSelectedRowKeys: props.selectedRowKeys /* 选中   */,
    onSaveState: props.onSaveState /*   保存数据方法   */,
    onDataRowAdd: props.handleAddRow.bind(this, "sAssignField"),
    onDataRowDel: props.handleDelRow.bind(this, "sAssignField"),
    onDataRowCopy: props.handleCopyRow.bind(this, "sAssignField"),
    // onRowClick: props.handleRowClick.bind(this, 'sAssignField'),
    config: props.config,
    app: props.app,
    enabled: props.enabled,
    onDataChange: props.onChange,
    onGetsAssignField: props.onGetsAssignField,
    handleFieldDoubleClick: props.handleFieldDoubleClick
  };

  if (!masterData) {
    return "";
  }

  return (
    <Form>
      <Layout>
        <HeaderComponent {...props} />
        <Layout className={styles.clayout}>
          <Content className={styles.content} style={{ position: "relative" }}>
            {/* <LeftTabComponent {...props} /> */}
            <CommonViewComponent {...props} />
            <AvatarComponent {...props} />
            <ProcessCardComponent {...props} />
            <div
              id="slaveTabs"
              className={`xly-bill-list commonNewBillContainer commonNewTabBilll`}
              style={{
                marginTop: 0
              }}
            >
              <TabsLv1Component {...props} />
            </div>
          </Content>
          <ModalComponent1 {...props} />
          <ModalComponent2 {...props} />
          {/* <ModalComponent3 {...props} /> */}
          <ModalComponent4 {...props} />
          <ModalComponent5 {...props} />
          <ModalComponentPack {...props} />
          <div>
            <AssignmentField {...assignmentFieldProps} />
          </div>
          <ModalComponentMenu {...props} />
        </Layout>
      </Layout>
    </Form>
  );
});

// 头部工具栏按钮
const HeaderComponent = props => {
  const {
    app,
    formData,
    sModelsId,
    sModelsType,
    masterConfig,
    masterData
  } = props;

  const templateProps = formData.filter(
    item => item.sGrd === "importTemplate"
  )[0];
  let gdsconfigformmasterId = "";
  if (templateProps !== undefined) {
    gdsconfigformmasterId = templateProps.sId;
  }
  const sNotEmpty = "sParentId,sProductId";
  let uploadUrl = `${
    commonConfig.server_host
  }import/checkExcel?sModelsId=${sModelsId}&gdsconfigformmasterId=${gdsconfigformmasterId}&sNotEmpty=${sNotEmpty}&token=${
    app.token
  }`;
  /* 送货单需要传客户id  */
  if (
    commonUtils.isNotEmptyObject(sModelsType) &&
    sModelsType === "sales/salesSgoods" &&
    commonUtils.isNotEmptyObject(masterData)
  ) {
    const sCustomerId = masterData.sCustomerId;
    if (commonUtils.isNotEmptyObject(sCustomerId)) {
      uploadUrl = `${
        commonConfig.server_host
      }import/checkExcel?sModelsId=${sModelsId}&gdsconfigformmasterId=${gdsconfigformmasterId}&sNotEmpty=${sNotEmpty}&sCustomerId=${sCustomerId}&token=${
        app.token
      }`;
    }
  }
  const outProps = {
    action: uploadUrl,
    onChange: props.onUploadChangeFile /* 文件上传 */,
    accept: "xls/*",
    showUploadList: false,
    beforeUpload: () => {
      /* 查看时不可上传 */
      if (!props.enabled) return false;
    }
  };

  const uploadPropsSales = props.onUploadPropsSales();
  const BtnimportData = commonFunc.showMessage(
    app.commonConst,
    "importData"
  ); /* 导入数据 */
  const ImportData = commonUtils.isNotEmptyObject(masterConfig)
    ? masterConfig.gdsconfigformslave.filter(
        item => item.sControlName.includes("ImportData") && item.bVisible
      )
    : ""; /* 后台是否配置导入 */
  return (
    <Header className={styles.header}>
      <div className="billToolBar">
        <Toolbar
          {...props}
          className="billBtnGroup btnGroupHasImport"
          style={{ backgroundColor: "#646464", color: "rgb(255,255,255)" }}
          pageFrom="billList"
        />
      </div>
      {commonUtils.isNotEmptyArr(ImportData) ? (
        <div id="btnImportData" className={`importData ${props.enabled}`}>
          <Upload {...outProps}>
            <UploadOutlined />
            {BtnimportData}
            <Button {...uploadPropsSales} />
          </Upload>
        </div>
      ) : (
        ""
      )}
    </Header>
  );
};

// 主表表单左侧切换按钮
const LeftTabComponent = props => {
  const {
    bShowSlaveTop,
    masterConfig,
    slaveTopConfig,
    currentTopValue = "master"
  } = props;
  if (!bShowSlaveTop) {
    return "";
  }

  const options = [
    {
      label: masterConfig.showName,
      value: "master"
    },
    {
      label: slaveTopConfig.showName,
      value: "slaveTop"
    }
  ];
  const onChange = ({ target: { value } }) => {
    props.onSaveState({ currentTopValue: value });
  };
  return (
    <div className={styles.leftTab}>
      <Radio.Group
        options={options}
        onChange={onChange}
        value={currentTopValue}
        optionType="button"
        buttonStyle="solid"
      />
    </div>
  );
};

// 主表表单内容
const CommonViewComponent = props => {
  let { slaveTopData = [], masterData = {} } = props;
  const {
    dataRelationJson,
    currentTopValue,
    // bShowSlaveTop,
    slaveTopConfig = {}
  } = props;
  const [expended, setExpanded] = useState(false);
  const commonViewHeight = useRef(0);

  useEffect(
    () => {
      props.onSaveState({ currentExpanded: expended });
    },
    [expended]
  );

  const style = {
    position: "relative"
  };
  if (!expended) {
    style.maxHeight = 97;
    style.overflow = "hidden";
  }

  if (slaveTopConfig.sSqlStr === "noQuery" && dataRelationJson.slaveTop) {
    slaveTopData = props[`${dataRelationJson.slaveTop}Data`];
  }

  const { sBusinessType } = masterData;

  /* 树形展示 */
  const bTree =
    slaveTopConfig &&
    slaveTopConfig.sTableType === "single" &&
    commonUtils.isNotEmptyArr(slaveTopData) && (
    slaveTopData.findIndex(item => commonUtils.isNotEmptyObject(item.sFatherSlaveId)) > -1 ||
      slaveTopData.length  > 1
    );
  // useEffect(
  //   () => {
  //     if (bTree) {
  //       setExpanded(true);
  //     }
  //   },
  //   [bTree]
  // );

  return (
    <div
      style={{
        border: "1px solid #c2c3c5",
        margin: "8px 8px 0 8px",
        backgroundColor: "#fff"
      }}
    >
      <div
        className={"bill-search-group bill-search-group1"}
        ref={ref => {
          _this.commonViewRef = ref;
          if (ref && currentTopValue !== "slaveTop") {
            const { height } = ref.getBoundingClientRect();
            if (height) {
              commonViewHeight.current = height;
            }
          }
        }}
        style={style}
      >
        {bTree ? (
          <SlaveTopTableComponent
            {...props}
            commonViewHeight={commonViewHeight}
          />
        ) : (
          <CommonView {...props} />
        )}
        <div
          style={{ position: "absolute", bottom: 0, right: 5, zIndex: 1000 }}
        >
          <DoubleRightOutlined
            rotate={expended ? -90 : 90}
            onClick={() => {
              setExpanded(!expended);
            }}
          />
        </div>
      </div>
    </div>
  );
};

// 与主表表单切换的从表
const SlaveTopTableComponent = props => {
  const { commonViewHeight, slaveTopConfig, sModelsId } = props;

  const tableProps = {
    ...commonBusiness.getTableTypes("slaveTop", props),
    ...props.onGetTableTypesNew("slaveTop"),
    tableProps: {
      setNoCommonOperate: true
    },
    onSelectRowChange: (tableName, selectedRowKeys) => {
      props.onSelectRowChange(tableName, selectedRowKeys);

      props.onSaveState({
        // slave0Child1SelectedRowKeys: [],
        currentSelectedSlaveData: props[`${tableName}Data`].find(
          item => item.sId === selectedRowKeys[0]
        )
      });
    },
    fixedHeight: 120,
    noVlistTable: true
  };

  /* 树形展示 */
  const bTree =
    slaveTopConfig &&
    slaveTopConfig.sTableType === "single" &&
    commonUtils.isNotEmptyArr(tableProps.data) &&
    tableProps.data.findIndex(item =>
      commonUtils.isNotEmptyObject(item.sFatherSlaveId)
    ) > -1;

  if (bTree) {
    tableProps.data = commonUtils.genTreeByArr(
      tableProps.data,
      "sId",
      "sFatherSlaveId"
    );
  }

  return (
    <div className="xly-bill-list" style={{ marginTop: 8 }}>
      <StaticEditTable {...tableProps} />
    </div>
  );
};

// 状态图标
const AvatarComponent = props => {
  const checkPerson = props.imgPersonSrc
    ? commonUtils.isNotEmptyObject(props.masterData)
      ? props.masterData.sCheckPerson
      : ""
    : "";
  const sInfo = props.imgPersonSrc ? "已审核" : "";
  return (
    <div className={styles.bShow1}>
      <div className={styles.personChecked}>
        <Avatar src={props.imgPersonSrc} />
        <div className={styles.personName}>
          {checkPerson}
          {sInfo}
        </div>
      </div>
    </div>
  );
};

// 第一层tab内容
const TabsLv1Component = props => {
  const { masterConfig = {}, masterData = {} } = props;
  const { gdsconfigformslave = [] } = masterConfig;
  const [showTabList, setShowTabList] = useState([]);
  const sBusinessTypeConfig = gdsconfigformslave.find(
    item => item.bVisible && item.sName === "sBusinessType"
  );
  let sButtonEnabled = "[]";
  if (sBusinessTypeConfig) {
    sButtonEnabled = sBusinessTypeConfig.sButtonEnabled;
  }
  useEffect(
    () => {
      const rules = commonUtils.convertStrToObj(sButtonEnabled, []);
      let iIndex = -1;
      try {
        iIndex = rules.findIndex(
          item =>
            item.condition[0].bFilterName === "sBusinessType" &&
            item.condition[0].bFilterValue === masterData.sBusinessType
        );
      } catch (error) {}
      if (iIndex !== -1) {
        const { showColumn } = rules[iIndex];
        setShowTabList(showColumn);
      } else {
        setShowTabList([]);
      }
    },
    [masterData.sBusinessType]
  );

  const tabsRef = useRef(null);

  useEffect(
    () => {
      if (tabsRef.current) {
        const oList = tabsRef.current.querySelector(".ant-tabs-nav-list");
        if (oList) {
          const oLastTab = oList.querySelectorAll(".ant-tabs-tab");
          const bHasActive = oList.querySelector(".ant-tabs-tab-active");
          if (oLastTab && oLastTab.length && !bHasActive) {
            const nodeKey = oLastTab[oLastTab.length - 1].getAttribute(
              "data-node-key"
            );
            if (nodeKey) {
              props.onSaveCurrentTab(nodeKey);
            }
          }
        }
      }
    },
    [showTabList]
  );

  return (
    <div ref={tabsRef}>
      <Tabs
        activeKey={props.currentTab}
        onChange={props.onTabChange}
        className={styles.slaveTabs}
        tabBarStyle={{ margin: "0 8px" }}
      >
        {getMasterCommonViewTabComponent(props, showTabList)}
        {getSlaveTabCompnent(props, showTabList)}
      </Tabs>
    </div>
  );
};

// 主表commonViewTab页签
const getMasterCommonViewTabComponent = (props, showTabList) => {
  const { masterConfig } = props;
  if (commonUtils.isEmptyObject(masterConfig)) {
    return "";
  }

  /* 取 masterConfig中有多少个Tab页签配置 */
  const masterShowConfig = masterConfig.gdsconfigformslave.filter(
    item => item.bVisible && item.sName !== ""
  );
  /* 有Tab的配置 */
  const diliverConfigTypeArr = [];
  masterShowConfig.forEach(child => {
    if (child.sControlName.indexOf("_") > -1) {
      const tableType = child.sControlName.split("_")[1];
      const isIndex = diliverConfigTypeArr.findIndex(
        item => item === tableType
      );
      if (isIndex === -1) {
        diliverConfigTypeArr.push(tableType);
      }
    }
  });

  if (!diliverConfigTypeArr.length) {
    return "";
  }

  const oTabPane = diliverConfigTypeArr.map(item => {
    let num = item.replace(/[^\d]/g, "").trim();
    const tabName = item.replace(/\d+/g, "");
    if (showTabList.length && !showTabList.includes(tabName)) {
      return "";
    }

    return (
      <TabPane tab={tabName} key={num} className="xly-bill-list">
        <div>
          <CommonView {...props} tableConfigType={item} />
        </div>
      </TabPane>
    );
  });

  return oTabPane;
};

const getiOrder = (config, type, defaultValue) => {
  let slaveOrder = defaultValue;
  const iIndex = config.gdsconfigformslave.findIndex(
    item => item.sControlName === type && item.bVisible
  );
  if (iIndex !== -1) {
    slaveOrder = config.gdsconfigformslave[iIndex].sDefault;
  }
  return slaveOrder;
};

// 非主表tab页签
const getSlaveTabCompnent = (props, showTabList) => {
  const { addStateMap } = props;
  return new Array(_this.maxTableNum).fill("").map((_, index) => {
    const slaveIndex = index === 0 ? "" : index - 1;

    // 是否有配置文件
    const bShow =
      props[`onlySlave${slaveIndex}`] || props[`onlyslave${slaveIndex}`];
    if (!bShow) {
      return "";
    }

    const { [`slave${slaveIndex}Config`]: config = {}, slaveData, slaveSelectedRowKeys } = props;
    const { showName: tabInfo } = config;

    if (showTabList.length && !showTabList.includes(tabInfo)) {
      return "";
    }

    const { gdsconfigformslave } = config;
    const tableName = `slave${slaveIndex}`;

    if (config.showName.includes('_hide')) {
      return "";
    }

    // 是否有子从表（是 -> 展示二级tab）
    let bHasChildSlave = false;
    if (
      commonUtils.isNotEmptyObject(addStateMap) &&
      commonUtils.isNotEmptyObject(config)
    ) {
      // 从表的sChildTableName是否包含子从表sGrd
      const iKey = Object.keys(addStateMap).some(
        key =>
          config.sChildTableName &&
          config.sChildTableName.split(",").includes(addStateMap[key].sGrd)
      );
      if (iKey) {
        bHasChildSlave = true;
        // slaveIndex = iKey.split("slave")[1].split("Child")[0];
      }
    }

    if (tableName === 'slave1') {
      const iConfigIndex = gdsconfigformslave.findIndex(item => item.sName === 'dConsumeQty');
      if (iConfigIndex > -1 && commonUtils.isNotEmptyArr(slaveSelectedRowKeys) && commonUtils.isNotEmptyArr(slaveData)) {
        const iSlaveIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys[0]);
        gdsconfigformslave[iConfigIndex].bReadonly = slaveData[iSlaveIndex].sFatherSlaveId === '';
      }
    }

    // 从表表格宽度
    let salveIColValue = 24;
    const iIndex = gdsconfigformslave.findIndex(
      item =>
        item.sControlName === "bShowAllTable" ||
        item.sControlName === "bShowSlaveTable"
    );
    if (iIndex !== -1 && !gdsconfigformslave[iIndex].bVisible) {
      salveIColValue = 0;
    } else {
      const iShowLeftIndex = gdsconfigformslave.findIndex(
        item => item.sControlName === "bShowLeft" && item.bVisible
      );
      if (iShowLeftIndex !== -1) {
        salveIColValue = gdsconfigformslave[iShowLeftIndex].iColValue;
      }

      // 是否有表格字段
      const bShowTable = gdsconfigformslave.some(
        item =>
          item.sName !== "" &&
          item.bVisible &&
          item.sControlName.indexOf("Btn") === -1
      );

      if (!bShowTable) {
        salveIColValue = 0;
      }
    }

    // 获取各部分顺序
    const slaveOrder = getiOrder(config, "slaveOrder", 0);
    const viewTableOrder = getiOrder(config, "viewTableOrder", 10);
    const slaveChildOrder = getiOrder(config, "slaveChildOrder", 20);

    const porpsNew = {
      ...props,
      tableName,
      bHasChildSlave,
      slaveOrder,
      viewTableOrder,
      slaveChildOrder,
      salveIColValue
    };

    return (
      <TabPane tab={tabInfo} key={10 * (index + 1)} className="xly-bill-list">
        <div
          className="TabPaneStyle"
          style={{
            height: props.onGetHeight()
          }}
        >
          <Row gutter={[8, 0]}>
            <SlaveTableComponent {...porpsNew} />
            <CommonViewTableComponent {...porpsNew} />
            <SlaveChildTableComponent {...porpsNew} />
          </Row>
        </div>
      </TabPane>
    );
  });
};

/**
 * 从表组件
 * sControlName：bShowLeft，bVisible，取iColValue作宽度
 * iColValue为0时不显示，默认为24
 */
const SlaveTableComponent = props => {
  const {
    tableName,
    sModelsType,
    slaveOrder,
    salveIColValue,
    bHasChildSlave,
    bAutoHeight,
    AutoTableHeight,
    slaveData,
  } = props;
  const {
    [`${tableName}Config`]: config,
    [`${tableName}Data`]: data,
    [`${tableName}Pagination`]: sPagination,
    sModelsId,
  } = props;

  if (!salveIColValue) {
    // 是否有表单组件
    const bHasViewConfigs = config.gdsconfigformslave.some(
      item =>
        item.sName !== "" &&
        item.bControl &&
        item.sControlName.indexOf("Btn") === -1 &&
        item.sControlName.indexOf("_") === -1
    );
    return bHasViewConfigs ? <div style={{ width: "100%", height: 4 }} /> : "";
  }

  // 表格是否分页
  const bPagination = commonUtils.isNotEmptyObject(config)
    ? config.bPagination
    : false;

  let pagination = false;
  if (bPagination) {
    // 分页
    let pageSize = commonConfig.pageSize;
    const pageSizeTemp = props[`${tableName}PageSize`];
    if (commonUtils.isNotEmptyNumber(pageSizeTemp) && pageSizeTemp !== 0) {
      pageSize = pageSizeTemp;
    }

    const isSmall = false;
    pagination = {
      pageSize,
      total: commonUtils.isEmptyArr(data) ? 0 : data.length,
      current: commonUtils.isEmptyObject(sPagination) ? 1 : sPagination.current,
      ...sPagination,
      hideOnSinglePage: false,
      size: isSmall ? "small" : "large",
      pageSizeOptions: commonConfig.pageSizeOptions,
      showSizeChanger: !isSmall,
      showQuickJumper: !isSmall
    };
  }

  // 是否展示操作按钮
  let bShowOperate = true;
  if (commonUtils.isNotEmptyObject(config)) {
    const condition1 = config.sTbName === "sysbillcheckresult";
    const condition2 = config.gdsconfigformslave.some(
      item =>
        item.sControlName && item.sControlName.includes("setNoCommonOperate")
    );
    if (condition1 || condition2) {
      bShowOperate = false;
    }
  }

  const listType = "commonMultiList";
  const setOpterationColumn =
    sModelsType !== "cost/cosexpenseshare" &&
    sModelsType !== listType &&
    bShowOperate
      ? "Y"
      : "";

  const baseProps = commonBusiness.getTableTypes(tableName, props);

  /* 过滤部件数据 */
  const dataFilter = (tableProps, type) => {
    let oriData = commonUtils.isNotEmptyArr(tableProps.data)
      ? tableProps.data
      : [];
    let config = commonUtils.isNotEmptyArr(tableProps.config)
      ? tableProps.config
      : [];
    let res = [];
    const bPassRateTable =
      config.showName === "合格率评审"; /* 根据首选、备选过滤合格率评审数据 */
    if (type === "slave0Child1" && bPassRateTable) {
      // const { currentProductTechnologyVer, currentProductCardId } = props;
      // const controlFilterData = oriData
      //   .filter(
      //     item =>
      //       item.sProductCardId === currentProductCardId &&
      //       item.sProductTechnologyVer === currentProductTechnologyVer
      //   )
      //   .reduce((result, item) => {
      //     const slaveSelectedRow =
      //       props.currentSelectedSlaveData || props.slaveData[0];
      //     const sCombinedMemoArr = commonUtils.isJSON(item.sCombinedMemo)
      //       ? JSON.parse(item.sCombinedMemo)
      //       : [];
      //
      //     const getSlaveSelectedRowChildren = (allData, sId) => {
      //       let result = [];
      //       allData.forEach(item => {
      //         if (item.sFatherSlaveId === sId) {
      //           result.push(item);
      //           result = [
      //             ...result,
      //             ...getSlaveSelectedRowChildren(allData, item.sId)
      //           ];
      //         }
      //       });
      //       return result;
      //     };
      //     const slaveSelectedRowChildren = getSlaveSelectedRowChildren(
      //       props.slaveData,
      //       slaveSelectedRow.sId
      //     );
      //     const slaveRows = [slaveSelectedRow, ...slaveSelectedRowChildren];
      //     const len = sCombinedMemoArr.filter(
      //       item =>
      //         item.sProductNo &&
      //         slaveRows.some(
      //           slaveRow => slaveRow.sProductNo === item.sProductNo
      //         )
      //     ).length;
      //     if (len) {
      //       result.push(item);
      //     }
      //     return result;
      //   }, []);
      //
      // res = controlFilterData;
      // _this.controlFilterData = controlFilterData;
      res = _this.controlFilterData;
    } else if (
      (type === "materials" && (config.showName === "工序物料" || config.showName === "全部材料" )) ||
      (type === "slave0" && config.showName === "工艺评审")
    ) {
      /* 根据部件选中行 过滤材料、工序 */
      const {
        currentProductTechnologyVer,
        currentProductCardId,
        slave0Child1SelectedRowKeys
      } = props;

      const slave0Child1Data =
        _this.controlFilterData || props.slave0Child1Data;

      const iSIndex = commonUtils.isNotEmptyArr(slave0Child1Data)
        ? slave0Child1Data.findIndex(item =>
            slave0Child1SelectedRowKeys.includes(item.sId)
          )
        : -1;
      let slaveRow = {};
      if (iSIndex > -1) {
        slaveRow = slave0Child1Data[iSIndex];
      } else if (commonUtils.isNotEmptyArr(slave0Child1Data)) {
        const controlFilterData = slave0Child1Data.filter(
          item =>
            item.sProductCardId === currentProductCardId &&
            item.sProductTechnologyVer === currentProductTechnologyVer
        );
        if (
          commonUtils.isNotEmptyArr(controlFilterData) &&
          controlFilterData.length === 1
        ) {
          slaveRow = controlFilterData[0];
        }
      }
      let filterData = [];
      if (commonUtils.isNotEmptyObject(slaveRow)) {
        filterData = oriData.filter(item => item.sControlId === slaveRow.sId);
      }
      res = filterData;
    } else if(type ==='slave4' && config.showName === '物料采购时间'){
      if(commonUtils.isNotEmptyArr(props.slave0Child1SelectedRowKeys)) {
        res = oriData.filter(item => item.sOrderControlId === props.slave0Child1SelectedRowKeys[0]  && (item.sNons !== "非标"));
      } else {
        res = oriData;
      }
    } else {
      res = oriData;
    }
    return res;
  };

  let bForbiddenDrag = true; /* 禁止拖动 */
  if (baseProps.name === 'slave0' && config.showName === '工艺评审') {
    if(sModelsId === '12710101117054908553170' || sModelsId ==='12710101117183304335380') {
      bForbiddenDrag = false;
    }
    baseProps.tableId = props.processTableId;
    baseProps.onDrag = props.onDrag;
    baseProps.dragHandle = true;
    baseProps.noVlistTable = true;
    baseProps.bForbiddenDrag = bForbiddenDrag; /* 是否可以拖动 */
  }

  // 表格属性
  const tableProps = {
    ...baseProps,
    ...props.onGetTableTypesNew(tableName),
    onSelectRowChange: props.onSelectRowChange,
    setOpterationColumn,
    fixedHeight: !bAutoHeight
      ? props.onGetHeight(
          baseProps.headerColumn.some(item => item.title.includes("-"))
            ? 110
            : 80,
          bHasChildSlave && salveIColValue === 24
        )
      : null,
    tableProps: {
      setAdd,
      setCopy,
      setCopyAll,
      setDelete,
      pagination,
      onChange: props.onTitleChange.bind(this, tableName),
      AutoTableHeight
    },
    data: dataFilter(baseProps, tableName)
  };

  if(config.showName === '合格率评审'){
    tableProps.tableProps.onRow =(record => {
      return {
        onClick: () => { props.onRowClick(tableName, record); },
        // onMouseEnter: () => { props.onRowMouseEnter('slaveInfo', record); },
      };
    })
    tableProps.tableProps.setProcess = true;

    let chooseProcessConfigRow;
    /* 获取toolbar 选择工序 */
    if (commonUtils.isNotEmptyObject(config)) {
      const onChooseProcessIndex = config.gdsconfigformslave.findIndex(item => item.sControlName === 'BtnChooseProcess');
      if (onChooseProcessIndex > -1) {
        chooseProcessConfigRow = config.gdsconfigformslave[onChooseProcessIndex];
      }
    }
    tableProps.tableProps.chooseProcessConfigRow = chooseProcessConfigRow;

    if(commonUtils.isNotEmptyArr(slaveData)) {
      if(commonUtils.isEmptyObject(slaveData[0].sMainProductTechnologyId) && commonUtils.isEmptyObject(slaveData[0].sSpareProductTechnologyId) ) {
        tableProps.bLimitOperate = true;
      }
    }
  }
  if (baseProps.name === 'slave0' && config.showName === '工艺评审') {
    tableProps.fixedHeight = props.materialsPackup ? 'calc(38vh + 60px)' :  'calc(16vh)';
  }

  /* 树形展示 */
  const bTree =
    config.sTableType === "single" &&
    commonUtils.isNotEmptyArr(tableProps.data) &&
    tableProps.data.some(rowData =>
      commonUtils.isNotEmptyObject(rowData.sFatherSlaveId)
    );

  if (bTree) {
    tableProps.data = commonUtils.genTreeByArr(
      tableProps.data,
      "sId",
      "sFatherSlaveId"
    );
  }

  const { name } = tableProps;
  const tableInfoName = `${name}Info`;
  const bGxwl = tableProps.config.showName === "工序物料" || tableProps.config.showName === "全部材料";
  if (!bGxwl && commonUtils.isNotEmptyObject(props[`${tableInfoName}Config`])) {
    const tableInfoProps = {
      ...commonBusiness.getTableTypes(tableInfoName, props),
      tableProps: {
        rowKey: "sId",
        pagination: false,
        rowSelection: null
        // onChange: props.onTitleChange.bind(this, "slaveInfo")
      }
    };
    tableProps.setExpandedRowRender = "Y";
    tableProps.slaveInfo = tableInfoProps;
    tableProps.onTableFilterData = props.onTableFilterData;
  }

  // 多表树形展示
  useEffect(() => {
    const tempFun = async () => {
      const { config, name } = tableProps;
      const { sTableType, sGrd } = config;
      if (sTableType === "multiple") {
        const { formData, currentId } = props;
        const sId = currentId !== undefined ? currentId : "";
        const tableInfoConfig = formData.find(
          item => item.sGrd === `${sGrd}_child`
        );
        if (tableInfoConfig) {
          let addState = {};
          if (tableInfoConfig.sSqlStr !== "noQuery") {
            const conditonValues = props.onGetSqlConditionValues(tableInfoConfig);
            addState =
              (await props.handleGetDataSet({
                name: `${name}Info`,
                configData: tableInfoConfig,
                condition: {
                  sSqlCondition: { ...conditonValues, sParentId: sId }
                },
                isWait: true
              })) || {};
          }
          addState[`${name}InfoConfig`] = tableInfoConfig;
          addState[`${name}InfoColumn`] = commonFunc.getHeaderConfig(
            tableInfoConfig
          );
          addState[`${name}InfoPageSize`] =
            commonUtils.isNotEmptyNumber(tableInfoConfig.iPageSize) &&
            tableInfoConfig.iPageSize !== 0
              ? tableInfoConfig.iPageSize
              : commonConfig.pageSize;

          props.onSaveState(addState);
        }
      }
    }
    tempFun();
  }, []);

  return (
    <Col
      span={salveIColValue}
      order={slaveOrder}
      className={styles.costomTabBillTable}
    >
      <StaticEditTable {...tableProps} />
    </Col>
  );
};

/**
 * 从表form表单
 * sControlName：bShowRight，bVisible，取iColValue作宽度
 * 没有配置iColValue，没有配置表格字段，iColValue宽度为24
 * iColValue为0时不显示，默认为0
 */
const CommonViewTableComponent = props => {
  const { tableName, viewTableOrder, viewConfigsCostom, formData } = props;
  const { name: tableNameNew = tableName } = props.onGetTableTypesNew(
    tableName
  );
  let {
    [`${tableName}Config`]: config = {},
    [`${tableName}SelectedRowKeys`]: selectedRowKeys = []
  } = props;


  let { [`${tableNameNew}Data`]: data } = props;
  // 从表表格变化时重新取selectedRowKeys 暂时不知道什么原因是slave1.
  if (tableNameNew === 'slave' || tableNameNew === 'slave5') {
    selectedRowKeys = props[`${tableNameNew}SelectedRowKeys`] ? props[`${tableNameNew}SelectedRowKeys`] : [];
  }

  if(tableNameNew === 'slave0Child1') {
    selectedRowKeys = props[`${tableNameNew}SelectedRowKeys`] ? props[`${tableNameNew}SelectedRowKeys`] : [];
  }

  if ((tableName === "slave0Child1" || tableName ==='slave2Child1' || tableName ==='slave0Child4') && _this.controlFilterData) {
    data = _this.controlFilterData;
  }

  let { gdsconfigformslave = [] } = config;

  // 判断是否工序参数展示
  const bShowProcessParam = gdsconfigformslave.some(
    item => item.sControlName === "sProcessParamType"
  );
  if (bShowProcessParam) {
    return "";
  }

  // 展示右侧
  const iShowRightIndex = gdsconfigformslave.findIndex(
    item => item.sControlName === "bShowRight" && item.bVisible
  );

  // 设置宽度
  let iColValue = 0;
  if (iShowRightIndex !== -1) {
    iColValue = gdsconfigformslave[iShowRightIndex].iColValue;
  }

  // 是否有表格字段
  const bShowTable =
    gdsconfigformslave.some(
      item =>
        item.sName !== "" &&
        item.bVisible &&
        item.sControlName.indexOf("Btn") === -1
    ) &&
    !gdsconfigformslave.some(
      item => item.sControlName.indexOf("hideAllFields") !== -1
    );

  // 如果是孙表格
  if (tableName.split("Child").length >= 3) {
    iColValue = 24;
  }

  if (!iColValue) {
    if (!bShowTable) {
      iColValue = 24;
    } else {
      return "";
    }
  }

  const { currentPane = {} } = props.app;
  const { title = "" } = currentPane;

  const getGdsconfigformslaveNew = (gdsconfigformslaveOld, bOldOrderValue) => {
    const { slaveData, slaveSelectedRowKeys }= props;
    const iIndex = commonUtils.isNotEmptyArr(slaveData) ? commonUtils.isNotEmptyArr(slaveSelectedRowKeys) ?
      slaveData.findIndex(item => slaveSelectedRowKeys.includes(item.sId)) : 0: -1;
    const slaveRow = iIndex > -1 ? slaveData[iIndex] : {};
    const bHideCondition = bOldOrderValue
      ? slaveRow?.bOldOrder
      : props.slaveData?.some(item => !item.bOldOrder);
    if (bHideCondition) {
      const gdsconfigformslaveNew = JSON.parse(JSON.stringify(gdsconfigformslaveOld))
      const dPlanAdd = gdsconfigformslaveNew.find(item => item.sName === "dPlanAdd" || item.sControlName === "dPlanAdd");
      const dSpecialAdd = gdsconfigformslaveNew.find(item => item.sName === "dSpecialAdd" || item.sControlName === "dSpecialAdd");
      if (dPlanAdd) {
        dPlanAdd.bReadonly = true;
      }
      if (dSpecialAdd) {
        dSpecialAdd.bReadonly = true;
      }
      return gdsconfigformslaveNew;
    }
    return gdsconfigformslaveOld;
  }

  // 订单工艺评审合格率， 如果从表bOldOrder为true，则dPlanAdd、dSpecialAdd字段只读
  if (title.indexOf("订单工艺评审") !== -1 || title.indexOf("补单工艺评审") !== -1) {
    if (tableName === 'slave0Child1' || tableName === 'slave2Child1') {
      gdsconfigformslave = getGdsconfigformslaveNew(gdsconfigformslave, true);
    }
  }

  // 订单生管评审合格率， 如果从表bOldOrder为FALSE，则dPlanAdd、dSpecialAdd字段只读
  if (title.indexOf("订单生管评审") !== -1 || title.indexOf("补单生管评审") !== -1) {
    if (tableName === 'slave0Child1' || tableName === 'slave2Child1') {
      gdsconfigformslave = getGdsconfigformslaveNew(gdsconfigformslave, false);
    }
  }


  // 表单字段
  const viewConfigs =
    viewConfigsCostom ||
    gdsconfigformslave.filter(
      item =>
        (item.sName !== "" &&
          item.bControl &&
          item.sControlName.indexOf("Btn") === -1 &&
          item.sControlName.indexOf("_") === -1) ||
        (item.sControlName && item.sControlName.indexOf("DividerArea") !== -1)
    );

  // 数据为选中行数据
  const [viewRow, setViewRow] = useState({});
  useEffect(
    () => {
      if (
        commonUtils.isNotEmptyArr(selectedRowKeys) &&
        commonUtils.isNotEmptyArr(data)
      ) {
        const iIndex = data.findIndex(item =>
          selectedRowKeys.includes(item.sId)
        );

        if (iIndex > -1) {
          setViewRow(data[iIndex]);
        } else {
          setViewRow(data[0]);
        }
      } else if (commonUtils.isNotEmptyArr(data)) {
        setViewRow(data[0]);
      } else {
        setViewRow({});
      }
    },
    [selectedRowKeys[0], JSON.stringify(data)]
  );

  // 上批下批不同标红
  const [viewConfigsNew, setViewConfigsNew] = useState([]);
  const { sChildTableName } = config;
  const childConfig =
    formData.find(
      item =>
        item.sGrd === sChildTableName &&
        (item.showName.includes("对比") || item.showName.includes("上批"))
    ) || {};
  const childName = `${tableName}Child0`;
  const childData = props[`${childName}Data`] || [];
  const { gdsconfigformslave: childGdsconfigformslave = [] } = childConfig;
  useEffect(
    () => {
      const childViewRow = childData[0] || {};
      const configFilter = gdsconfigformslave.filter(
        item => item.bControl && item.sName
      );
      const childConfigFilter = childGdsconfigformslave.filter(
        item => item.bControl && item.sName
      );
      if (
        commonUtils.isNotEmptyArr(configFilter) &&
        commonUtils.isNotEmptyArr(childConfigFilter) &&
        commonUtils.isNotEmptyObject({ ...viewRow, ...childViewRow })
      ) {
        const tempViewConfigs = JSON.parse(JSON.stringify(viewConfigs));
        configFilter.forEach(item => {
          const { sName } = item;
          const iChildIndex = childConfigFilter.findIndex(
            item => item.sName === `${sName}Up`
          );
          if (iChildIndex !== -1) {
            const value = viewRow[`${sName}Up`];
            const childValue = viewRow[sName];
            const iIndex = tempViewConfigs.findIndex(
              item => item.sName === sName
            );

            const bDiff = value !== undefined && value !== childValue;
            tempViewConfigs[iIndex].costomStyle = bDiff
              ? styles.costomTabBillDiff
              : "";
          }
        });

        setViewConfigsNew(tempViewConfigs);
      }
    },
    [JSON.stringify(data), JSON.stringify(childData), viewRow]
  );


  const [viewProps, setViewProps] = useState({});
  useEffect(
    () => {
      const viewConfigsBase = commonUtils.isNotEmptyArr(viewConfigsNew) ? viewConfigsNew : viewConfigs;
      if (['12710101117055480463460'].includes(props?.sModelsId)) {
        const index = viewConfigsBase?.findIndex( i => i && i.sName === 'tEstimateCompletDate');
        if (index >= 0) {
          if (!props.enabled) {
            viewConfigsBase[index].buttonbReadonly = true;
          } else {
            viewConfigsBase[index].buttonbReadonly = false;
          }
        }
      }
      setViewProps({
        ...props,
        viewConfigs: viewConfigsBase,
        tableConfig: config,
        iColValueView: iColValue,
        viewRow,
        tableName: tableNameNew,
        slaveName: tableName,
        viewOrder: viewTableOrder
      });
    },
    [
      viewConfigsNew,
      JSON.stringify(viewConfigs),
      viewRow,
      props.enabled,
      props.showTableName,
      props.masterData,
    ]
  );

  return <CommonViewTable {...viewProps} />;
};

// 获取从表form表单（额外）
const getCommonViewTableComponentExtra = props => {
  const { tableName, viewTableOrder = 5 } = props;
  const { [`${tableName}Config`]: config = {} } = props;

  const { gdsconfigformslave = [] } = config;
  const viewConfigs = gdsconfigformslave.filter(
    item =>
      item.sName !== "" &&
      item.bControl &&
      item.sControlName.indexOf("Btn") === -1 &&
      item.sControlName.indexOf("_") !== -1
  );
  if (viewConfigs.length === 0) {
    return "";
  }

  const viewJson = viewConfigs.reduce((result, item) => {
    const group = item.sControlName.split("_");
    const tabInfo = group[1].replace(/\d+/g, "");
    let num = group[1].replace(/[^\d]/g, "").trim();
    num = num === "" ? 1 : num;
    if (!result[tabInfo]) {
      result[tabInfo] = {
        num,
        viewConfigs: []
      };
    }
    result[tabInfo].viewConfigs.push(item);
    return result;
  }, {});

  return Object.keys(viewJson).map(tabInfo => {
    const { num, viewConfigs } = viewJson[tabInfo];

    return (
      <TabPane tab={tabInfo} key={num}>
        <CommonViewTableComponent
          {...props}
          viewTableOrder={viewTableOrder}
          viewConfigsCostom={viewConfigs}
        />
      </TabPane>
    );
  });
};

// 获取从表form表单（额外）
const getCommonViewTableComponentCombine = props => {
  const { tableName, viewTableOrder = 5 } = props;
  const { [`${tableName}Config`]: config = {} } = props;

  const { gdsconfigformslave = [] } = config;
  const viewConfigs = gdsconfigformslave.filter(
    item =>
      item.sName === 'dCombinedQty'
  );
  if(commonUtils.isNotEmptyArr(viewConfigs)) {
    viewConfigs[0].bControl = false;
  }
  if (viewConfigs.length === 0) {
    return "";
  }

  return (
    <CommonViewTableComponent
      {...props}
      viewTableOrder={viewTableOrder}
      viewConfigsCostom={viewConfigs}
    />
  );
};

/**
 * 子从表格组件
 */
const SlaveChildTableComponent = props => {
  const {
    sModelsType,
    addStateMap,
    tableName,
    bHasChildSlave,
    slaveChildOrder,
    salveIColValue,
    [`${tableName}Config`]: slaveConfig,
    masterData,
    masterConfig = [],
    currentProductCardId
  } = props;

  if (!bHasChildSlave) {
    return "";
  }

  // 是否工艺评审（特殊处理）
  const bGyps =
    slaveConfig.showName && slaveConfig.showName.includes("工艺评审");
  // 是否生管评审（特殊处理）
  const bSgps = false;
  // slaveConfig.showName && slaveConfig.showName.includes("生管评审");
  // 是否物资评审（特殊处理）
  const bWzps =
    slaveConfig.showName && slaveConfig.showName.includes("物资评审");
  // 是否品管评审（特殊处理）
  const bPgps =
    slaveConfig.showName && slaveConfig.showName.includes("品管评审");

  // 是否有表单字段
  const bHasViewConfigs = slaveConfig.gdsconfigformslave.some(
    item =>
      item.sName !== "" &&
      item.bControl &&
      item.sControlName.indexOf("Btn") === -1
  );

  const slaveChildNameArr = Object.keys(addStateMap)
    .filter(
      key =>
        slaveConfig.sChildTableName
          .split(",")
          .includes(addStateMap[key].sGrd) &&
        addStateMap[key].sGrd.indexOf("_wz") === -1
    )
    .map(key => key.split("Config")[0]);

  /* 过滤非标材料数据 */
  const dataFilterTable = (tableProps, type) => {
    let oriData = commonUtils.isNotEmptyArr(tableProps.data)
      ? tableProps.data
      : [];
    let config = commonUtils.isNotEmptyArr(tableProps.config)
      ? tableProps.config
      : [];
    let res = [];
    const bNoPassMaterials =
      config.showName === "非标材料"; /* 根据首选、备选过滤合格率评审数据 */

    const bMaterialsInfo =
      config.showName === "物料信息"; /* 根据首选、备选过滤合格率评审数据 */

    if (type === "slave0Child2" && bNoPassMaterials) {
      /* 根据部件选中行 过滤材料、工序 */
      const {
        slaveData, slaveSelectedRowKeys,
        currentProductTechnologyVer,
        currentProductCardId,
        slave0Child1Data,
        slave0Child1SelectedRowKeys,
        currentSelectedSlaveData,
        materialsData
      } = props;

      const iIndex = commonUtils.isNotEmptyArr(slaveData) ? commonUtils.isNotEmptyArr(slaveSelectedRowKeys) ?
        slaveData.findIndex(item => slaveSelectedRowKeys.includes(item.sId)) : 0: -1;
      const slaveRow = iIndex > -1 ? slaveData[iIndex] : {};
      const iControlIndex = commonUtils.isNotEmptyArr(slave0Child1Data) ?
        slave0Child1Data.findIndex(
          controlItem => {
            const sCombinedMemoArr = JSON.parse(controlItem.sCombinedMemo);
            const sCombinedMemoFilterArr = sCombinedMemoArr.filter(item => item.dCombineQty > 0 && item.sProductNo === slaveRow?.sProductNo);
            return controlItem.sProductCardId === currentProductCardId &&
              commonUtils.isNotEmptyArr(sCombinedMemoFilterArr)
          }) : -1;
      const controlFilterData = iControlIndex > -1 ? [slave0Child1Data[iControlIndex]] : [];
      const filterData = commonUtils.isNotEmptyArr(materialsData) && commonUtils.isNotEmptyArr(controlFilterData)
        ? materialsData.filter(
            item =>
              item.sControlId === controlFilterData[0].sId &&
              (item.sNons === "非标")
              // (item.sNons === "非标" || item.sZmldlt === "版材")
          )
        : [];
      res = filterData;
    }else if(type === 'slave0Child3') { /* 改版处 */
      const { currentProductCardId, slaveSelectedRowKeys } = props;
      if(commonUtils.isNotEmptyArr(oriData)) {
        if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
          res = oriData.filter(item => item.sProductCardId === currentProductCardId && item.sSlaveId === slaveSelectedRowKeys[0])
        } else {
          res = oriData.filter(item => item.sProductCardId === currentProductCardId)
        }
      }
    } else if (type === "slave1Child0") {
      const { slave1Child0Data, slaveSelectedRowKeys } = props;
      // 拆分工单后过滤订单从表数据
      if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
        const filterData = commonUtils.isNotEmptyArr(slave1Child0Data)
          ? slave1Child0Data.filter(item => item.sOrderSplitSlaveId === slaveSelectedRowKeys[0])
          : [];
        res = filterData;
      } else {
        res = oriData;
      }

    } else if(type === 'slave3Child0' && bMaterialsInfo){ /* 物料信息 过滤逻辑 */
      /* 默认过滤条件
        sInkBOMsMaterialsId         空或null
        bMainMaterials              等于 1
        sParentMaterialsId          空或null
        切换查看二级：
        sInkBOMsMaterialsId         不等于空
        bMainMaterials              等于 1
        sParentMaterialsId          空或null */
      const { materialsData, bSecondMainMaterials } = props;
      if(commonUtils.isNotEmptyArr(materialsData)) {
        let materialsFilterData =  materialsData;
        if(commonUtils.isNotEmptyArr(_this.controlFilterData)) {
          materialsFilterData = materialsData.filter(item => item.sControlId === _this.controlFilterData[0].sId && (item.sNons !== "非标"));
        }
        if(bSecondMainMaterials) { /*  切换查看二级： */
          res = materialsFilterData.filter(item => commonUtils.isEmptyObject(item.sParentMaterialsId)
            && item.sMaterialStructure === '2'
            && item.bMainMaterials && (item.sNons !== "非标")
          )
        } else { /* 默认过滤 */
          res = materialsFilterData.filter(item => commonUtils.isEmptyObject(item.sParentMaterialsId)
            && item.sMaterialStructure === '1'
            && item.bMainMaterials && (item.sNons !== "非标")
          )
        }

      }
    } else if((type === "slave2Child0" || type ==='slave6Child1') && config.showName === "工单交期"){ /* 根据从表选中行与工单交期sOrderSlaveId关系过滤工单交期数据 */
      const slaveSelectedRow = commonUtils.isNotEmptyArr(props.slaveData) ?  props.currentSelectedSlaveData || props.slaveData[0]:{};
      if(commonUtils.isNotEmptyObject(slaveSelectedRow)) {
        const filterData = oriData.filter(item => item.sOrderSlaveId === slaveSelectedRow.sId && (item.sNons !== "非标"));
        if(commonUtils.isNotEmptyArr(filterData)) {
          res = filterData;
        }
      }

    }else if(type === "slave6Child0" && config.showName === "物料到货时间变化记录"){ /* 物料到货时间变化记录 */
      if(commonUtils.isNotEmptyArr(props.slave0Child1SelectedRowKeys)) {
        res = oriData.filter(item => item.sOrderControlId === props.slave0Child1SelectedRowKeys[0] && (item.sNons !== "非标"));
      } else {
        res = oriData;
      }
    }else if(type === "slave5Child5"){ /* 车间产前提醒 */
      const slaveSelectedRow = commonUtils.isNotEmptyArr(props.slaveData) ?  props.currentSelectedSlaveData || props.slaveData[0]:{};
      if(commonUtils.isNotEmptyObject(slaveSelectedRow)) {
        res = oriData.filter(item => item.sSlaveId === slaveSelectedRow.sId);
      } else {
        res = oriData;
      }
    } else {
      res = oriData;
    }
    return res;
  };

  const tablePropsList = [];
  slaveChildNameArr.forEach(slaveChildName => {
    // 是否展示操作按钮
    let bShowOperate = true;
    const config = props[`${slaveChildName}Config`];
    if (commonUtils.isNotEmptyObject(config)) {
      const condition1 = config.sTbName === "sysbillcheckresult";
      const condition2 = config.gdsconfigformslave.some(
        item =>
          item.sControlName && item.sControlName.includes("setNoCommonOperate")
      );
      if (condition1 || condition2) {
        bShowOperate = false;
      }
    }

    const listType = "commonMultiList";
    const setOpterationColumn =
      sModelsType !== "cost/cosexpenseshare" &&
      sModelsType !== listType &&
      bShowOperate
        ? "Y"
        : "";
    const item = {
      ...commonBusiness.getTableTypes(`${slaveChildName}`, props),
      ...props.onGetTableTypesNew(`${slaveChildName}`),
      // tableBelone: 'list',
      setOpterationColumn,
      tableProps: {
        setAdd,
        setCopy,
        setCopyAll,
        setDelete,
        AutoTableHeight: bHasViewConfigs ? window.innerHeight - 500 : null
      },
      data: dataFilterTable(
        commonBusiness.getTableTypes(`${slaveChildName}`, props),
        slaveChildName
      )
    };

    const hideAllFields = item.config.gdsconfigformslave.some(
      item => item.sControlName.indexOf("hideAllFields") !== -1
    );
    if (hideAllFields) {
      item.headerColumn = [];
    }

    /* 树形展示 */
    const bTree =
      config.sTableType === "single" &&
      commonUtils.isNotEmptyArr(item.data) &&
      item.data.some(rowData =>
        commonUtils.isNotEmptyObject(rowData.sFatherSlaveId)
      );

    if (bTree) {
      item.data = commonUtils.genTreeByArr(item.data, "sId", "sFatherSlaveId");
    }

    item.sChildTableName = item.config.sChildTableName;
    if (bHasViewConfigs) {
      // 如果从表位置是表单展示
      item.fixedHeight = null;
    } else if (item.sChildTableName) {
      // 如果有孙从表
      item.fixedHeight = props.onGetHeight(80, true);
    }
    // else if (bGyps) {
    //   // 如果是工艺评审
    //   item.fixedHeight = props.onGetHeight(120);
    // }
    else if (salveIColValue === 24) {
      // 如果有从表，并且占了24格
      item.fixedHeight = props.onGetHeight(80, true);
    } else {
      item.fixedHeight = props.onGetHeight(80);
    }
    tablePropsList.push(item);
  });

  tablePropsList.forEach(tableProps => {
    const { name } = tableProps;
    const tableInfoName = `${name}Info`;
    if (commonUtils.isNotEmptyObject(props[`${tableInfoName}Config`])) {
      const tableInfoProps = {
        ...commonBusiness.getTableTypes(tableInfoName, props),
        tableProps: {
          rowKey: "sId",
          pagination: false,
          bSlaveInfo: true
          // rowSelection: null
          // onChange: props.onTitleChange.bind(this, "slaveInfo")
        }
      };
      tableProps.setExpandedRowRender = "Y";
      tableProps.slaveInfo = tableInfoProps;
      tableProps.onTableFilterData = props.onTableFilterData;
    }
    if(name === 'slave3Child0') {
      tableProps.sourceAllData = props.materialsData;
      tableProps.fixedHeight =  props.wzPackup ? 500 : tableProps.fixedHeight;
    }
  });


  // 多表树形展示
  useEffect(
    () => {
      if (tablePropsList.length) {
        tablePropsList.forEach(async (tableProps, index) => {
          const { config, name } = tableProps;
          const { sTableType, sGrd } = config;
          if (sTableType === "multiple") {
            const { formData, currentId } = props;
            const sId = currentId !== undefined ? currentId : "";
            const tableInfoConfig = formData.find(
              item => item.sGrd === `${sGrd}_child`
            );
            if (tableInfoConfig) {
              let addState = {};
              if (tableInfoConfig.sSqlStr !== "noQuery") {
                const conditonValues = props.onGetSqlConditionValues(
                  tableInfoConfig
                );
                addState =
                  (await props.handleGetDataSet({
                    name: `${name}Info`,
                    configData: tableInfoConfig,
                    condition: {
                      sSqlCondition: { ...conditonValues, sParentId: sId }
                    },
                    isWait: true
                  })) || {};
              }
              if (name === 'slave3Child0') {
                addState[`${name}Data`] = props.materialsData;
              }
              addState[`${name}InfoConfig`] = tableInfoConfig;
              addState[`${name}InfoColumn`] = commonFunc.getHeaderConfig(
                tableInfoConfig
              );
              addState[`${name}InfoPageSize`] =
                commonUtils.isNotEmptyNumber(tableInfoConfig.iPageSize) &&
                tableInfoConfig.iPageSize !== 0
                  ? tableInfoConfig.iPageSize
                  : commonConfig.pageSize;

              // const replaceMaterials =
              //   "slave3Child0Child0Data"; /* 替换物料数据 */
              // const slaveInfoData = commonUtils.isNotEmptyObject(addState)
              //   ? addState[`${name}InfoData`]
              //   : [];
              // const filterData = commonUtils.isNotEmptyArr(slaveInfoData)
              //   ? slaveInfoData.filter(item =>
              //       commonUtils.isNotEmptyObject(item.sParentMaterialsId)
              //     )
              //   : [];
              // addState[replaceMaterials] = commonUtils.isNotEmptyArr(filterData)
              //   ? filterData
              //   : [];
              props.onSaveState(addState);
            }
          }
        });
      }
    },
    [tablePropsList.length, props.bRefreshTime]
  );

  let iColValue = 24;
  if (salveIColValue > 0 && salveIColValue < 24) {
    iColValue = 24 - salveIColValue;
  }

  const { gdsconfigformslave = [] } = masterConfig;
  const [hideTabList, setHideTabList] = useState([]);
  const sBusinessTypeConfig = gdsconfigformslave.find(
    item => item.bVisible && item.sName === "sBusinessType"
  );
  let sButtonEnabled = "[]";
  if (sBusinessTypeConfig) {
    sButtonEnabled = sBusinessTypeConfig.sButtonEnabled;
  }

  useEffect(
    () => {
      const rules = commonUtils.convertStrToObj(sButtonEnabled, []);
      let iIndex = -1;
      try {
        iIndex = rules.findIndex(
          item =>
            item.condition[0].bFilterName === "sBusinessType" &&
            item.condition[0].bFilterValue === masterData.sBusinessType
        );
      } catch (error) {}
      if (iIndex !== -1) {
        const { hideColumn } = rules[iIndex];
        setHideTabList(hideColumn);
      } else {
        setHideTabList([]);
      }
    },
    [masterData.sBusinessType]
  );

  // TabPane排序
  const tabRef = useRef(null);
  useEffect(() => {
    if (tabRef.current) {
      const oNavList = tabRef.current.querySelector(".ant-tabs-nav-list");
      if (oNavList) {
        const tabs = Array.from(oNavList.children);
        tabs.sort((a, b) => {
          const keyA = a.getAttribute("data-node-key") || 999;
          const keyB = b.getAttribute("data-node-key") || 999;
          return keyA < keyB ? -1 : keyA > keyB ? 1 : 0;
        });
        oNavList.innerHTML = "";
        tabs.forEach(tab => oNavList.appendChild(tab));
      }
    }
  }, []);

  return (
    <Col span={iColValue} order={slaveChildOrder}>
      {/* {bGyps && (
        <Row>
          <Col span={24}>
            <ProcessCardComponent {...props} slaveName={tableName} />
            <ProcessCardBtnsComponent {...props} />
          </Col>
        </Row>
      )} */}
      <Row>
        <Col span={24} ref={tabRef}>
          <Tabs
            tabBarStyle={{ margin: "4px 0 0 0" }}
            tabBarExtraContent={
              bSgps
                ? {
                    left: (
                      <div
                        style={{
                          position: "absolute",
                          left: 140,
                          top: 0,
                          zIndex: 1
                        }}
                      >
                        <ProcessCardComponent
                          {...props}
                          slaveName={tableName}
                        />
                      </div>
                    )
                  }
                : bWzps
                  ? {
                      left: (
                        <div
                          style={{
                            position: "absolute",
                            left: 300,
                            top: 0,
                            zIndex: 1
                          }}
                        >
                          {/* <Button>物料清单</Button>
                          <Button>需求运算</Button>
                          <Button>排除运算</Button>
                          <Button>清除占料</Button>
                          <Button>生成清购</Button>
                          <Button>评审备注</Button>
                          <Button>标准Bom</Button>
                          <Button>导出</Button>
                          <Button>备料单</Button> */}
                        </div>
                      )
                    }
                  : bGyps
                    ? {
                        left: (
                          <div
                            style={{
                              position: "absolute",
                              right: 0,
                              top: 0,
                              zIndex: 1
                            }}
                          >
                            {/* {currentProductCardId !== "preVersion" && (
                              <Button>PBOM</Button>
                            )}
                            {currentProductCardId === "preVersion" && (
                              <Button>传工单</Button>
                            )} */}
                          </div>
                        )
                      }
                    : null
            }
          >
            {tablePropsList.map((tableProps, index) => {
              const tabInfo = tableProps.config.showName;
              if (
                (hideTabList &&
                hideTabList.length &&
                hideTabList.includes(tabInfo)) || (tableProps.config.showName.includes('_hide'))
              ) {
                return "";
              }
              /* 根据config 解析数据 */
              const arr =
                tableProps.config &&
                tableProps.config.sGrd &&
                tableProps.config.sGrd.split("_"); /* slave5_1_1 */
              const firstTable = arr[0]; /* 第二层：物资评审 - 物料信息  */
              return (
                <>
                  <TabPane tab={tabInfo} key={index * 10}>
                    {tableProps.headerColumn.length !== 0 && (
                      <Row style={{ background: "#FFF" }} className="scrollInfo">
                        <Col
                          flex="auto"
                          className={styles.costomTabBillTable}
                          style={{ width: 100 }}
                        >
                          <StaticEditTable {...tableProps} />
                        </Col>
                        {bPgps && (
                          <MemoListComponent
                            {...props}
                            tableName={slaveChildNameArr[index]}
                          />
                        )}
                      </Row>
                    )}
                    <CommonViewTableComponent
                      {...props}
                      tableName={slaveChildNameArr[index]}
                      viewTableOrder={5}
                    />
                    <CommonViewDragableComponent
                      {...props}
                      tableName={slaveChildNameArr[index]}
                    />
                    {bWzps && (
                      <div
                        style={{ display:'flex', flexDirection:'row', justifyContent:'flex-end' }}
                      >
                        <DoubleRightOutlined
                          rotate={props.wzPackup ? 90 : -90}
                          // rotate={expended ? -90 : 90}
                          onClick={() => {
                            props.onSaveState({wzPackup: !props.wzPackup});
                          }}
                        />
                      </div>
                    )}
                    {!props.wzPackup && tableProps.sChildTableName && (
                      <>
                        <GrandChildTableComponent
                          {...props}
                          tableName={slaveChildNameArr[index]}
                          sChildTableName={tableProps.sChildTableName}
                          bGyps={bGyps}
                        />
                      </>
                    )}
                    {bPgps &&
                      !tableProps.headerColumn.length && (
                        <div
                          style={{
                            position: "absolute",
                            right: 0,
                            top: -29,
                            zIndex: 1
                          }}
                        >
                          <Button
                            disabled={!props.enabled}
                            onClick={() => {
                              handleBtnExtract(
                                props,
                                "",
                                firstTable,
                                true
                              ); /* slave5_0  slave5 */
                            }}
                          >
                            提取全部
                          </Button>
                        </div>
                      )}
                  </TabPane>
                  {getCommonViewTableComponentExtra({
                    ...props,
                    tableName: slaveChildNameArr[index]
                  })}
                </>
              );
            })}
          </Tabs>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <CommonViewDragableComponent {...props} tableName={tableName} />
        </Col>
      </Row>
    </Col>
  );
};

// 工序参数展示
const CommonViewDragableComponent = props => {
  const { tableName, currentProductTechnologyVer, currentProductCardId, slaveData, slaveSelectedRowKeys, slave0Child1Data:controlData } = props;
  const { [`${tableName}Config`]: config } = props;
  // 是否工艺卡
  const bGyk =
    config.showName &&
    (config.showName.includes("工艺卡") ||
      config.showName.includes("印品工艺") ||
      config.showName.includes("BOM&BOP"));

  const bWl = config.showName &&
    (config.showName.includes("物料信息"));
  if (bWl) {
    const materialsInfoArr = Object.keys(props).filter(
      key =>
        key &&
        key.includes("Config") &&
        commonUtils.isNotEmptyObject(props[key]) &&
        props[key].sTbName === "salsalesordermaterials" &&
        (props[key].showName === "工序物料" || props[key].showName === "全部材料")
    );
    useEffect(() => {
      if (!materialsInfoArr.length) {
        handleGetTableData(props, "materials");
      }
    }, []);
  }
  if(commonUtils.isNotEmptyArr(controlData)) {
    let sProductNo = '';
    let sBomId = '';
    if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys) && commonUtils.isNotEmptyArr(slaveData)) {
      const iIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys[0]);
      sProductNo = iIndex >-1 ? slaveData[iIndex].sProductNo : '';
      sBomId = iIndex >-1 ? slaveData[iIndex].sBomId : '';
    }
    const controlFilterData = controlData
      .filter(controlItem => {
        const sCombinedMemoArr = JSON.parse(controlItem.sCombinedMemo);
        const sCombinedMemoFilterArr = sCombinedMemoArr.filter(item => item.dCombineQty > 0 && item.sProductNo === sProductNo);
        return controlItem.sProductCardId === sBomId &&
          // controlItem.sProductTechnologyVer === currentProductTechnologyVer &&
          commonUtils.isNotEmptyArr(sCombinedMemoFilterArr)
        }
      );
    _this.controlFilterData = controlFilterData;
  } else {
    _this.controlFilterData = [];
  }

  if (!bGyk) {
    return "";
  }
  // 获取部件表格（印品基本资料）
  let partsTableName;
  const slaveNameArr = Object.keys(props).filter(
    key =>
      key &&
      key.includes("Config") &&
      commonUtils.isNotEmptyObject(props[key]) &&
      props[key].sTbName === "salsalesordercontrol" &&
      (props[key].showName === "印品基本资料" ||
        props[key].showName === "合格率评审")
  );

  if (slaveNameArr.length) {
    partsTableName = slaveNameArr[0].split("Config")[0];
  }

  useEffect(() => {
    if (!slaveNameArr.length) {
      handleGetTableData(props, "control");
    }
  }, []);

  // 获取工序表格（工艺评审）
  let processTableName;
  const slaveNameArr1 = Object.keys(props).filter(
    key =>
      key &&
      key.includes("Config") &&
      commonUtils.isNotEmptyObject(props[key]) &&
      props[key].sTbName === "salsalesorderprocess" &&
      props[key].showName === "工艺评审"
  );

  if (slaveNameArr1.length) {
    processTableName = slaveNameArr1[0].split("Config")[0];
  }
  const bProcessHeight = 'calc(16vh)';

  // 获取材料表格（工序物料/全部材料）
  let materialsTableName;
  const slaveNameArr2 = Object.keys(props).filter(
    key =>
      key &&
      key.includes("Config") &&
      commonUtils.isNotEmptyObject(props[key]) &&
      props[key].sTbName === "salsalesordermaterials" &&
      (props[key].showName === "工序物料" || props[key].showName === "全部材料")
  );

  if (slaveNameArr2.length) {
    materialsTableName = slaveNameArr2[0].split("Config")[0];
  }

  useEffect(() => {
    if (!slaveNameArr2.length) {
      handleGetTableData(props, "materials");
    }
  }, []);

  const tabChange = (e) => {
    props.onActiveKey(e);
  };

  const materialsFilterNew = (data, type) => {
    const { materialsData:materials0Data, slave0SelectedRowKeys:processSelectedRowKeys, slave0Data:processData,
      slave0Child1SelectedRowKeys:controlSelectedRowKeys, slave0Child1Data:controlData, currentProductTechnologyVer,
      currentProductCardId,
    } = props;
    let oriData = materials0Data || []; // commonUtils.isNotEmptyArr(data.data) ? data.data : [];
    let res = [];
    let newData = [];
    let processRow = {};
    let controlRow = {};

    if(commonUtils.isNotEmptyArr(controlData) && commonUtils.isNotEmptyArr(controlSelectedRowKeys)){ /* 没有工序选中行 则不进行数据过滤 */
      const iIndex = controlData.findIndex(item => controlSelectedRowKeys.includes(item.sId));
      if(iIndex > -1) {
        controlRow = controlData[iIndex];
      }
    }

    if(commonUtils.isNotEmptyArr(processData) && commonUtils.isNotEmptyArr(processSelectedRowKeys)){ /* 没有工序选中行 则不进行数据过滤 */
      const iIndex = processData.findIndex(item => processSelectedRowKeys.includes(item.sId));
      if(iIndex > -1) {
        processRow = processData[iIndex];
      }
    }
    if (type === 'materials') {
      /* 根据工序表选中行的部件id +工序id 过滤全部材料数据 */
      if(commonUtils.isNotEmptyObject(processRow) && commonUtils.isNotEmptyObject(controlRow)){
        const filterData = oriData.filter(item => item.sControlId === processRow.sControlId && item.sProcessId === processRow.sProcessId  && item.sProcessTbId === processRow.sId
          && commonUtils.isEmptyObject(item.sParentMaterialsId) && (item.sNons !== "非标") );
        if (commonUtils.isNotEmptyArr(filterData)) {
          newData = filterData.filter(item => ((commonUtils.isEmptyObject(item.sInkBOMId) && commonUtils.isEmptyObject(item.sInkBOMsSlaveId) && commonUtils.isEmptyObject(item.sInkBOMsMaterialsId)) ||
            ( (commonUtils.isNotEmptyObject(item.sInkBOMsMaterialsId) && commonUtils.isNotEmptyObject(item.sInkBOMId) && commonUtils.isNotEmptyObject(item.sInkBOMsSlaveId)))) && (item.sNons !== "非标")
          );
        }
        res = newData;
      } else if(commonUtils.isNotEmptyObject(controlRow)){
        const filterData = oriData.filter(item => item.sControlId === controlRow.sId && commonUtils.isEmptyObject(item.sParentMaterialsId) && (item.sNons !== "非标") );
        if (commonUtils.isNotEmptyArr(filterData)) {
          newData = filterData.filter(item => ((commonUtils.isEmptyObject(item.sInkBOMId) && commonUtils.isEmptyObject(item.sInkBOMsSlaveId) && commonUtils.isEmptyObject(item.sInkBOMsMaterialsId)) ||
            ( (commonUtils.isNotEmptyObject(item.sInkBOMsMaterialsId) && commonUtils.isNotEmptyObject(item.sInkBOMId) && commonUtils.isNotEmptyObject(item.sInkBOMsSlaveId)))) && (item.sNons !== "非标")
          );
        }
        res = newData;
      } else {
        res = commonUtils.isEmptyArr(oriData) ? oriData : oriData.filter(item => commonUtils.isEmptyObject(item.sParentMaterialsId)
        && item.sProductCardId === currentProductCardId && (item.sNons !== "非标"));
        res = commonUtils.isEmptyArr(oriData) ? oriData : res.filter(item => ((commonUtils.isEmptyObject(item.sInkBOMId) && commonUtils.isEmptyObject(item.sInkBOMsSlaveId) && commonUtils.isEmptyObject(item.sInkBOMsMaterialsId)) ||
          ( (commonUtils.isNotEmptyObject(item.sInkBOMsMaterialsId) && commonUtils.isNotEmptyObject(item.sInkBOMId) && commonUtils.isNotEmptyObject(item.sInkBOMsSlaveId)))  && (item.sNons !== "非标"))
        );
      }

    } else if (type === 'materials1' || type === 'materials2'  || type === 'materials3') {
      /* 过滤后的 materials0Data */
      let materials0FilterData = [];
      if(commonUtils.isNotEmptyObject(processRow) && commonUtils.isNotEmptyArr(materials0Data)){
        const filterData = materials0Data.filter(item => (item.sControlId === processRow.sControlId && item.sProcessId === processRow.sProcessId && item.sProcessTbId === processRow.sId && commonUtils.isEmptyObject(item.sParentMaterialsId)) && (item.sNons !== "非标"));
        if (commonUtils.isNotEmptyArr(filterData)) {
          materials0FilterData = filterData;
        }
      }else if(commonUtils.isNotEmptyObject(controlRow) && commonUtils.isNotEmptyArr(materials0Data)){
        const filterData = materials0Data.filter(item => item.sControlId === controlRow.sId && commonUtils.isEmptyObject(item.sParentMaterialsId) && (item.sNons !== "非标"));
        if (commonUtils.isNotEmptyArr(filterData)) {
          materials0FilterData = filterData;
        }
      }
      if (commonUtils.isNotEmptyArr(materials0FilterData)) {
        materials0FilterData = materials0FilterData.filter(item => item.sProductCardId === currentProductCardId && (item.sNons !== "非标"));
        const config = data.config;
        const sSqlCondition = config ? config.sSqlCondition : 'materials0.sBclassifyName.油墨';
        if (sSqlCondition) {
          let targetTbName = sSqlCondition.split('.')[0]; /* 1.表名 control  */
          if(commonUtils.isEmptyObject(targetTbName)) {
            targetTbName = 'materials0';
          }
          let filteredValue = sSqlCondition.split('.')[1]; /* 2.解析filterValue: controlSelectedRowKeys */
          let sParentKey = sSqlCondition.split('.')[2]; /* 2.解析本身表对应的值,如控制表筛选材料表 则材料表的sControlId = 控制表的controlSelectedRowKeys[0] */
          /* 双重条件 */
          if(commonUtils.isEmptyObject(targetTbName)){
            if(type === 'materials1') { /* materials0.sBclassifyName.油墨 */
              filteredValue = 'sBclassifyName';
              sParentKey = '油墨';
            } else if(type ==='materials2') { /* materials0.sBclassifyName.电化铝 */
              filteredValue = 'sBclassifyName';
              sParentKey = '电化铝';
            }
          }
          if (targetTbName === 'materials0') {
            let filterData = [];
            if(type === 'materials1') { /* 油墨 */
              filterData = materials0FilterData.filter(item => sParentKey && sParentKey.includes(item[filteredValue]) &&
                (
                  (commonUtils.isNotEmptyObject(item.sInkBOMsMaterialsId) && commonUtils.isNotEmptyObject(item.sInkBOMId) && commonUtils.isNotEmptyObject(item.sInkBOMsSlaveId)) ||
                  (commonUtils.isEmptyObject(item.sInkBOMsMaterialsId) && commonUtils.isEmptyObject(item.sInkBOMId) && commonUtils.isEmptyObject(item.sInkBOMsSlaveId))
                )
                && (item.sNons !== "非标"));
            }else if(type === 'materials2') {  /* 电化铝 */
              filterData = materials0FilterData.filter(item => sParentKey && sParentKey.includes(item[filteredValue]) && commonUtils.isEmptyObject(item.sParentMaterialsId) && (item.sNons !== "非标"));
            } else if(type === 'materials3') {  /* 包材 */
              filterData = materials0FilterData.filter(item => sParentKey && sParentKey.includes(item[filteredValue]) && commonUtils.isEmptyObject(item.sParentMaterialsId) && (item.sNons !== "非标"));
            }
            newData = filterData;
          }
        }

      }
      res = newData;
    } else if( type === 'materials1Child') { /* 过滤油墨子集 */
      const { materialsData, materials1SelectedRowKeys } = props;
      let materials1Row ={}; /* 油墨子级 */
      if(commonUtils.isNotEmptyArr(materialsData) && commonUtils.isNotEmptyArr(materials1SelectedRowKeys)){ /* 没有工序选中行 则不进行数据过滤 */
        const iIndex = materialsData.findIndex(item => materials1SelectedRowKeys.includes(item.sId));
        if(iIndex > -1) {
          materials1Row = materials0Data[iIndex];
        }
        res = materialsData.filter(item => item.sInkFatherMaterialsTbId === materials1Row.sId);
        // res = materialsData.filter(item => commonUtils.isNotEmptyObject(item.sInkBOMId) && item.sInkBOMId === materials1Row.sInkBOMId
        //   &&  commonUtils.isNotEmptyObject(item.sInkBOMsSlaveId) && item.sInkBOMsSlaveId === materials1Row.sInkBOMsSlaveId &&
        //   commonUtils.isEmptyObject(item.sInkBOMsMaterialsId) && item.sProductCardId === currentProductCardId);
      }
    } else if(type ==='materialsChild') { /* 全部材料 过滤替代料 */
      const { materialsSelectedRowKeys:materials0SelectedRowKeys } = props;
      let materials0Row ={};
      if(commonUtils.isNotEmptyArr(materials0Data) && commonUtils.isNotEmptyArr(materials0SelectedRowKeys)){ /* 没有工序选中行 则不进行数据过滤 */
        const iIndex = materials0Data.findIndex(item => materials0SelectedRowKeys.includes(item.sId));
        if(iIndex > -1) {
          materials0Row = materials0Data[iIndex];
        }
      }
      if(commonUtils.isNotEmptyObject(materials0Row)) {  /* 根据工序过滤所有替代料 */
        if(commonUtils.isNotEmptyObject(materials0Row.sAluminumBomId)) { /* 电化铝替代料过滤, 相同编号的共享替代料信息 */
          res = oriData.filter(item => item.sParentMaterialsId === materials0Row.sId ||
            ( commonUtils.isNotEmptyObject(item.sParentMaterialsId) &&
              commonUtils.isNotEmptyObject(item.sMaterialsNo) &&
              item.sProductCardId === currentProductCardId  &&
              item.sMaterialsNo1 === materials0Row.sMaterialsNo) );
        } else {
          res = oriData.filter(item => item.sParentMaterialsId === materials0Row.sId && item.sProductCardId === currentProductCardId);
        }
      } else if(commonUtils.isNotEmptyObject(processRow)) { /* 根据工序过滤所有替代料 */
        res = oriData.filter(item => item.sProcessId === processRow.sProcessId && item.sProcessTbId === processRow.sId
          && commonUtils.isNotEmptyObject(item.sParentMaterialsId) && item.sProductCardId === currentProductCardId);
      } else if(commonUtils.isNotEmptyObject(controlRow)){
        res = oriData.filter(item => item.sControlId=== controlRow.sId && commonUtils.isNotEmptyObject(item.sParentMaterialsId) && item.sProductCardId === currentProductCardId);
      } else {
        res =  oriData.filter(item =>  commonUtils.isNotEmptyObject(item.sParentMaterialsId) && item.sProductCardId === currentProductCardId); /* 没有选中 则展示全部替代料 */
      }

    } else {
      res = oriData;
    }
    return res;
  }

  /* 处理可折叠页签标题名称 */
  const panelExtra = (type) => {
    let str = '';
    /* 根据materials找到其组所有配置头 */
    const { formData } = props;

    let radioConfigArr = [];
    if(commonUtils.isNotEmptyArr(formData)) {
      radioConfigArr =  formData.filter(item => commonUtils.isNotEmptyObject(item.sGrd) && item.sGrd.includes(type) && item.sGrd.split('_').length <3 );}

    if (type === 'materials') {
      str = (
        <div>
            <Radio.Group defaultValue={props.colTabKey} onChange={e => tabChange(e.target.value)}>
            {
              radioConfigArr.map((child, index) => {
                const radioTitle =  child.showName;
                const radioValue =  index + 2 + 10;
                return(
                  <Radio value={radioValue}>{radioTitle}</Radio>
                )
              })
            }
          </Radio.Group>
        </div>
      )
    }
    return str;
  }

  const bMaterialsHeight = props.gongxuPackup ? 'calc(28vh + 60px)' : 'calc(12vh)';
  const { materialsInfoList, materialsChildInfoList } = props;
  /* 循环展示材料表 */
  const materialsTablePropsList = {};
  if (commonUtils.isNotEmptyArr(materialsInfoList)) {
    materialsInfoList.forEach((item, index) => {
      const tableNameProps = index === 0 ? `materialsTable` : `materialsTable${index}`;
      const tableName = index === 0 ? `materials` : `materials${index}`;
      materialsTablePropsList[`${tableNameProps}Props`] = {
        ...commonBusiness.getTableTypes(tableName, props),
        // tableBelone: 'list',
        data: materialsFilterNew(commonBusiness.getTableTypes(tableName, props), tableName, false),
        tableProps: {
          setAdd,
          setCopy,
          setDelete,
          // AutoTableHeight: bMaterialsHeight,
        },
        fixedHeight: bMaterialsHeight
      };
    });
  }

 /* 展示材料表 子从表 */
  const materialsChildTablePropsList = {};
  if (commonUtils.isNotEmptyArr(materialsChildInfoList)) {
    materialsChildInfoList.forEach((item, index) => {
      materialsChildTablePropsList[`${item}TableProps`] = {
        ...commonBusiness.getTableTypes(`${item}`, props),
        data: materialsFilterNew(commonBusiness.getTableTypes(item, props), item, false),
        // tableBelone: 'list',
        tableProps: {
          setAdd,
          setCopy,
          setDelete,
          // AutoTableHeight: bMaterialsHeight,
        },
        onDrag: props.onDrag,
        fixedHeight: bMaterialsHeight
      };
      if(item === 'materialsChild') {
        if(commonUtils.isNotEmptyArr(slaveData)) {
          if(commonUtils.isEmptyObject(slaveData[0].sMainProductTechnologyId) && commonUtils.isEmptyObject(slaveData[0].sSpareProductTechnologyId) ) {
            materialsChildTablePropsList[`${item}TableProps`].bLimitOperate = true;
          }
        }
      }
    });
  }

  // 获取改版处表格（改版处）
  const slaveNameArr3 = Object.keys(props).filter(
    key =>
      key &&
      key.includes("Config") &&
      commonUtils.isNotEmptyObject(props[key]) &&
      props[key].sTbName === "salsalesorderrevision" &&
      props[key].showName === "改版处"
  );

  useEffect(() => {
    if (!slaveNameArr3.length) {
      handleGetTableData(props, "revision");
    }
  }, []);

  const getDividerTitle = title => {
    return (
      <>
        <div>
          <div
            style={{
              borderTop: "1px solid rgba(0, 0, 0, 0.3)",
              width: 15,
              position: "absolute",
              left: 0,
              top: 12
            }}
          />
          <div
            style={{
              width: 4,
              height: 4,
              background: "black",
              position: "absolute",
              top: 10,
              left: 26,
              borderRadius: "50%"
            }}
          />
        </div>
        <span style={{ padding: "0 0 0 36px" }}>{title}</span>
        {
          title === "工序信息" ? (
            <div
              style={{ position: "absolute", top: 0, right: 0 }}
            >
              <DoubleRightOutlined
                rotate={ props.gongxuPackup ? 90 : -90 }
                // rotate={expended ? -90 : 90}
                onClick={() => {
                  props.onSaveState({ gongxuPackup: !props.gongxuPackup });
                }}
              />
            </div>
          ) : ""
        }
        {
          title === "材料信息" ? (
            <div
              style={{ position: "absolute", top: 0, right: 0 }}
            >
              <DoubleRightOutlined
                rotate={ props.materialsPackup ? 90 : -90 }
                onClick={() => {
                  props.onSaveState({ materialsPackup: !props.materialsPackup });
                }}
              />
            </div>
          ) : ""
        }
      </>
    );
  };

  return (
    <Row className={styles.costomTabBillDivider}>
      {partsTableName && (
        <Col span={24}>
          <Divider
            orientation="left"
            orientationMargin={0}
            style={{
              margin: 0,
              borderTopColor: "rgba(0, 0, 0, 0.3)"
            }}
          >
            {getDividerTitle("部件信息")}
          </Divider>
          <SlaveTableComponent
            {...props}
            tableName={partsTableName}
            salveIColValue={24}
            bAutoHeight={true}
          />
        </Col>
      )}
      {processTableName && (
        <Col span={24} id={props.processTableId}>
          <Divider
            orientation="left"
            orientationMargin={0}
            style={{
              margin: 0,
              borderTopColor: "rgba(0, 0, 0, 0.3)",
              paddingRight: 20
            }}
          >
            {getDividerTitle("工序信息")}
          </Divider>
          {
            !props.gongxuPackup ? (
              <SlaveTableComponent
                {...props}
                tableName={processTableName}
                salveIColValue={24}
                bAutoHeight={true}
                AutoTableHeight={bProcessHeight}
              />
            ) : ""
          }
        </Col>
      )}
      {materialsTableName && (
        <Col
          span={24}
          // className={styles.costomTabBillAutoHeight}
        >
          <Divider
            orientation="left"
            orientationMargin={0}
            style={{
              margin: 0,
              borderTopColor: "rgba(0, 0, 0, 0.3)"
            }}
          >
            {getDividerTitle("材料信息")}
          </Divider>
          {/*按照印品PBOM材料方式展示材料信息*/}
          {
            !props.materialsPackup ?
              <Collapse defaultActiveKey={props.activeKey} className="custom-collapse">
                <Panel collapsible="header"
                       // header={(<RightOutlined style={{fontSize: '11px', transition: 'ease 0.3s', transform: `rotate(${(commonUtils.isNotEmptyObject(props.activeKey) && props.activeKey.indexOf('1') !== -1)? '90deg' : '0deg'})`}} />)}
                       showArrow={true}
                       extra={panelExtra('materials')}
                       key="1"
                >
                  { props.materialsInfoList?.map((item, index) => {
                    let num = 12 + index;
                    const tablePropsName = index === 0 ? `materialsTableProps` : `materialsTable${index}Props`;
                    const materialsOtherPropsType = materialsTablePropsList[tablePropsName];
                    let sWidth = '100%';
                    let sRightWidth = '100%';
                    /* 全部材料 是否可排序 */
                    let bMaterialsSort = false;
                    bMaterialsSort = commonUtils.isNotEmptyObject(materialsOtherPropsType) && commonUtils.isNotEmptyObject(materialsOtherPropsType.config) &&
                    commonUtils.isNotEmptyArr(materialsOtherPropsType.config.gdsconfigformslave) &&
                    commonUtils.isNotEmptyArr(materialsOtherPropsType.config.gdsconfigformslave.filter(item => item.sControlName === 'handleSort' && item.bVisible)) ? true : false ;

                    /* 找到子级 左右列 */
                    let materialsChildTableProps ={};
                    let materialsChildTableTitle = '子表记录';
                    if(commonUtils.isNotEmptyArr(materialsChildInfoList)) {
                      const iIndex = materialsChildInfoList.findIndex(child => child.includes(item) );
                      if(iIndex > -1) {
                        materialsChildTableProps =  materialsChildTablePropsList[`${item}ChildTableProps`];
                        sWidth = '58%';
                        sRightWidth = '42%';
                        materialsChildTableTitle = commonUtils.isNotEmptyObject(materialsChildTableProps) &&  commonUtils.isNotEmptyObject(materialsChildTableProps.config) ?  materialsChildTableProps.config.sChinese : '';
                      } else {
                        sWidth = '100%';
                      }
                    }else {
                      sWidth = '100%';
                    }
                    const { currentPane = {} } = props.app;
                    const { title = "" } = currentPane;
                    const bGyps = title.indexOf("订单工艺评审") !== -1;
                    return (
                      props.colTabKey === num &&
                      <div className='dlhStyle1'>
                        <div style={{ width: sWidth, position: 'relative' }}>
                          {
                            index === 0 && bGyps ?
                              <div className={styles.costomTabDelAll}>
                                <Space>
                                  <Button type='primary' disabled={!props.enabled || commonUtils.isEmptyArr(materialsOtherPropsType.data)} onClick={props.onDelAllMaterials.bind(this, materialsOtherPropsType.data, true)}>删除选中</Button>
                                  <Button type='primary' disabled={!props.enabled || commonUtils.isEmptyArr(materialsOtherPropsType.data)} onClick={props.onDelAllMaterials.bind(this, materialsOtherPropsType.data, false)}>删除全部</Button>
                                </Space>
                              </div>
                              : ""
                          }
                          <StaticEditTable {...materialsOtherPropsType} setOpterationColumn="Y"  />
                        </div>
                        {
                          commonUtils.isNotEmptyObject(materialsChildTableProps)?
                            <div style={{width:sRightWidth, position: 'relative'}}>
                              <div className="fixChildTitle"> <Radio.Group defaultValue={1} >
                                <Radio value={1}>{materialsChildTableTitle}</Radio>
                              </Radio.Group> </div>
                              <StaticEditTable {...materialsChildTableProps} setOpterationColumn="Y"  noVlist selfTableHeight={82}/>
                            </div>
                            : ''
                        }
                      </div>
                    )
                  }) }
                </Panel>
              </Collapse> : ''

          }
        </Col>
      )}
    </Row>
  );
};

// 额外加载表格
const handleGetTableData = async (props, sGrdName) => {
  const { formData, currentId, queryConfigArr, dataRelationJson } = props;
  const sId = currentId !== undefined ? currentId : "";
  const config = formData.find(item => item.sGrd === sGrdName);
  if (config) {
    const name = sGrdName;
    let addState = {};
    if (config.sSqlStr !== "noQuery") {
      const conditonValues = props.onGetSqlConditionValues(config);
      addState =
        (await props.handleGetDataSet({
          name,
          configData: config,
          condition: {
            sSqlCondition: { ...conditonValues, sParentId: sId }
          },
          isWait: true
        })) || {};
    } else {
      const { sTbName } = config;
      const iIndex = queryConfigArr.findIndex(
        item => item[1].sTbName === sTbName
      );
      if (iIndex !== -1) {
        addState.dataRelationJson = {
          ...dataRelationJson,
          [name]: queryConfigArr[iIndex][0]
        };
      }
    }
    addState[`${name}Config`] = config;
    addState[`${name}Column`] = commonFunc.getHeaderConfig(config);
    addState[`${name}PageSize`] =
      commonUtils.isNotEmptyNumber(config.iPageSize) && config.iPageSize !== 0
        ? config.iPageSize
        : commonConfig.pageSize;

    props.onSaveState(addState);
  }
};

// 工序参数展示
const CommonViewDragableComponentBak = props => {
  const { tableName } = props;
  const { [`${tableName}Config`]: config } = props;
  const { gdsconfigformslave } = config;
  const iIndex = gdsconfigformslave.findIndex(
    item => item.sControlName === "sProcessParamType"
  );
  if (iIndex === -1) {
    return "";
  }
  const { sDefault } = gdsconfigformslave[iIndex];
  const sParamList = ["sProcess", "sReport", "sWorkOrder", "sNorm", "sTest"];
  if (!sParamList.includes(sDefault)) {
    return "";
  }

  const slaveName = tableName.split("Child")[0];
  const commonViewDragableProps = {
    ...props,
    hideTabsNav: true,
    sParamData: [
      {
        sParamType: sDefault,
        sParamName: "参数"
      }
    ],
    tableName: slaveName
  };
  return <CommonViewDragable {...commonViewDragableProps} />;
};

// 工艺卡部件选择
const ProcessCardComponent = props => {
  const slaveNameArr = Object.keys(props).filter(
    key =>
      key &&
      key.includes("Config") &&
      commonUtils.isNotEmptyObject(props[key]) &&
      props[key].sTbName === "salsalesorderprocess" &&
      props[key].sSqlStr &&
      props[key].sSqlStr !== "noTable" &&
      props[key].sSqlStr !== "noQuery"
  );

  let slaveName = "";
  if (slaveNameArr.length) {
    slaveName = slaveNameArr[0].split("Config")[0];
  }

  if (!slaveName) {
    return "";
  }

  const childIndex = new Array(10).fill("").findIndex((_, index) => {
    const config = props[`${slaveName}Child${index}Config`];
    return (
      commonUtils.isNotEmptyObject(config) &&
      config.sTbName === "salsalesordercontrol"
    );
  });

  let tableName = "control";
  if (
    commonUtils.isNotEmptyObject(props[`${slaveName}Child${childIndex}Config`])
  ) {
    tableName = `${slaveName}Child${childIndex}`;
  }

  const { [`${tableName}Data`]: tableData = [], slaveData = [] } = props;

  const [productCardOptions, setProductCardOptions] = useState([]);
  const [partsOptions, setPartsOptions] = useState([]);

  const [productCardValue, setProductCardValue] = useState("");
  const [partsValue, setPartsValue] = useState("");

  useEffect(() => {
    if (!commonUtils.isNotEmptyArr(tableData)) {
      handleGetTableData(props, tableName);
    }
  }, []);

  // 获取工艺卡
  useEffect(
    () => {
      const { slaveData, bReset } = props;
      // 默认或者processCardUpdate为ture时才更新
      if (props.processCardUpdate || props.processCardUpdate === undefined) {
        /* 将tableData中 currentSelectType 根据从表对应 */
        if (
          commonUtils.isNotEmptyArr(tableData) &&
          commonUtils.isNotEmptyArr(productCardOptions)
        ) {
          tableData.forEach((item, index) => {
            const {
              sProductCardId,
              sProductCardNo,
              sProductTechnologyVer
            } = item;
            let { currentSelectType } = item;
            if (commonUtils.isEmptyObject(currentSelectType)) {
              /* 首次加载 找不到选择项目 */
              if (commonUtils.isNotEmptyArr(slaveData)) {
                if (item.sProductCardId === slaveData[0].sBomId) {
                  currentSelectType = slaveData[0].sSelectType;
                } else {
                  currentSelectType =
                    slaveData[0].sSelectType === "mainVersion"
                      ? "preVersion"
                      : "mainVersion";
                }
              } else {
                currentSelectType = "mainVersion";
              }
            }
            /*
            循环控制表,填充工艺落线数据
             */
            const iIndex = productCardOptions.findIndex(
              key => key.value && key.value.includes(currentSelectType)
            );
            if (iIndex > -1) {
              let sVer = commonUtils.isEmptyObject(sProductTechnologyVer)
                ? "已载入"
                : sProductTechnologyVer;
              const obj = {
                label:
                  currentSelectType === "mainVersion"
                    ? `首选版本：${sVer}`
                    : `备选版本：${sVer}`,
                value: `${currentSelectType},${sProductCardId},${sVer}`,
                data: item
              };
              productCardOptions[iIndex] = {
                ...productCardOptions[iIndex],
                ...obj
              };
            }
          });
        }

        if (!productCardOptions.length) {
          productCardOptions.push({
            label: "首选版本：无",
            value: "mainVersion",
            data: {}
          });

          productCardOptions.push({
            label: "备选版本：无",
            value: "preVersion",
            data: {}
          });
        } else {
          props.onSaveState({ processCardUpdate: false });
        }

        /* 取消回置Radio */
        if(bReset){
          if(tableData !== undefined && productCardOptions.length ){
            productCardOptions.forEach((item, index) => {
              const iIndex = tableData.findIndex(row => item.value.includes(row.sProductCardId) );
              if(iIndex === -1) {
                const obj ={
                  label: index === 0 ? "首选版本：无" : '备选版本：无',
                  value: index === 0 ? "mainVersion": 'preVersion',
                  data: {}
                };
                productCardOptions[index] = {...productCardOptions[index], ...obj}
              }

            })
          }
        }


        if (
          commonUtils.isNotEmptyArr(tableData) &&
          tableData.length === 1 &&
          productCardOptions.length === 1
        ) {
          productCardOptions.push({
            label:
              tableData[0].currentSelectType === "mainVersion"
                ? "备选版本：无"
                : "首选版本：无",
            value:
              tableData[0].currentSelectType === "mainVersion"
                ? "preVersion"
                : "mainVersion",
            data: {}
          });
        }

        /*
          根据从表的sSelectType， 定位当前版本在哪个Radio
       */
        if (productCardOptions.length) {
          let iType = 0;
          // const { currentSelectType:currentSelectType1 } = props;
          if (commonUtils.isNotEmptyArr(slaveData)) {
            const currentSelectType = slaveData[0].sSelectType;
            const iIndex = productCardOptions.findIndex(
              item => item.value && item.value.includes(currentSelectType)
            );
            if (iIndex === -1) {
              iType = 0;
            } else {
              iType = iIndex;
            }
          }
          setProductCardOptions(productCardOptions);
          setProductCardValue(productCardOptions[iType].value);
        }
      }
    },
    [JSON.stringify(tableData), JSON.stringify(slaveData)]
  );

  // 获取部件
  useEffect(
    () => {
      if (productCardValue) {
        const partsOptions = tableData
          .filter(item => item.sProductCardId === productCardValue)
          .map(item => ({ label: item.sPartsName, value: item.sId }));
        if (partsOptions.length) {
          setPartsOptions(partsOptions);
          setPartsValue(partsOptions[0].value);
        } else if (productCardValue === "preVersion") {
          setPartsOptions([{ label: "备选版本", value: "preVersion" }]);
          setPartsValue("preVersion");
        }
      }
    },
    [productCardValue]
  );

  // 当工艺卡id变化时候，保存到props中
  useEffect(
    () => {
      if (productCardValue) {
        const { slaveData, slaveSelectedRowKey, slave0Child1Data: controlData } = props;
        let {
          [`${tableName}SelectedRowKeys`]: controlSelectedRowKeys = []
        } = props;
        const [
          version,
          sProductCardId,
          sProductTechnologyVer
        ] = productCardValue.split(",");
        const currentSelectType = version;
        // 要保存到props的数据
        // 。。。
        /* 将首选、备选方案选择的值 更新到从表中 */
        // if (commonUtils.isNotEmptyArr(slaveData)) {
        //   const addState = {};
        //   addState.sBomId = sProductCardId;
        //   addState.sProductTechnologyVer = sProductTechnologyVer;
        //   addState.sSelectType = version;
        //   if (version === "mainVersion") {
        //     addState.sMainProductTechnologyId = sProductCardId;
        //   } else if (version === "preVersion") {
        //     addState.sSpareProductTechnologyId = sProductCardId;
        //   }
        //   addState.handleType = commonUtils.isEmpty(slaveData[0].handleType)
        //     ? "update"
        //     : slaveData[0].handleType;
        //   slaveData[0] = { ...slaveData[0], ...addState };
        // }
        /* 将切换的版本存到slave中 */
        let slaveRow = {};
        let iSlaveIndex = -1;
        if(commonUtils.isNotEmptyArr(slaveData)) {
          if(commonUtils.isNotEmptyArr(slaveSelectedRowKey)) {
            iSlaveIndex = slaveData.findIndex(item => slaveSelectedRowKey.includes(item.sId));
          } else {
            iSlaveIndex = 0;
          }
        }
        if(iSlaveIndex > -1) {
          slaveRow = slaveData[iSlaveIndex];
        }
        const addState = {};
        if(commonUtils.isNotEmptyObject(slaveRow)) {
          addState.sBomId = sProductCardId;
          addState.sProductTechnologyVer = sProductTechnologyVer;
          addState.sSelectType = currentSelectType;
          addState.handleType = commonUtils.isEmpty(slaveRow.handleType) ? 'update' : slaveRow.handleType;
          if (currentSelectType === "mainVersion") {
            addState.sMainProductTechnologyId = sProductCardId;
          } else if (currentSelectType === "preVersion") {
            addState.sSpareProductTechnologyId = sProductCardId;
          }
          slaveData[iSlaveIndex] ={...slaveRow, ...addState};
        }

        /* 切换时 默认控制表属于该版本的第一条 */
        if (commonUtils.isNotEmptyArr(controlData)) {
          /* 找当前版本下的第一条部件 作为默认部件 */
          if (
            commonUtils.isNotEmptyArr(slaveData) &&
            commonUtils.isNotEmptyArr(controlData)
          ) {
            // const controlFilterData = controlData
            //   .filter(controlItem => {
            //       const sCombinedMemoArr = JSON.parse(controlItem.sCombinedMemo);
            //       const sCombinedMemoFilterArr = sCombinedMemoArr.filter(item => item.dCombineQty > 0 && item.sProductNo === slaveRow.sProductNo);
            //       return controlItem.sProductCardId === currentProductCardId &&
            //         controlItem.sProductTechnologyVer === currentProductTechnologyVer &&
            //         commonUtils.isNotEmptyArr(sCombinedMemoFilterArr)
            //     }
            //   );

            const iIndex = controlData.findIndex(
              controlItem => {
                const sCombinedMemoArr = JSON.parse(controlItem.sCombinedMemo);
                const sCombinedMemoFilterArr = sCombinedMemoArr.filter(item => item.dCombineQty > 0 && item.sProductNo === slaveRow.sProductNo);
                return controlItem.sProductCardId === slaveData[0].sBomId &&
                  commonUtils.isNotEmptyArr(sCombinedMemoFilterArr)
              }
            );
            if (iIndex > -1) {
              controlSelectedRowKeys = [controlData[iIndex].sId];
            } else {
              controlSelectedRowKeys = [];
            }
          }
        }

        if(commonUtils.isNotEmptyArr(_this.controlFilterData) && commonUtils.isNotEmptyArr(controlSelectedRowKeys)) {
          _this.controlFilterData = controlData.filter(item  => controlSelectedRowKeys.includes(item.sId));
        }

        props.onSaveState({
          currentProductCardId: sProductCardId,
          currentSelectType,
          currentProductTechnologyVer: sProductTechnologyVer,
          slave0Child1SelectedRowKeys: [],
          slaveData,
          [`${tableName}SelectedRowKeys`]: controlSelectedRowKeys
        });
      }
    },
    [productCardValue]
  );

  // 当部件id变化时候，保存到props中
  useEffect(
    () => {
      if (partsValue) {
        /* 首先版本、备选版本类型 + 版本ID 过滤部件条件 */
        const currentSelectType =
          partsValue === "preVersion" ? "preVersion" : " mainVersion";
        const currentVersionInfo = currentSelectType + "-" + partsValue;
        props.onSaveState({
          currentPartsId: partsValue,
          currentSelectType,
          currentVersionInfo
        });
      }
    },
    [partsValue]
  );

  const onChange = (type, { target: { value } }) => {
    if (type === "0") {
      setProductCardValue(value);
    } else if (type === "1") {
      setPartsValue(value);
    }
  };

  // 判断是否显示选择POM、选择传票按钮
  const { slave0Config = {}, masterData = {}, slave0Child1Data: controlData, enabled, slaveConfig,sModelsId  } = props;
  const { gdsconfigformslave = [] } = slave0Config;
  const bHasChoosePOM = gdsconfigformslave.some(
    item => item.sControlName && item.sControlName.includes("_choosePBOM")
  );
  const bHasChooseTicket = gdsconfigformslave.some(
    item => item.sControlName && item.sControlName.includes("_chooseTicket")
  );

  /* 拆分工单后 工艺路线置灰 */
  let bDisabledRoute = false;
  if(commonUtils.isNotEmptyArr(masterData)) {
    bDisabledRoute = masterData.bSplit || masterData.sBusinessType === 'ZS01-5';
    if(!bDisabledRoute){
      if(!masterData.bSplit && masterData.bPD){
        if(commonUtils.isNotEmptyArr(controlData) && controlData.length === 1) {
          bDisabledRoute = true;
        }

      }
    }
  }

  /* 是否显示合版数量区域 */
  let bShowCombineArea = false;
  if(slaveConfig && slaveConfig.gdsconfigformslave) {
    bShowCombineArea = slaveConfig.gdsconfigformslave.findIndex(item => item.sName ==='dCombinedQty') > -1
  }
  let bShowRoute = true;
  if(sModelsId === '12710101117172075846130') {
    bShowRoute = false
  }

  return (
    <div className={styles.costomTabBillProcessCard}>
      {productCardValue && bShowRoute ? (
        <div className="radioDiv">
          <span
          // style={{
          //   fontSize: 16,
          //   fontWeight: "bold"
          // }}
          >
            工艺路线：
          </span>
          <Radio.Group
            options={productCardOptions}
            onChange={onChange.bind(this, "0")}
            value={productCardValue}
            disabled={bDisabledRoute}
            // optionType="button"
            // buttonStyle="solid"
          />
          {/* <Radio.Group
              options={partsOptions}
              onChange={onChange.bind(this, "1")}
              value={partsValue}
            /> */}
          {/* {productCardValue === "preVersion" && ( */}
          {
            bShowCombineArea ?
              <div style={{ width:'38%' }} >
                {
                  getCommonViewTableComponentCombine({
                    ...props,
                    tableName: 'slave'
                  })
                }
              </div> : false
          }

          <Space
            size={3}
            style={{
              position: "absolute",
              top: 0,
              right: 20
            }}
          >
            {bHasChoosePOM && (
              <Button
                disabled={!props.enabled}
                onClick={() => {
                  handleOpenModal(props, "choosePBOM");
                }}
              >
                选择PBOM
              </Button>
            )}
            {bHasChooseTicket && (
              <Button
                disabled={!props.enabled}
                onClick={() => {
                  handleOpenModal(props, "chooseTicket");
                }}
              >
                选择传票
              </Button>
            )}
          </Space>
          {/* )} */}
        </div>
      ) : (
        ""
      )}
    </div>
  );
};

// 工艺评审按钮
const ProcessCardBtnsComponent = props => {
  return "";
  return (
    <div style={{ width: "100%", height: 30, lineHeight: "30px" }}>
      <Button>标准</Button>
      <Button>传票</Button>
      <Button>向上</Button>
      <Button>向下</Button>
      <Button>新增</Button>
      <Button>插入</Button>
      <Button>删除</Button>
      <Button>修改</Button>
      <Button>保存</Button>
      <Button>取消</Button>
      <Button>烫金</Button>
    </div>
  );
};

// 孙表格
const GrandChildTableComponent = props => {
  const {
    addStateMap,
    tableName,
    sChildTableName,
    formData,
    currentId,
    bGyps,
    sModelsType
  } = props;
  const sId = currentId !== undefined ? currentId : "";
  const config = formData.find(item => item.sGrd === sChildTableName);
  const name = `${tableName}Child0`;

  /* 替代料单独处理 */
  const configRm = formData.find(item => item.showName === '印品PBOM替代料'); /* 更换材料 */
  const nameRm = `${tableName}Child1`;

  /* 更换材料单独处理 */
  const configCm = formData.find(item => item.showName === '更换材料'); /* 更换材料 */
  const nameCm = `${tableName}Child2`;

  const bWzps =
    props[`${tableName}Config`].showName.indexOf("物资评审") !== -1 ||
    props[`${tableName}Config`].showName.indexOf("物料信息") !== -1;

  // 没有配置或者， 返回空
  if (commonUtils.isEmptyObject(config)) {
    return "";
  }
  if (commonUtils.isEmptyObject(configRm) && bWzps) {
    return "";
  }
  if (commonUtils.isEmptyObject(configCm) && bWzps) {
    return "";
  }
  useEffect(() => {
    const tempFun = async () => {
      let addState = {};
      if (config.sSqlStr !== "noQuery") {
        const conditonValues = props.onGetSqlConditionValues(config);
        addState =
          (await props.handleGetDataSet({
            name,
            configData: config,
            condition: { sSqlCondition: { ...conditonValues, sParentId: sId } },
            isWait: true
          })) || {};
      }
      addState[`${name}Config`] = config;
      addState[`${name}Column`] = commonFunc.getHeaderConfig(config);
      addState[`${name}PageSize`] =
        commonUtils.isNotEmptyNumber(config.iPageSize) && config.iPageSize !== 0
          ? config.iPageSize
          : commonConfig.pageSize;
      if(commonUtils.isNotEmptyObject(configCm)) { /* 特殊处理更新材料信息 */
        addState[`${nameCm}Config`] = configCm;
        addState[`${nameCm}Column`] = commonFunc.getHeaderConfig(configCm);
        addState[`${nameCm}PageSize`] =
          commonUtils.isNotEmptyNumber(configCm.iPageSize) && configCm.iPageSize !== 0
            ? configCm.iPageSize
            : commonConfig.pageSize;
      }
      if(commonUtils.isNotEmptyObject(configRm)) { /* 特殊处理更新材料信息 */
        addState[`${nameRm}Config`] = configRm;
        addState[`${nameRm}Column`] = commonFunc.getHeaderConfig(configRm);
        addState[`${nameRm}PageSize`] =
          commonUtils.isNotEmptyNumber(configRm.iPageSize) && configRm.iPageSize !== 0
            ? configRm.iPageSize
            : configRm.pageSize;
      }
      props.onSaveState(addState);
    }
    tempFun();
  }, []);

  const { bGrdVisible } = config;
  const { gdsconfigformslave } = config;
  const bHasDividerArea = gdsconfigformslave.some(
    item => item.sControlName && item.sControlName.includes("DividerArea")
  );
  /* 根据config 解析数据 */
  const arr = config.sGrd && config.sGrd.split("_"); /* slave5_1_1 */
  const firstTable = arr[0]; /* 第一层：品管评审 */
  let secondTable = ""; /* 第二层 ：客户投诉 */
  if (arr.length > 1) {
    const secondFlag = Number(arr[1]) - 1;
    secondTable = firstTable + "_" + secondFlag;
  }

  /* 控制提取上次信息按钮状态 */
  let disabled = false;
  if (firstTable) {
    const { [`${firstTable}Config`]: firstTableConfig } = props;
    const filterConfig = commonUtils.isNotEmptyObject(firstTableConfig)
      ? firstTableConfig.gdsconfigformslave.filter(
          item => item.sControlName && item.sControlName.includes("BtnExtract")
        )
      : {};
    if (commonUtils.isNotEmptyArr(filterConfig)) {
      disabled = filterConfig[0].bReadonly;
    }
    if(!disabled) {
      disabled = !props.enabled;
    }
  }
  if (!bGrdVisible) {
    // 表单形式展示
    return (
      <>
        <div
          style={{
            position: "relative",
            width: "100%",
            height: 30,
            lineHeight: "30px",
            textAlign: "center",
            backgroundColor: "#FFF",
            fontSize: 18,
            fontWeight: "bold"
          }}
        >
          {!bHasDividerArea && <span>{config.showName}</span>}
          <Button
            disabled={disabled}
            onClick={() => {
              handleBtnExtract(
                props,
                secondTable,
                firstTable,
                false
              ); /* slave5_0  slave5 */
            }}
            style={{
              position: "absolute",
              right: 0,
              top: 0
            }}
          >
            提取上次信息
          </Button>
        </div>
        <CommonViewTableComponent
          {...props}
          tableName={name}
          viewTableOrder={5}
        />
      </>
    );
  }

  const otherTableProps = {};
  // if (config.sSqlStr === "noQuery") {
  //   const tempConfigName = Object.keys(addStateMap).find(
  //     key =>
  //       addStateMap[key].sSqlStr !== "noQuery" &&
  //       addStateMap[key].sTbName === config.sTbName
  //   );

  //   if (tempConfigName) {
  //     const tempName = tempConfigName.split("Config")[0];
  //     otherTableProps.name = tempName;
  //     otherTableProps.data = props[`${tempName}Data`];
  //   }
  // }



  const bRm = commonUtils.isNotEmptyObject(configRm)
  const bCm = commonUtils.isNotEmptyObject(configCm); /* 是否展示更换材料页签 */

  // 是否展示操作按钮
  let bShowOperate = true;
  if (commonUtils.isNotEmptyObject(config)) {
    const condition1 = config.sTbName === "sysbillcheckresult";
    const condition2 = config.gdsconfigformslave.some(
      item =>
        item.sControlName && item.sControlName.includes("setNoCommonOperate")
    );
    if (condition1 || condition2) {
      bShowOperate = false;
    }
  }

  const isSpecialType = (['12710101117055564119120'].includes(props.sModelsId) ||
    props?.slave3Child0Child2Config?.gdsconfigformslave?.find(i => i && ['sTypeShowAll'].includes(i.sControlName)));

  /* 根据主料过滤替代料数据 */
  const dataMaterialsFilter = (tableProps, type) => {
    let oriData = commonUtils.isNotEmptyArr(tableProps.data)
      ? tableProps.data
      : [];
    let config = commonUtils.isNotEmptyArr(tableProps.config)
      ? tableProps.config
      : [];
    let res = [];
    const bReplaceMaterials =
      config.showName === "印品PBOM替代料"; /* 根据首选、备选过滤合格率评审数据 */
    if (type === "slave3Child0Child1" && bReplaceMaterials) {
      /* 替代料数据 */
      /* 主料数据是slave3Child0 */
      const {
        materialsData: materailsData = [],
        slave3Child0SelectedRowKeys:  materialsSelecteRowKeys
      } = props;
      let materialsFilterData =  materailsData;
      if(commonUtils.isNotEmptyArr(_this.controlFilterData)) {
        materialsFilterData = materailsData.filter(item => item.sControlId === _this.controlFilterData[0].sId && (item.sNons !== "非标"));
      }
      const iPIndex = commonUtils.isNotEmptyArr(materailsData) && commonUtils.isNotEmptyArr(materialsSelecteRowKeys)
        ? materailsData.findIndex(item =>
            materialsSelecteRowKeys.includes(item.sId)
          )
        : -1;
      let materialsRow = {};
      // if (iPIndex > -1) {
      //   materialsRow = materailsData[iPIndex];
      // }
      let filterData = [];
      if (commonUtils.isNotEmptyArr(materailsData)) {
        if(commonUtils.isEmptyObject(materialsRow)) {
          filterData = materialsFilterData.filter(item => commonUtils.isNotEmptyObject(item.sParentMaterialsId)  && item.sNons !=='替代料');
        } else {
          filterData = materialsFilterData.filter(item => commonUtils.isNotEmptyObject(item.sParentMaterialsId) && item.sParentMaterialsId === materialsRow.sId && item.sNons !=='替代料');
        }

      }
      res = filterData;
    } else if (type === "slave3Child0Child2" && config.showName ==='更换材料') {
      /* 替代料数据 */
      /* 主料数据是slave3Child0 */
      const {
        materialsData: materailsData,
        slave3Child0SelectedRowKeys:  materialsSelecteRowKeys
      } = props;
      const iPIndex = commonUtils.isNotEmptyArr(materailsData) && commonUtils.isNotEmptyArr(materialsSelecteRowKeys)
        ? materailsData.findIndex(item =>
          materialsSelecteRowKeys.includes(item.sId)
        )
        : -1;
      let materialsRow = {};
      if (iPIndex > -1) {
        materialsRow = materailsData[iPIndex];
      }
      let filterData = [];
      if (commonUtils.isNotEmptyArr(materailsData)) {
        if(commonUtils.isEmptyObject(materialsRow) || isSpecialType) {
          filterData = materailsData.filter(item => commonUtils.isNotEmptyObject(item.sParentMaterialsId)  && item.sNons ==='替代料');
        }else {
          filterData = materailsData.filter(
            item =>
              commonUtils.isNotEmptyObject(item.sParentMaterialsId) &&
              item.sParentMaterialsId === materialsRow.sId && item.sNons ==='替代料'
          );
        }

      }
      const { slave3Child0SelectedRowKeys = [] } = props;
      filterData.forEach(item => {
        if (item.sParentMaterialsId && item.sParentMaterialsId === slave3Child0SelectedRowKeys[0]) {
          item.costomRowColor = "yellow";
        } else {
          delete item.costomRowColor;
        }
      })
      res = filterData;
    } else {
      res = oriData;
    }
    return res;
  };

  const listType = "commonMultiList";
  const setOpterationColumn =
    sModelsType !== "cost/cosexpenseshare" &&
    sModelsType !== listType &&
    bShowOperate
      ? "Y"
      : "";

  const baseProps = commonBusiness.getTableTypes(name, props);
  const tableProps = {
    ...baseProps,
    ...otherTableProps,
    setOpterationColumn,
    // filteredValue: props.slave3Child0InfoSelectedRowKeys,
    // onFilterData: props.onFilterData,
    tableProps: {
      setAdd,
      setCopy,
      setCopyAll,
      setDelete,
      onChange: props.onTitleChange.bind(this, tableName)
      // AutoTableHeight: 300
    },
    // fixedHeight: "calc(100% - 250px)"
    fixedHeight: props.onGetHeight(
      (baseProps.headerColumn.some(item => item.title.includes("-"))
        ? 375
        : 345) + (bGyps ? 20 : 0)
    )
  };

  const cmBaseProps = commonBusiness.getTableTypes(nameCm, props);

  const cmProps = {
    ...cmBaseProps,
    ...otherTableProps,
    setOpterationColumn,
    // filteredValue: props.slave3Child0InfoSelectedRowKeys,
    // onFilterData: props.onFilterData,
    tableProps: {
      setAdd,
      setCopy,
      setCopyAll,
      setDelete,
      onChange: props.onTitleChange.bind(this, tableName),
      AutoTableHeight: 300
    },
    data: dataMaterialsFilter(cmBaseProps, nameCm),
    sParentSelectedRowKeys: commonUtils.isNotEmptyArr(props.slave3Child0SelectedRowKeys) ? props.slave3Child0SelectedRowKeys[0] : undefined,
    // fixedHeight: "calc(100% - 250px)"
  };

  if (!isSpecialType) {
    cmProps.fixedHeight = props.onGetHeight(
      (baseProps.headerColumn.some(item => item.title.includes("-"))
        ? 375
        : 345) + (bGyps ? 20 : 0)
    );
    delete cmProps.tableProps.AutoTableHeight;
  }

  const rmBaseProps = commonBusiness.getTableTypes(nameRm, props);

  const rmProps = {
    ...rmBaseProps,
    ...otherTableProps,
    setOpterationColumn,
    // filteredValue: props.slave3Child0InfoSelectedRowKeys,
    // onFilterData: props.onFilterData,
    tableProps: {
      setAdd,
      setCopy,
      setCopyAll,
      setDelete,
      onChange: props.onTitleChange.bind(this, tableName)
      // AutoTableHeight: 300
    },
    data: dataMaterialsFilter(rmBaseProps, nameRm),
    sParentSelectedRowKeys: commonUtils.isNotEmptyArr(props.slave3Child0SelectedRowKeys) ? props.slave3Child0SelectedRowKeys[0] : undefined,
    // fixedHeight: "calc(100% - 250px)"
    fixedHeight: props.onGetHeight(
      (baseProps.headerColumn.some(item => item.title.includes("-"))
        ? 375
        : 345) + (bGyps ? 20 : 0)
    )
  };
  /* 树形展示 */
  const bTree =
    config.sTableType === "single" &&
    commonUtils.isNotEmptyArr(tableProps.data) &&
    tableProps.data.some(rowData =>
      commonUtils.isNotEmptyObject(rowData.sFatherSlaveId)
    );

  if (bTree) {
    tableProps.data = commonUtils.genTreeByArr(
      tableProps.data,
      "sId",
      "sFatherSlaveId"
    );
  }

  if (bWzps) {
    tableProps.fixedHeight = props.onGetHeight(80, true);
  }

  return (
    <Tabs
      // tabBarExtraContent={
      //   bWzps
      //     ? {
      //         left: (
      //           <div
      //             style={{
      //               position: "absolute",
      //               left: 140,
      //               top: 0,
      //               zIndex: 1
      //             }}
      //           >
      //             <Button
      //               disabled={!props.enabled}
      //               onClick={() => {
      //                 handleReplaceMaterials(
      //                   props,
      //                   tableName
      //                 ); /* 替换物料 上下数据集进行颠倒 */
      //               }}
      //             >
      //               替换物料
      //             </Button>
      //           </div>
      //         )
      //       }
      //     : null
      // }
    >
      <TabPane tab={config.showName} key="1">
        <StaticEditTable {...tableProps} />
      </TabPane>
      {
        bRm ?
          <TabPane tab={configRm.showName} key="2">
            <StaticEditTable {...rmProps} />
          </TabPane> : ''
      }
      {
        bCm ?
          <TabPane tab={configCm.showName} key="3">
            <StaticEditTable {...cmProps} />
          </TabPane> : ''
      }

    </Tabs>
  );
};

// 备注列表
const MemoListComponent = props => {
  const { tableName, enabled } = props;
  const {
    [`${tableName}Config`]: config,
    [`${tableName}Data`]: data = [],
    [`${tableName}SelectedRowKeys`]: selectedRowKeys = []
  } = props;

  const configData = config.gdsconfigformslave.filter(
    item =>
      item.sName &&
      item.sName.indexOf("Memo") !== -1 &&
      item.bVisible &&
      item.sControlName === "extraMemo"
  );

  const selectedDataIndex = data.findIndex(item =>
    selectedRowKeys.includes(item.sId)
  );
  const selectedData = selectedDataIndex !== -1 ? data[selectedDataIndex] : {};

  if (!configData.length) {
    return "";
  }

  const { sName, iTag } = configData[0];
  const [listValue, setListValue] = useState([]);

  useEffect(
    () => {
      if (selectedDataIndex === -1) {
        return;
      }

      const fieldValue = selectedData[sName] || "";
      const listValueNew = fieldValue.split("\n\n");
      setListValue(listValueNew);
    },
    [selectedRowKeys[0], selectedData[sName]]
  );

  const timer = useRef(null);
  useEffect(
    () => {
      if (selectedDataIndex === -1) {
        return;
      }
      clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        const dataRow = listValue.reduce((result, item, index) => {
          result += item;
          if (index < listValue.length - 1) {
            result += "\n\n";
          }
          return result;
        }, "");
        const newData = [...data];
        newData[selectedDataIndex][sName] = dataRow;
        props.onSaveState({
          [`${tableName}Data`]: newData
        });
      }, 500);
    },
    [listValue]
  );

  return (
    <Col flex="250px" className="xlyMemoList">
      <List
        itemLayout="horizontal"
        header={
          <div style={{ color: "rgba(0,0,0,.85)", fontWeight: "bold" }}>
            {configData[0].showName}
          </div>
        }
        dataSource={listValue}
        style={{
          paddingLeft: 10,
          paddingRight: 10,
          maxHeight: props.onGetHeight(55),
          overflow: "auto"
        }}
        renderItem={(item, index) => {
          const bDisabled = !enabled || iTag === 1;
          const inputProps = {
            value: item,
            disabled: bDisabled,
            // disabled: false,
            readOnly: configData[0].readOnly,
            autoSize: { minRows: 1, maxRows: 100 },
            onChange: ({ target: { value } }) => {
              setListValue(prev => {
                const newList = [...prev];
                newList[index] = value;
                return newList;
              });
            }
          };
          return (
            <List.Item style={{ display: "flex" }}>
              <Input.TextArea {...inputProps} />
              {index
                ? !bDisabled && (
                    <Button
                      type="text"
                      icon={<DeleteOutlined />}
                      onClick={() => {
                        setListValue(prev => {
                          const newList = [...prev];
                          newList.splice(index, 1);
                          return newList;
                        });
                      }}
                    />
                  )
                : !bDisabled && (
                    <Button
                      type="text"
                      icon={<PlusOutlined />}
                      onClick={() => {
                        setListValue(prev => [...prev, ""]);
                      }}
                    />
                  )}
            </List.Item>
          );
        }}
      />
    </Col>
  );
};

// 弹窗1
const ModalComponent1 = props => {
  const { app } = props;
  let processCardSearchResult = commonFunc.showMessage(
    app.commonConst,
    "processCardSearchResult"
  ); /* 复制从工艺卡查询结果 */
  let productProcessInfoType = {};
  let productProcessInfoConfig = {};

  if (commonUtils.isNotEmptyObject(props.productProcessInfoChooseData)) {
    const productProcessInfoCopyFromKey = props.productProcessInfoCopyFromKey;
    const iIndex = props.slave0Config.gdsconfigformslave.findIndex(
      item => item.sControlName === productProcessInfoCopyFromKey
    );
    if (iIndex > -1) {
      productProcessInfoConfig = props.slave0Config.gdsconfigformslave[iIndex];
      processCardSearchResult =
        commonUtils.isNotEmptyObject(productProcessInfoConfig) &&
        commonUtils.isNotEmptyObject(productProcessInfoConfig.sActiveName)
          ? productProcessInfoConfig.sActiveName
          : processCardSearchResult;
    }
    productProcessInfoType = {
      app: {
        ...props.app,
        currentPane: {
          name: "productProcessInfo",
          config: productProcessInfoConfig,
          conditonValues: props.getSqlCondition(productProcessInfoConfig),
          title: props.productProcessInfoChooseData.sMenuName,
          route: props.productProcessInfoChooseData.sName,
          formId: props.productProcessInfoChooseData.sId,
          key: props.sModelsId + props.productProcessInfoChooseData.sId,
          sModelsType: props.productProcessInfoChooseData.sModelType,
          select: props.onSelect,
          selectCancel: props.onSelectCancel
        }
      },
      dispatch: props.dispatch,
      content: props.content,
      id: new Date().getTime().toString()
    };
  }
  return props.productProcessInfoChooseVisible ? (
    <AntdDraggableModal
      width={1200}
      title={processCardSearchResult}
      visible={props.productProcessInfoChooseVisible}
      onCancel={props.onCancelProductProcessInfoChooseModal}
      footer={null}
    >
      <CommonListSelect {...productProcessInfoType} />
    </AntdDraggableModal>
  ) : (
    ""
  );
};

// 弹窗2
const ModalComponent2 = props => {
  const { app } = props;
  /* 显示导入报错信息 */
  let importExcelProps = {};
  let importExcelTitle = commonUtils.isNotEmptyObject(
    commonFunc.showMessage(app.commonConst, "processCardSearchResult")
  )
    ? commonFunc.showMessage(app.commonConst, "importErrorMsg")
    : "导入校验信息"; /* 导入校验信息 */
  if (commonUtils.isNotEmptyObject(props)) {
    importExcelProps = {
      ...commonBusiness.getTableTypes("import", props),
      ...props.onGetTableTypesNew("import"),
      tableProps: {
        pagination: null,
        AutoTableHeight: 400
      },
      // data: bSingleTree && commonUtils.isNotEmptyArr(slaveData) ?  commonUtils.genTreeByArr(slaveData, 'sId', 'sFatherSlaveId') : slaveData,
      onDelRow: props.onDelRow,
      onKeyDown: props.onKeyDown,
      onContextMenu: props.onContextMenu,
      masterData: props.masterData, // 为通用弹窗提供主表数据(孟总需求：产品新增需要带上客户信息)
      tableBelone: "list"
    };
  }
  return props.showImportErrorVisible ? (
    <AntdDraggableModal
      width={1480}
      zIndex={1000}
      title={importExcelTitle}
      bodyStyle={{ height: "450px" }}
      visible={props.showImportErrorVisible}
      onCancel={props.handleCancelModal.bind(this, "showImportErrorVisible")}
      onOk={props.handleCancelModal.bind(this, "showImportErrorVisible")}
      onSaveState={props.onSaveState}
      // footer={null}
    >
      <StaticEditTable {...importExcelProps} />
    </AntdDraggableModal>
  ) : (
    ""
  );
};

// 工序弹窗
const ModalComponent3 = props => {
  const { app, sParamsModalVisible, sModelsType } = props;
  if (!sParamsModalVisible) {
    return "";
  }
  const sProcessParams = commonFunc.showMessage(
    app.commonConst,
    "sProcessParams"
  ); /* 选择工艺参数标题 */

  const sParamProps = {
    ...commonBusiness.getTableTypes("sParam", props),
    tableProps: {
      rowKey: "sId",
      onChange: props.onTitleChange,
      sModelsType,
      AutoTableHeight: 350
    },
    bRowClick: true
  };

  const onParamsOk = () => {
    const {
      processTableName,
      [`${processTableName}Data`]: processData,
      processRecord,
      enabled,
      sParamModalType
    } = props;
    let { sParamData } = props;
    if (enabled) {
      if (
        commonUtils.isNotEmptyArr(processData) &&
        commonUtils.isNotEmptyObject(processRecord)
      ) {
        const processSelectDataIndex = processData.findIndex(
          item => item.sId === processRecord.sId
        );
        if (processSelectDataIndex > -1) {
          if (commonUtils.isNotEmptyArr(sParamData)) {
            let sParamJsonData = "";
            // const sParamSeletedData = sParamData.filter(item => item.bSelfCbx);
            const iFaceIndex = sParamData.findIndex(
              item => item.sParamKey === "sParam1000"
            );
            const iColorIndex = sParamData.findIndex(
              item => item.sParamKey === "sParam1001"
            );
            if (iFaceIndex > -1) {
              let iFaceValue = "";
              const iFaceObj = sParamData[iFaceIndex];
              if (commonUtils.isNotEmptyObject(iFaceObj)) {
                if (iFaceObj.sParamValue === "正面") {
                  iFaceValue = 0;
                } else if (iFaceObj.sParamValue === "反面") {
                  iFaceValue = 1;
                } else if (iFaceObj.sParamValue === "双面") {
                  iFaceValue = 2;
                }
              }
              processData[processSelectDataIndex].iFace = iFaceValue;
              sParamData.splice(iFaceIndex, 1);
            }
            /* 移除 印面、色序配置 */
            if (iColorIndex > -1) {
              const iColorObj = sParamData[iColorIndex];
              sParamData.splice(iFaceIndex, 1);
            }
            /* 移除色序，单双面 */
            const sParamSeletedData = sParamData;
            if (commonUtils.isNotEmptyObject(sParamSeletedData)) {
              sParamJsonData = JSON.stringify(sParamSeletedData);
            }
            let { handleType } = processData[processSelectDataIndex];
            handleType = commonUtils.isEmpty(handleType)
              ? "update"
              : handleType;
            if (sParamModalType === "sQuo") {
              /* 报价参数点击确定 */
              processData[processSelectDataIndex].sQuoParams = sParamJsonData;
            } else {
              /* 工单参数点击确定 */
              processData[processSelectDataIndex].sParams = sParamJsonData;
            }
            processData[processSelectDataIndex].handleType = handleType;
          }
        }
      }
      props.onSaveState({
        [`${processTableName}Data`]: processData,
        sParamsModalVisible: false
      });
    } else {
      props.onSaveState({
        sParamsModalVisible: false
      });
    }
  };

  const onCancelModal = () => {
    props.onSaveState({
      sParamsModalVisible: false
    });
  };

  return (
    <AntdDraggableModal
      width="920px"
      className="paramModal"
      title={sProcessParams}
      visible={sParamsModalVisible}
      onOk={onParamsOk}
      onCancel={onCancelModal}
    >
      <div className="xly-bill-list">
        <StaticEditTable {...sParamProps} footer="hidden" noVlist />
      </div>
    </AntdDraggableModal>
  );
};

//
const ModalComponent4 = props => {
  const {
    sisColorChooseVisible,
    app,
    sTabId,
    sModelsId
  } = props;
  if (!sisColorChooseVisible) {
    return "";
  }
  const processTableName = 'slave0';

  const pane = app.panes.filter(paneTmp => paneTmp.key === sTabId)[0];
  const setSisColorTitle = commonFunc.showMessage(
    app.commonConst,
    "setSisColor"
  ); /* 选择颜色标题 */

  /* 选择基础颜色 */
  const handleSelectSisColor = async (name, selectConfig, selectData) => {
    const {
      enabled,
      [`${processTableName}Data`]: processData,
      processSelectedRowId,
      paramSelectedRowId,
      sParamData
    } = props;
    if (enabled && commonUtils.isNotEmptyObject(processSelectedRowId)) {
      let sColorSerialMemoStr = "";
      const jsonData = [];
      if (commonUtils.isNotEmptyArr(selectData)) {
        selectData.forEach(item => {
          const { sId, sName, dColor, CreateDate, sMakePerson } = item;
          const jsonObj = {};
          jsonObj.sId = sId;
          jsonObj.sName = sName; /* 名称 */
          jsonObj.dColor = dColor; /* 色序 */
          jsonObj.CreateDate = CreateDate;
          jsonObj.sMakePerson = sMakePerson;
          sColorSerialMemoStr += `${sName}-${dColor},`;
          jsonData.push(jsonObj);
        });
        if (commonUtils.isNotEmptyObject(sColorSerialMemoStr)) {
          sColorSerialMemoStr = commonUtils.isNotEmptyArr(jsonData)
            ? JSON.stringify(jsonData)
            : ""; /* JSON对象转换为字符串存放到合版信息中 */
        }
      }
      const iIndex = processData.findIndex(
        item => item.sId === processSelectedRowId
      );
      if (iIndex > -1) {
        const addState = {};
        let { handleType } = processData[iIndex];
        handleType = commonUtils.isEmpty(handleType) ? "update" : handleType;
        addState.handleType = handleType;
        addState.sColorSerialMemo = sColorSerialMemoStr;
        processData[iIndex] = { ...processData[iIndex], ...addState };
      }

      if (
        commonUtils.isNotEmptyArr(sParamData) &&
        commonUtils.isNotEmptyObject(paramSelectedRowId)
      ) {
        const iParamIndex = sParamData.findIndex(
          item => item.sId === paramSelectedRowId
        );
        if (iParamIndex > -1) {
          const addState = {};
          // let { handleType } = sParamData[iIndex];
          // handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType;
          // addState.handleType = handleType;
          addState.sParamValue = sColorSerialMemoStr;
          sParamData[iParamIndex] = { ...sParamData[iParamIndex], ...addState };
        }
      }
    }
    props.resetSColorSerialMemo();
    props.onSaveState({
      sisColorChooseVisible: false
    });
  };

  const onCancelModal = () => {
    props.onSaveState({
      sisColorChooseVisible: false
    });
    props.resetSColorSerialMemo();
  };

  let chooseColorsConfig = {};
  let searchColorsType = {};
  const config = props[`${processTableName}Config`];
  if (
    commonUtils.isNotEmptyObject(props) &&
    commonUtils.isNotEmptyObject(config)
  ) {
    const iIndex = config.gdsconfigformslave.findIndex(
      item => item.sControlName === "BtnChooseColors"
    );
    if (iIndex > -1) {
      chooseColorsConfig = config.gdsconfigformslave[iIndex];
    }
    searchColorsType = {
      app: {
        ...app,
        currentPane: {
          name: "sisColor",
          config: chooseColorsConfig,
          conditonValues: props.getSqlCondition(chooseColorsConfig),
          title: "选择颜色",
          route: "/indexPage/commonList",
          formRoute: "/indexPage/commonList",
          formId: chooseColorsConfig.sActiveId,
          key: sModelsId + chooseColorsConfig.sId,
          sModelsType: "search/sisColor",
          select: handleSelectSisColor,
          selectCancel: onCancelModal,
          bEdit: props.enabled
        }
      },
      enabled: props.enabled,
      sisColorSelectedData: props.sisColorSelectedData,
      slaveSelectedRowKeys: props.sisColorSelectedRowKeys,
      dispatch: props.dispatch,
      content: props.content,
      id: new Date().getTime().toString()
    };
    searchColorsType.app = {
      ...searchColorsType.app,
      ...props.showCacheData(props.isSColorSerialMemo?.current, props.slave0Data, props.processSelectedRowId) || {},
    };
  }

  return (
    <AntdDraggableModal
      width={1300}
      title={setSisColorTitle}
      visible={pane.notCurrentPane ? false : sisColorChooseVisible}
      onCancel={onCancelModal}
      footer={null}
    >
      <CommonListSelectFlex {...searchColorsType} />
    </AntdDraggableModal>
  );
};

// 工艺参数弹窗
const ModalComponent5 = props => {
  const modalName = "sParamsModalVisible"; // commonParamVisible
  const sProcessParams = "工单参数";
  return props[modalName] ? (
    <Modal
      width="80%"
      className="commonParamDrag"
      title={sProcessParams}
      visible={props[modalName]}
      onCancel={() => {
        props.onSaveState({ [modalName]: false });
      }}
      footer={
        <Button
          type="primary"
          onClick={() => {
            props.onSaveState({ [modalName]: false });
          }}
        >
          确定
        </Button>
      }
    >
      <div>
        <div className='oper'>
          <Button type='primary' onClick={() => { handleBtnParamPage(props, props.processTableId, 'first')}} >首条</Button>
          <Button type='primary' onClick={() => { handleBtnParamPage(props, props.processTableId, 'before')}} >上一条</Button>
          <Button type='primary' onClick={() => { handleBtnParamPage(props, props.processTableId, 'next')}} >下一条</Button>
          <Button type='primary' onClick={() => { handleBtnParamPage(props, props.processTableId, 'last')}} >末条</Button>
        </div>
      {[""].map(() => {
        const commonViewDragableProps = {
          ...props,
          hideTabsNav: true,
          // bSimpleMode: true,
          comparedTableId: props.processTableId,
          sParamData: [
            // {
            //   sParamType: 'sProcess',
            //   sParamName: '工序参数',
            // },
            // {
            //   sParamType: 'sReport',
            //   sParamName: '上报参数'
            // },
            {
              sParamType: "sWorkOrder",
              sParamName: "工单参数"
            }
            // {
            //   sParamType: 'sNorm',
            //   sParamName: '标准书参数'
            // },
            // {
            //   sParamType: 'sTest',
            //   sParamName: '测试参数'
            // }
          ],
          tableName: "slave0"
        };
        return <CommonViewDragable {...commonViewDragableProps} />;
      })}
      </div>
    </Modal>
  ) : (
    ""
  );
};

// 合版信息弹窗
const ModalComponentPack = props => {
  const { app, productCombinationVisible } = props;
  const setProductCombinationTitle = commonFunc.showMessage(app.commonConst, 'setProductCombination');/* 选择合拼产品标题 */
  const packTableProps = {
    ...commonBusiness.getTableTypes('pack', props),
    onKeyDown: props.onKeyDown,
    tableProps: {
      setCopy, setDelete, CalLastWidth: '1150', AutoTableHeight: '300px',
    },
    bRowClick: true,
  };
  return props.productCombinationVisible ? (
    <AntdDraggableModal
      width={1150}
      title={setProductCombinationTitle}
      visible={productCombinationVisible === undefined ? false : productCombinationVisible}
      onCancel={props.onCancelProductCombinationChooseModal}
      onOk={props.onSelectProductCombination}
    >
      <div id="ModalMaterialRemark">
        <div id="packModal" style={{ marginTop: 0, height: '350px', overflowY: 'hidden' }} >
          <StaticEditTable {...packTableProps} footer="hidden" setOpterationColumn="Y" />
        </div>
      </div>
    </AntdDraggableModal>
  ) : (
    ""
  );
};

const ModalComponentMenu = props => {
  const { contextMenuModalVisible } = props;
  return contextMenuModalVisible ? (
    <ContextMenuModal {...props} />
  ) : (
    ""
  );
};

// 按钮弹窗功能
const handleOpenModal = (props, type) => {
  const { masterConfig = {}, slave0Config = {} } = props;
  const { gdsconfigformslave = [] } = masterConfig;
  let iIndex = gdsconfigformslave.findIndex(
    item => item.sControlName && item.sControlName.includes(`_${type}`)
  );
  let obj = {};
  if (type && (type.includes("choosePBOM") || type.includes("chooseTicket"))) {
    iIndex = commonUtils.isNotEmptyObject(slave0Config)
      ? slave0Config.gdsconfigformslave.findIndex(
          item => item.sControlName && item.sControlName.includes(`_${type}`)
        )
      : -1;
    if (iIndex > -1) {
      const {
        showName,
        sActiveId,
        sControlName
      } = slave0Config.gdsconfigformslave[iIndex];
      obj = {
        name: showName,
        copyFromKey: sControlName,
        copyFromSActiveId: sActiveId
      };
    }
  } else {
    if (iIndex !== -1) {
      const { showName, sActiveId, sControlName } = gdsconfigformslave[iIndex];
      const obj = {
        name: showName,
        copyFromKey: sControlName,
        copyFromSActiveId: sActiveId
      };
      props.onCopyFrom(obj);
    }
  }
  if (commonUtils.isNotEmptyObject(obj)) {
    props.onCopyFrom(obj);
  }
  // _this.controlFilterData = null;
};

/* 提取功能 */
const handleBtnExtract = (props, type, pTable, bAll) => {
  /* 上批数据 */
  const { [`${pTable}Config`]: pTableConfig, dataRelationJson, slave5Child5Data } = props;
  let { [`${pTable}Data`]: pTableData, [`${pTable}SelectedRowKeys`]: pTableSelectedRowKeys } = props; /* 上批数据上层数据集 */
  if (commonUtils.isEmpty(pTableData)) {
    pTableData = [];
  }

  let iIndex = 0;
  let iUIndex = 0;
  if (commonUtils.isNotEmptyArr(pTableSelectedRowKeys)) {
    iIndex = pTableData.findIndex(item => item.sId === pTableSelectedRowKeys[0]);
  }

  /* 从父级找到所有的提取配置 */
  if (bAll) {
    /* 提取全部 */
    const filterConfig = commonUtils.isNotEmptyObject(pTableConfig)
      ? pTableConfig.gdsconfigformslave.filter(
        item => item.sControlName && item.sControlName.includes("BtnExtract")
      )
      : {};
    if (commonUtils.isNotEmptyArr(filterConfig)) {
      filterConfig.forEach(item => {
        const sControlName = item.sControlName;
        const type = sControlName.replace("BtnExtract", "").trim();
        const num = type && type.split("_")[1];
        const upType = pTable + "Child" + num + "Child0"; /* 上批对比的表名 */
        const relateName = dataRelationJson[upType];
        let upTableData = props[`${relateName}Data`]; /* 真实存在的数据集 如，slave0Child3Child0真实数据集 取得是slaveData */
        const upTableSelectedRowKeys = props[`${relateName}SelectedRowKeys`];
        if (commonUtils.isEmptyArr(upTableData)) {
          upTableData = [];
        }

        if (commonUtils.isNotEmptyArr(upTableSelectedRowKeys)) {
          iUIndex = upTableData.findIndex(item => item.sId === upTableSelectedRowKeys[0]);
        }

        const singleConfig = [item];
        if (
          commonUtils.isNotEmptyArr(singleConfig) &&
          commonUtils.isNotEmptyArr(upTableData)
        ) {
          const sAssignField = singleConfig[0].sAssignField;
          let tableRow = {};
          tableRow = {
            ...tableRow,
            ...commonFunc.getAssignFieldValue(sAssignField, upTableData[iUIndex])
          }; // 取赋值字段
          if (commonUtils.isNotEmptyArr(pTableData)) {
            const handleType = commonUtils.isEmpty(upTableData[iUIndex].handleType)
              ? "update"
              : upTableData[0].handleType;
            pTableData[iIndex] = { ...pTableData[iIndex], ...tableRow, handleType };
            upTableData[iUIndex] = { ...upTableData[iUIndex], ...tableRow, handleType };
          } else {
            pTableData.push(tableRow);
          }
          slave5Child5Data.forEach((tableDataRow, index) => {
            slave5Child5Data[index] = { ...tableDataRow,
              handleType:  commonUtils.isEmpty(tableDataRow.handleType) ? "update" : tableDataRow.handleType, sMemo: tableDataRow.sUpMemo }
          });
          props.onSaveState({ [`${pTable}Data`]: pTableData, slave5Child5Data });
        }
      });
    }
  } else {
    const num = type && type.split("_")[1];
    const upType = pTable + "Child" + num + "Child0"; /* 上批对比的表名 */
    const relateName = dataRelationJson[upType]; /* 真实表名 */
    let upTableData = props[`${relateName}Data`]; /* 真实存在的数据集 如，slave0Child3Child0真实数据集 取得是slaveData */
    const upTableSelectedRowKeys = props[`${relateName}SelectedRowKeys`];
    if (commonUtils.isEmptyArr(upTableData)) {
      upTableData = [];
    }

    if (commonUtils.isNotEmptyArr(upTableSelectedRowKeys)) {
      iUIndex = upTableData.findIndex(item => item.sId === upTableSelectedRowKeys[0]);
    }
    /* 上批数据到当前数据 */
    const singleConfig = commonUtils.isNotEmptyObject(pTableConfig)
      ? pTableConfig.gdsconfigformslave.filter(
        item =>
          item.sControlName && item.sControlName.includes(type + "BtnExtract")
      )
      : {};
    if (
      commonUtils.isNotEmptyArr(singleConfig) &&
      commonUtils.isNotEmptyArr(upTableData)
    ) {
      const sAssignField = singleConfig[0].sAssignField;
      let tableRow = {};
      tableRow = {
        ...tableRow,
        ...commonFunc.getAssignFieldValue(sAssignField, upTableData[iUIndex])
      }; // 取赋值字段
      if (commonUtils.isNotEmptyArr(pTableData)) {
        const handleType = commonUtils.isEmpty(upTableData[iUIndex].handleType)
          ? "update"
          : upTableData[0].handleType;
        pTableData[iIndex] = { ...pTableData[iIndex], ...tableRow };
        upTableData[iUIndex] = { ...upTableData[iUIndex], ...tableRow, handleType };
      } else {
        pTableData.push(tableRow);
      }
      props.onSaveState({ [`${pTable}Data`]: pTableData });
    } else if (commonUtils.isEmptyArr(singleConfig)) {
      message.error("请配置提取按钮！");
    }
  }
};

const handleBtnParamPage = (props, comparedTableId, type) =>{
  /* 找到所选择控制表, 根据当前行找 上条，下条，首条，末条 */
  const { slave0Data} = props;
  const processRow = handleGetSelectedData(props, 'slave0'); /* 工序当前选中行 */
  const controlRow = handleGetSelectedData(props, 'slave0Child1'); /* 控制表当前选中行 */
  let filterData = [];
  if(commonUtils.isNotEmptyObject(controlRow) && commonUtils.isNotEmptyArr(slave0Data)){
    filterData = slave0Data.filter(item => item.sControlId === controlRow.sId);
  }

  let tableDataRow = {};
  if( commonUtils.isNotEmptyArr(filterData)) {
    const iIndex = filterData.findIndex(item => item.sId === processRow.sId);
    if(iIndex > -1) {
      const len = filterData.length;
      if (type === 'first') {
        tableDataRow = filterData[0];

      }else if (type === 'last') {
        tableDataRow = filterData[len -1];

      }else if (type === 'before') {
        if(iIndex === 0 || iIndex > len -1) {
          message.error('当前是首条');
          return;
        }
        tableDataRow = filterData[iIndex - 1];

      }else if (type === 'next') {
        if(iIndex === len-1 || iIndex > len -1) {
          message.error('当前是末条');
          return;
        }
        tableDataRow = filterData[iIndex + 1];
      }
      if(commonUtils.isNotEmptyObject(tableDataRow)) {
        props.onSaveState({ slave0SelectedRowKeys: [tableDataRow.sId]})
      }
    }else{
      message.error('数据错误！');
    }
  } else{
    message.error('数据错误！');
  }

}

const handleGetSelectedData = (props, tableName) => {
  const selectedRowKeys = props[`${tableName}SelectedRowKeys`] || [];
  let selectedDataIndex = -1;
  const tableData = props[`${tableName}Data`];
  if (commonUtils.isNotEmptyArr(tableData)) {
    if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
      selectedDataIndex = tableData.findIndex(
        item => item.sId === selectedRowKeys[0]
      );
    } else {
      selectedDataIndex = 0;
    }
  }

  if( selectedDataIndex > -1) {
    console.log('工序选中行', props[`${tableName}Data`][selectedDataIndex]);
    return props[`${tableName}Data`][selectedDataIndex];
  } else {
    return {};
  }
};


export default CommonBase(CommonNewSales(CommonNewBill));
