/* eslint-disable */
import React, { useEffect, useState, useMemo, useRef } from "react";
import moment from "moment";
import { Avatar, Collapse, Radio, Row, Col, Divider, message, Modal, Button } from "antd-v4";
import { RightOutlined } from "@ant-design/icons";
import { Form } from "@ant-design/compatible";
import CommonBase from "@/components/Common/CommonBase";
import CommonSales from "@/components/Common/CommonBillEvent";
import { CommonPackEvent, CommonModal } from "../CommonPackEvent";
import * as commonBusiness from "@/components/Common/commonBusiness";
import * as commonUtils from "@/utils/utils";
import * as commonFunc from "@/components/Common/commonFunc";
import commonConfig from "@/utils/config";
import * as commonServices from "@/services/services";
import Toolbar from "@/components/Common/ToolBar/ToolBarNew";
import CommonView from "@/components/Common/CommonView";
import StaticEditTable from "@/components/Common/CommonTable";
import CommonViewDragable from "@/components/Common/CommonViewDragable";
import AntdDraggableModal from "@/components/Common/AntdDraggableModal";
import styles from "./index.less";
import CommonExamInfo from "../../Common/CommonExamInfo";

const { Panel } = Collapse;

// 数据处理
const WorkOrderPackTableTreeNewEvent = props => {
  const { formData, currentId, app, token, masterConfig = {}, slaveConfig } = props;
  const sId = currentId || "";
  const returnProps = {};
  const pageType = useRef("pbom");
  const isProcessAssortApiCalled = useRef(false);
  // 初始化获取数据
  useEffect(
    () => {
      if (!masterConfig.sId) return;
      if (masterConfig.sTbName.toLowerCase().includes("workorder")) {
        pageType.current = "workorder";
      }

      const fetchData = async () => {
        let addState = { pageType: pageType.current };
        const tableList = [];

        // 控制表配置
        const controlConfig = formData.filter(item => item.sTbName.toUpperCase() === "MftWorkOrderControl".toUpperCase())[0];
        const controlColumn = commonFunc.getHeaderConfig(controlConfig);
        tableList.push(["control", controlConfig, controlColumn]);

        // 工序表配置
        const processConfig = formData.filter(item => item.sTbName.toUpperCase() === "MftWorkOrderProcess".toUpperCase())[0];
        const iIndex = processConfig.gdsconfigformslave.findIndex(item => item.sName === "sMachineId");
        if (iIndex !== -1) {
          processConfig.gdsconfigformslave[iIndex].bReGetDropDown = true;
        }
        const processColumn = commonFunc.getHeaderConfig(processConfig);
        tableList.push(["process", processConfig, processColumn]);

        // 成品工序表配置
        const finishedProcessConfig = commonUtils.isNotEmptyArr(formData.filter(item => item.sGrd?.includes('productProcess'))) ?
          formData.filter(item => item.sGrd?.includes('productProcess'))[0] : {};
        const finishedProcessColumn = commonUtils.isNotEmptyObject(finishedProcessConfig)  ? commonFunc.getHeaderConfig(finishedProcessConfig) : false;
        if(commonUtils.isNotEmptyObject(finishedProcessConfig)) {
          tableList.push(["finishedProcess", finishedProcessConfig, finishedProcessColumn]);
        }

        // 成品材料表配置
        let finishedMaterialsConfig = commonUtils.isNotEmptyArr(formData.filter(item => item.sGrd?.includes('productMaterials'))) ?
          formData.filter(item => item.sGrd?.includes('productMaterials'))[0] : '';
        const finishedMaterialsColumn = finishedMaterialsConfig ? commonFunc.getHeaderConfig(finishedMaterialsConfig) : false;
        if(commonUtils.isNotEmptyObject(finishedProcessConfig)) {
          tableList.push(["finishedMaterials", finishedMaterialsConfig, finishedMaterialsColumn]);
        }


        // 材料表配置
        const materialsConfig = formData.filter(item => item.sTbName.toUpperCase() === "MftWorkOrderMaterials".toUpperCase())[0];
        const materialsColumn = commonFunc.getHeaderConfig(materialsConfig);
        addState = {
          ...addState,
          materialsConfig,
          materialsColumn,
        };

        const materialsInfoList = [];
        const materialsChildInfoList = [];
        const addStateMap = {};
        const materialsFormData = formData.filter(item => item.sGrd?.includes("materials") && item.bGrdVisible);

        materialsFormData.forEach((item, index) => {
          const config = item;
          const column = commonFunc.getHeaderConfig(item);
          const tablename = `materials${index}`;
          materialsInfoList.push(tablename);
          tableList.push([tablename, config, column]);
          addStateMap[`${tablename}Config`] = config;
          /* 找到该配置的子从表 */
          const childFormData = formData.filter(child => child.sGrd === item.sChildTableName);
          if (commonUtils.isNotEmptyArr(childFormData)) {
            childFormData.forEach((child, num) => {
              const childConfig = child;
              const childColumn = commonFunc.getHeaderConfig(child);
              const chlidTablename = `materials${index}Child`;
              materialsChildInfoList.push(chlidTablename);
              tableList.push([chlidTablename, childConfig, childColumn]);
              addStateMap[`${chlidTablename}Config`] = childConfig;
            });
          }
        });

        addState = {
          ...addState,
          materialsInfoList,
          materialsChildInfoList,
          addStateMap,
        };

        // // 日志表配置
        // const dailyConfig = formData.filter(item => item.sTbName.toUpperCase() === "mftproductchange".toUpperCase())[0];
        // const dailyConfigGrdVisible = dailyConfig?.bGrdVisible;

        // if (dailyConfigGrdVisible) {
        //   const dailyColumn = commonFunc.getHeaderConfig(dailyConfig);
        //   tableList.push(["daily", dailyConfig, dailyColumn]);
        // }

        // 颜色配置
        let colorConfig =
          formData.filter(item => item.sTbName.toUpperCase() === "mftworkorderparam".toUpperCase())[0] ||
          formData.filter(item => item.sTbName.toUpperCase() === "mftproductchange".toUpperCase())[0];
        const colorConfigGrdVisible = colorConfig?.bGrdVisible;

        if (colorConfigGrdVisible) {
          const colorColumn = commonFunc.getHeaderConfig(colorConfig);
          tableList.push(["color", colorConfig, colorColumn]);
        }

        // 合版信息配置
        const packConfig = formData.filter(
          item =>
            item.sTbName.toUpperCase() === "mftproductcontrolcombine".toUpperCase() ||
            item.sTbName.toUpperCase() === "mftworkordercontrolcombine".toUpperCase()
        )[0];

        // 合版信息拼接从表配置,客户名称 ，产品名称，生产数
        const slaveChooseConfig = slaveConfig.gdsconfigformslave.filter(
          item =>
            item.sName === "sCustomerName" ||
            item.sName === "sProductId" ||
            item.sName === "sCustomerId" ||
            item.sName === "sProductNo" ||
            item.sName === "sProductName" ||
            item.sName === "dProductQty" ||
            item.sName === "sProductStyle" ||
            item.sName === "sProductUnit"
        );
        const salveChooseConfigFilter = [];
        if (commonUtils.isNotEmptyArr(slaveChooseConfig) && commonUtils.isNotEmptyObject(packConfig)) {
          slaveChooseConfig.forEach(item => {
            const iIndex = packConfig.gdsconfigformslave.findIndex(itemNew => itemNew.sName === item.sName);
            if (iIndex === -1) {
              const itemNew = Object.assign({}, item);
              itemNew.bNotEmpty = false;
              salveChooseConfigFilter.push(itemNew);
            }
          });
        }

        if (commonUtils.isNotEmptyArr(salveChooseConfigFilter)) {
          if (commonUtils.isNotEmptyObject(packConfig)) {
            let packFilter = packConfig.gdsconfigformslave.filter(item => item.sName === "iOrder");
            packFilter = packFilter.concat(salveChooseConfigFilter);
            const packFilterOther = packConfig.gdsconfigformslave.filter(item => item.sName !== "iOrder");
            packFilter = packFilter.concat(packFilterOther);
            packConfig.gdsconfigformslave = packFilter;
          }
        }

        const packColumn = commonFunc.getHeaderConfig(packConfig);

        tableList.push(["pack", packConfig, packColumn]);

        // 改版信息配置
        const visionConfig = formData.find(item => item.sTbName.toUpperCase() === "sisrevision".toUpperCase() && item.bGrdVisible);
        if (visionConfig) {
          const visionColumn = commonFunc.getHeaderConfig(visionConfig);
          tableList.push(["vision", visionConfig, visionColumn]);
          addStateMap["visionConfig"] = visionConfig;
        }

        if (sId) {
          props.onGetData(masterConfig, slaveConfig);

          // 获取数据
          const fetchDataPromises = tableList.filter(item => item[1]).map(async item => {
            const [name, configData, column] = item;
            const dataSet = await props.handleGetDataSet({
              name,
              configData,
              condition: { sSqlCondition: { sParentId: sId } },
              isWait: true,
            });
            if(name === 'process'){
              dataSet.processSelectedRowKeys = [];
            }
            return {
              [`${name}Config`]: configData,
              [`${name}Column`]: column,
              ...dataSet,
            };
          });
          const results = await Promise.all(fetchDataPromises);
          results.forEach(result => {
            addState = { ...addState, ...result };
          });
        } else {
          const config = {};
          config.masterConfig = masterConfig;
          config.slaveConfig = slaveConfig;
          config.controlConfig = controlConfig;
          config.materialsConfig = materialsConfig;
          config.processConfig = processConfig;
          config.packConfig = packConfig;
          config.colorConfig = colorConfig;
          // config.dailyConfig = dailyConfig;
          addState = {
            ...addState,
            ...(await handleAdd(config, props.app.currentPane.copyTo, true)),
          };

          tableList.filter(item => item[1]).forEach(item => {
            const [name, configData, column] = item;
            addState = {
              ...addState,
              [`${name}Config`]: configData,
              [`${name}Column`]: column,
            };
          });
        }

        props.onSaveState(addState);
      };

      fetchData();
    },
    [masterConfig.sId]
  );

  // 将事件指派到指定的方法
  const dispatchFunc = (tableName, funcName, nameList, args) => {
    const params = nameList.reduce((pre, item, index) => {
      pre[item] = args[index];
      return pre;
    }, {});

    const func = props[`${tableName}Props`]?.[funcName];
    console.log("=====func", func);
    if (func) {
      return func(params);
    }

    return props[funcName](...args);
  };

  // 新增
  const handleAdd = async (config, copyTo, isWait) => {
    if (commonUtils.isEmptyObject(config)) {
      const { masterConfig, slaveConfig, controlConfig, processConfig, materialsConfig, colorConfig } = props;
      config = config === undefined ? {} : config;
      config.masterConfig = masterConfig;
      config.slaveConfig = slaveConfig;
      config.materialsConfig = materialsConfig;
      config.controlConfig = controlConfig;
      config.processConfig = processConfig;
      config.colorConfig = colorConfig;
    }
    let state = await props.onAdd(config, copyTo, true);
    let { slaveData, masterData } = state;
    let controlData = [];
    let packData = [];
    let materialsData = [];
    let processData = [];
    const colorData = [];
    const visionData = [];
    /* 未清复制到或是翻单走的逻辑 */
    if (commonUtils.isNotEmptyObject(copyTo)) {
      const { app, sModelsId, token, sModelsType } = props;
      const bCkxCopyFromTechnology = app.systemData.filter(item => item.sName === "CkxCopyFromTechnology")[0].sValue;
      const bCopyFromProcessCard =
        (commonUtils.isNotEmptyObject(copyTo.oldFormId) && copyTo.oldFormId === copyTo.newFormId) || sModelsType === "manufacture/workOrder2";
      /* 未清列表复制到，以工艺卡为主时所走的逻辑 */
      if (bCkxCopyFromTechnology === "1" && !bCopyFromProcessCard) {
        const sCustomerId = commonUtils.isEmptyStr(copyTo.masterData.sCustomerId) ? copyTo.slaveData[0].sCustomerId : copyTo.masterData.sCustomerId;
        const sProductIdArray = [];
        const sVerArray = [];
        copyTo.slaveData.forEach(slaveItem => {
          const sProductId = slaveItem.sProductId;
          if (commonUtils.isNotEmptyStr(sProductId)) {
            sProductIdArray.push(sProductId);
          }
          const sVerStr = slaveItem.sProductTechnologyVer;
          if (commonUtils.isNotEmptyStr(sVerStr)) {
            sVerArray.push(sVerStr);
          }
        });
        console.log('copyTo', copyTo, sVerArray);
        const sProductIds = sProductIdArray.toString();
        const sProductTechnologyVer =sVerArray.toString();
        const sRowData = copyTo?.slaveData || [];
        const condition = { sCustomerId, sProductIds, sProductTechnologyVer, sRowData};
        const dataUrl = `${commonConfig.server_host}salesorder/getProcessCardDataByCustomIdProductId/?sModelsId=${sModelsId}`;
        const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
        if (dataReturn.code === 1) {
          const returnData = dataReturn.dataset.rows[0];
          const copyToMasterDetailConfig = copyTo.config.filter(
            item => item.sControlName.toLowerCase() === `${copyTo.name}.masterdetail`.toLowerCase()
          );
          const copyToSlaveConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.slave`.toLowerCase());
          const copyToSlaveDetailConfig = copyTo.config.filter(
            item => item.sControlName.toLowerCase() === `${copyTo.name}.slavedetail`.toLowerCase()
          );
          const copyToControlConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.control`.toLowerCase());
          const copyToMaterialsConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.materials`.toLowerCase());
          const copyToProcessConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.process`.toLowerCase());
          const copyToColorConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.param`.toLowerCase());
          const copyToPackConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.pack`.toLowerCase());
          const masterDetailAssignField = commonUtils.isNotEmptyArr(copyToMasterDetailConfig) ? copyToMasterDetailConfig[0].sAssignField : "";
          const slaveAssignField = commonUtils.isNotEmptyObject(copyToSlaveConfig) ? copyToSlaveConfig[0].sAssignField : "";
          const slaveDetailAssignField = commonUtils.isNotEmptyArr(copyToSlaveDetailConfig) ? copyToSlaveDetailConfig[0].sAssignField : "";
          const controlAssignField = commonUtils.isNotEmptyArr(copyToControlConfig) ? copyToControlConfig[0].sAssignField : "";
          const materialsAssignField = commonUtils.isNotEmptyArr(copyToMaterialsConfig) ? copyToMaterialsConfig[0].sAssignField : "";
          const processAssignField = commonUtils.isNotEmptyArr(copyToProcessConfig) ? copyToProcessConfig[0].sAssignField : "";
          const colorAssignField = commonUtils.isNotEmptyArr(copyToColorConfig) ? copyToColorConfig[0].sAssignField : "";
          const packAssignField = commonUtils.isNotEmptyArr(copyToPackConfig) ? copyToPackConfig[0].sAssignField : "";

          const bProcessAssort = false;
          let returnProcessAssort = [];
          let processAssignAssort = "";
          let dropDownDataProcessName;
          const newCopyTo = {};
          newCopyTo.master = copyTo.masterData;
          newCopyTo.slave = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0];
          if (commonUtils.isNotEmptyArr(returnData.controlData)) {
            let dProductQty = 0;
            if (commonUtils.isNotEmptyArr(returnData.slaveData)) {
              masterData = {
                ...masterData,
                ...commonFunc.getAssignFieldValue(masterDetailAssignField, returnData.slaveData[0], newCopyTo),
              }; // 取赋值字段
              state.masterData = masterData;
            }
            if (commonUtils.isNotEmptyArr(returnData.slaveData)) {
              if (slaveData.length === 1 && returnData.slaveData.length === 1) {
                /* 从表与返回数据从表只有一条时 替换该从表数据  */
                // masterData = { ...masterData, ...commonFunc.getAssignFieldValue(masterDetailAssignField, returnData.slaveData[0], newCopyTo) }; // 取赋值字段
                slaveData.forEach((item, iSlaveIndex) => {
                  item = {
                    ...item,
                    ...commonFunc.getAssignFieldValue(slaveDetailAssignField, returnData.slaveData[0], newCopyTo),
                  }; // 取赋值字段
                  slaveData[iSlaveIndex] = item;
                });
              } else {
                // slaveData =[];
                returnData.slaveData.forEach(slaveItem => {
                  newCopyTo.slave = slaveItem;
                  const iSameIndex = commonUtils.isNotEmptyArr(slaveData)
                    ? slaveData.findIndex(
                      itemCurrent => itemCurrent.sProductId === slaveItem.sProductId && itemCurrent.sCustomerId === slaveItem.sCustomerId
                    )
                    : -1;
                  if (iSameIndex > -1) {
                    masterData = {
                      ...masterData,
                      ...commonFunc.getAssignFieldValue(masterDetailAssignField, slaveItem, newCopyTo),
                    }; // 取赋值字段
                    slaveData[iSameIndex] = {
                      ...slaveData[iSameIndex],
                      ...commonFunc.getAssignFieldValue(slaveDetailAssignField, slaveItem, newCopyTo),
                    }; // 取赋值字段
                    slaveData[iSameIndex].sOriginalId = commonUtils.isNotEmptyObject(slaveItem.sSlaveId)
                      ? slaveItem.sSlaveId
                      : slaveItem.sId; /* 原始sId */
                  } else {
                    let slaveRow = {};
                    slaveRow = {
                      ...slaveRow,
                      ...commonFunc.getAssignFieldValue(slaveDetailAssignField, slaveItem, newCopyTo),
                    }; // 取赋值字段
                    slaveRow.handleType = "add";
                    slaveRow.sId = commonUtils.createSid();
                    slaveRow.sParentId = masterData.sId;
                    slaveRow.sOriginalId = slaveItem.sSlaveId;
                    slaveData.push(slaveRow);
                  }
                });
              }
            }
            const treeCopyNodes = new Map();
            await returnData.controlData.forEach(async controlItem => {
              newCopyTo.control = controlItem;
              let controlRow = commonFunc.getDefaultData(config.controlConfig, newCopyTo); // 取默认值
              controlRow = {
                ...controlRow,
                ...commonFunc.getAssignFieldValue(controlAssignField, controlItem, newCopyTo),
              }; // 取赋值字段
              controlRow.handleType = "add";
              controlRow.sId = commonUtils.createSid();
              controlRow.sParentId = masterData.sId;
              /* CopyTo时sAllId,sControlParentId 设置 */
              // const sAllOldId = controlItem.sAllId;
              // let arr = [];
              // if (commonUtils.isNotEmptyObject(sAllOldId)) {
              //   arr = sAllOldId.split(",");
              // }
              // const newId = controlRow.sId;
              // let sOldParentId = "";
              // let sNewParentAllId = "";
              // if (arr.length < 2) {
              //   /* 根节点复制 */
              //   controlRow.sAllId = newId;
              //   sOldParentId = newId;
              //   sNewParentAllId = newId;
              // } else {
              //   sOldParentId = arr[arr.length - 2];
              //   if (treeCopyNodes.has(sOldParentId)) {
              //     sNewParentAllId = treeCopyNodes.get(sOldParentId);
              //   } else {
              //     const obj = arr[arr.length - 1];
              //     sNewParentAllId = sAllOldId.replace(`,${obj}`, "");
              //   }
              //   const sNewArr = sNewParentAllId.split(",");
              //   controlRow.sControlParentId = sNewArr[sNewArr.length - 1];
              //   sNewParentAllId = `${sNewParentAllId},${newId}`;
              //   controlRow.sAllId = sNewParentAllId;
              // }
              // treeCopyNodes.set(controlItem.sId, sNewParentAllId);
              controlRow.dPartsQty = dProductQty;
              controlData.push(controlRow);

              /* 复制到时增加合版表 */
              if (commonUtils.isNotEmptyArr(returnData.packData)) {
                await returnData.packData.filter(item => item.sControlId === controlItem.sId).forEach(async packItem => {
                  newCopyTo.pack = packItem;
                  let packRow = commonFunc.getDefaultData(config.packConfig, newCopyTo); // 取默认值
                  packRow = {
                    ...packRow,
                    ...commonFunc.getAssignFieldValue(packAssignField, packItem, newCopyTo),
                  }; // 取赋值字段
                  packRow.sOriginalId = packItem.sId; /* 翻单前的sId */
                  /* sSlaveId赋值 */
                  const iSlaveIndex = slaveData.findIndex(item => item.sOriginalId === packItem.sSlaveId);
                  if (iSlaveIndex > -1) {
                    const slaveDataRow = slaveData[iSlaveIndex];
                    const packRowAdd = props.handlePackDataAdd(slaveDataRow, 0, controlRow.sId, "add");
                    if (commonUtils.isNotEmptyObject(packRowAdd)) {
                      packRow = { ...packRow, ...packRowAdd };
                      /* 将控制表中的合版备注sId为新的sId */
                      let JsonData = [];
                      const jsonStr = controlRow.sCombinedMemo;
                      if (commonUtils.isNotEmptyObject(jsonStr) && commonUtils.isJSON(jsonStr)) {
                        JsonData = JSON.parse(jsonStr);
                        if (commonUtils.isNotEmptyArr(JsonData)) {
                          let sCombinedMemoNew = "";
                          JsonData.forEach((item, index) => {
                            if (item.sId === packItem.sId) {
                              JsonData[index].sId = packRow.sId;
                            }
                          });
                          sCombinedMemoNew = JSON.stringify(JsonData);
                          controlRow.sCombinedMemo = sCombinedMemoNew;
                          const icontrolIndex = controlData.findIndex(item => item.sId === controlRow.sId);
                          if (icontrolIndex) {
                            controlData[icontrolIndex] = {
                              ...controlData[icontrolIndex],
                              sCombinedMemo: sCombinedMemoNew,
                            };
                          }
                        }
                      }
                      packData.push(packRow);
                    }
                  }
                });
              }

              if (commonUtils.isNotEmptyArr(returnData.processData)) {
                returnData.processData.filter(item => item.sControlId === controlItem.sId && item.sType !== "3").forEach(processItem => {
                  // eslint-disable-next-line radix
                  if (true) {
                    newCopyTo.process = processItem;
                    let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                    processRow = {
                      ...processRow,
                      ...commonFunc.getAssignFieldValue(processAssignField, processItem, newCopyTo),
                    }; // 取赋值字段
                    processRow.handleType = "add";
                    processRow.sId = commonUtils.createSid();
                    processRow.sParentId = masterData.sId;
                    processRow.sControlId = controlRow.sId;
                    processRow.sPartsName = controlRow.sPartsName;
                    /* 根据合版表的源sOriginalId找到新sId */
                    let sNewIds = "";
                    let sNewNames = "";
                    const sOldIds = processItem.sCombinePartsName;
                    if (commonUtils.isNotEmptyObject(sOldIds)) {
                      const sOldArr = sOldIds.split(",");
                      for (const sId of sOldArr) {
                        const index = packData.findIndex(item => item.sOriginalId === sId);
                        if (index > -1) {
                          const tableDataRow = packData[index];
                          sNewIds += `${tableDataRow.sId},`;
                          sNewNames += `${tableDataRow.sCustomerName}-${tableDataRow.sProductName}-${tableDataRow.sCombinePartsName},`;
                        }
                      }
                      sNewIds = commonUtils.isNotEmptyObject(sNewIds) ? sNewIds.substr(0, sNewIds.length - 1) : "";
                      sNewNames = commonUtils.isNotEmptyObject(sNewNames) ? sNewNames.substr(0, sNewNames.length - 1) : "";
                    }
                    processRow.sCombinePartsName = sNewIds;
                    processRow.sCombinePartsNameNew = sNewNames;
                    processData.push(processRow);
                  }
                });
              }

              if (commonUtils.isNotEmptyArr(returnData.materialsData)) {
                await returnData.materialsData
                  .filter(item => item.sControlId === controlItem.sId && item.sType !== "2")
                  .forEach(async materialsItem => {
                    newCopyTo.materials = materialsItem;
                    let materialsRow = commonFunc.getDefaultData(config.materialsConfig, newCopyTo); // 取默认值
                    materialsRow = {
                      ...materialsRow,
                      ...commonFunc.getAssignFieldValue(materialsAssignField, materialsItem, newCopyTo),
                    }; // 取赋值字段
                    materialsRow.handleType = "add";
                    materialsRow.sId = commonUtils.createSid();
                    materialsRow.sParentId = masterData.sId;
                    materialsRow.sControlId = controlRow.sId;
                    materialsRow.sPartsName = controlRow.sPartsName;
                    materialsRow.sOriginalId = materialsItem.sId;
                    materialsRow.sZmldlt = materialsItem.sZmldlt;
                    materialsRow.sInkFatherMaterialsTbId = materialsItem.sInkFatherMaterialsTbId;
                    // 材料对应工序的ID要变化
                    if (commonUtils.isNotEmptyArr(returnData.processData)) {
                      const iProcessIndex = processData.findIndex(
                        item => item.sControlId === controlRow.sId && item.sSrcProcessTbId === materialsItem.sProcessTbId
                      );
                      if (iProcessIndex > -1) {
                        materialsRow.sProcessTbId = processData[iProcessIndex].sId;
                      }
                    }
                    materialsData.push(materialsRow);
                  });
              }
              /* 将 materialsData中sParentMaterialsId替换为最新的sid */
              if (commonUtils.isNotEmptyArr(materialsData)) {
                const materialsFilterData = materialsData.filter(item => commonUtils.isNotEmptyObject(item.sParentMaterialsId));
                if (commonUtils.isNotEmptyArr(materialsFilterData)) {
                  materialsFilterData.forEach((filterItem, index) => {
                    const iIndex = materialsData.findIndex(item => item.sOriginalId === filterItem.sParentMaterialsId);
                    if (iIndex > -1) {
                      const iNexIndex = materialsData.findIndex(item => item.sId === filterItem.sId);
                      if (iNexIndex > -1) {
                        materialsData[iNexIndex] = {
                          ...materialsData[iNexIndex],
                          sParentMaterialsId: materialsData[iIndex].sId,
                        };
                      }
                    }
                  });
                }

                const materialsInkFilterData = materialsData.filter(item => commonUtils.isNotEmptyObject(item.sInkFatherMaterialsTbId));
                if (commonUtils.isNotEmptyArr(materialsInkFilterData)) {
                  materialsInkFilterData.forEach((filterItem, index) => {
                    const iIndex = materialsData.findIndex(item => item.sOriginalId === filterItem.sInkFatherMaterialsTbId);
                    if (iIndex > -1) {
                      const iNexIndex = materialsData.findIndex(item => item.sId === filterItem.sId);
                      if (iNexIndex > -1) {
                        materialsData[iNexIndex] = {
                          ...materialsData[iNexIndex],
                          sInkFatherMaterialsTbId: materialsData[iIndex].sId,
                        };
                      }
                    }
                  });
                }
              }
            });
          }
          if (commonUtils.isNotEmptyArr(returnData.materialsData)) {
            await returnData.materialsData.filter(item => item.sType === "2").forEach(async materialsItem => {
              newCopyTo.materials = materialsItem;
              let materialsRow = commonFunc.getDefaultData(config.materialsConfig, newCopyTo); // 取默认值
              materialsRow = {
                ...materialsRow,
                ...commonFunc.getAssignFieldValue(materialsAssignField, materialsItem, newCopyTo),
              }; // 取赋值字段
              materialsRow.handleType = "add";
              materialsRow.sId = commonUtils.createSid();
              materialsRow.sParentId = masterData.sId;

              /* 根据从表源sOriginalId找到新sId */
              let sNewIds = "";
              let sNewNames = "";
              const sOldIds = materialsItem.sCombinePartsName;
              if (commonUtils.isNotEmptyObject(sOldIds)) {
                const sOldArr = sOldIds.split(",");
                for (const sId of sOldArr) {
                  const index = slaveData.findIndex(item => item.sOriginalId === sId);
                  if (index > -1) {
                    const tableDataRow = slaveData[index];
                    sNewIds += `${tableDataRow.sId},`;
                    sNewNames += `${tableDataRow.sProductName},`;
                  }
                }
                sNewIds = commonUtils.isNotEmptyObject(sNewIds) ? sNewIds.substr(0, sNewIds.length - 1) : "";
                sNewNames = commonUtils.isNotEmptyObject(sNewNames) ? sNewNames.substr(0, sNewNames.length - 1) : "";
              }
              materialsRow.sCombinePartsName = sNewIds;
              materialsRow.sCombinePartsNameNew = sNewNames;
              materialsData.push(materialsRow);
            });
          }

          if (commonUtils.isNotEmptyArr(returnData.processData)) {
            returnData.processData.filter(item => item.sType === "3").forEach(processItem => {
              newCopyTo.process = processItem;
              let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
              processRow = {
                ...processRow,
                ...commonFunc.getAssignFieldValue(processAssignField, processItem, newCopyTo),
              }; // 取赋值字段
              processRow.handleType = "add";
              processRow.sId = commonUtils.createSid();
              processRow.sParentId = masterData.sId;
              /* 根据从表的源sOriginalId找到新sId */
              let sNewIds = "";
              let sNewNames = "";
              const sOldIds = processItem.sCombinePartsName;
              if (commonUtils.isNotEmptyObject(sOldIds)) {
                const sOldArr = sOldIds.split(",");
                for (const sId of sOldArr) {
                  const index = slaveData.findIndex(item => item.sOriginalId === sId);
                  if (index > -1) {
                    const tableDataRow = slaveData[index];
                    sNewIds += `${tableDataRow.sId},`;
                    sNewNames += `${tableDataRow.sCustomerName}-${tableDataRow.sProductName},`;
                  }
                }
                sNewIds = commonUtils.isNotEmptyObject(sNewIds) ? sNewIds.substr(0, sNewIds.length - 1) : "";
                sNewNames = commonUtils.isNotEmptyObject(sNewNames) ? sNewNames.substr(0, sNewNames.length - 1) : "";
              }
              processRow.sCombinePartsName = sNewIds;
              processRow.sCombinePartsNameNew = sNewNames;
              processData.push(processRow);
              // 成品配套工序
              if (bProcessAssort) {
                returnProcessAssort.filter(item => item.sParentId === processRow.sProcessId).forEach(itemProcessAssort => {
                  const iIndex = dropDownDataProcessName.findIndex(item => item.sId === itemProcessAssort.sProcessId);
                  const iProcessIndex = returnData.processData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId);
                  const iNewProcessIndex = processData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId);
                  if (iIndex > -1 && iProcessIndex < 0 && iNewProcessIndex < 0) {
                    if (itemProcessAssort.sType === "single") {
                      let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                      processRow = {
                        ...processRow,
                        ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                      }; // 取赋值字段
                      processRow.handleType = "add";
                      processRow.sId = commonUtils.createSid();
                      processRow.sParentId = masterData.sId;
                      processRow.sType = dropDownDataProcessName[iIndex].sType;
                      processData.push(processRow);
                    } else if (itemProcessAssort.sType === "all") {
                      controlData.forEach(controlItem => {
                        let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                        processRow = {
                          ...processRow,
                          ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                        }; // 取赋值字段
                        processRow.handleType = "add";
                        processRow.sId = commonUtils.createSid();
                        processRow.sParentId = masterData.sId;
                        processRow.sControlId = controlItem.sId;
                        processRow.sPartsName = controlItem.sPartsName;
                        processRow.sType = dropDownDataProcessName[iIndex].sType;
                        processData.push(processRow);
                      });
                    }
                  }
                });
              }
            });
          }
          if (commonUtils.isNotEmptyArr(returnData.colorData)) {
            returnData.colorData.forEach(colorItem => {
              newCopyTo.color = colorItem;
              let colorRow = commonFunc.getDefaultData(config.colorConfig, newCopyTo); // 取默认值
              colorRow = {
                ...colorRow,
                ...commonFunc.getAssignFieldValue(colorAssignField, colorItem, newCopyTo),
              }; // 取赋值字段
              colorRow.handleType = "add";
              colorRow.sId = commonUtils.createSid();
              colorRow.sParentId = masterData.sId;
              colorData.push(colorRow);
            });
          }
        } else {
          props.getServiceError(dataReturn.msg);
        }
      } else {
        const copyToControlConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.control`.toLowerCase());
        const copyToMaterialsConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.materials`.toLowerCase());
        const copyToProcessConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.process`.toLowerCase());
        const copyToColorConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.param`.toLowerCase());
        const copyToPackConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.pack`.toLowerCase());
        const copyToVisionConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.vision`.toLowerCase());
        const controlAssignField = commonUtils.isNotEmptyArr(copyToControlConfig) ? copyToControlConfig[0].sAssignField : "";
        const materialsAssignField = commonUtils.isNotEmptyArr(copyToMaterialsConfig) ? copyToMaterialsConfig[0].sAssignField : "";
        const processAssignField = commonUtils.isNotEmptyArr(copyToProcessConfig) ? copyToProcessConfig[0].sAssignField : "";
        const colorAssignField = commonUtils.isNotEmptyArr(copyToColorConfig) ? copyToColorConfig[0].sAssignField : "";
        const packAssignField = commonUtils.isNotEmptyArr(copyToPackConfig) ? copyToPackConfig[0].sAssignField : "";
        const visionAssignField = commonUtils.isNotEmptyArr(copyToVisionConfig) ? copyToVisionConfig[0].sAssignField : "";

        const newCopyTo = {};
        newCopyTo.master = copyTo.masterData;
        newCopyTo.slave = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0];
        let bProcessAssort = false;
        /* 生产翻单不生成配套工序 */
        const srcFormRoute = copyTo.srcFormRoute; /* 未清来源路径 */
        if (sModelsType === "manufacture/workOrder" && (commonUtils.isEmpty(srcFormRoute) || srcFormRoute.includes("workOrder"))) {
          bProcessAssort = false;
        }
        if (commonUtils.isEmptyArr(copyTo.controlData) && commonUtils.isNotEmptyArr(copyTo.slaveData)) {
          const { token } = props;
          const sSlaveId = commonUtils.isNotEmptyStr(copyTo.slaveData[0].sSlaveId) ? copyTo.slaveData[0].sSlaveId : copyTo.slaveData[0].sId;
          const condition = { sSlaveId };
          const dataUrl = `${commonConfig.server_host}salesorder/getPartsInfo?sModelsId=${sModelsId}`;
          const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
          // bProcessAssort = false;
          if (dataReturn.code === 1) {
            const returnData = dataReturn.dataset.rows[0];
            copyTo.controlData = returnData.controlData;
            copyTo.materialsData = returnData.materialsData;
            copyTo.processData = returnData.processData;
            copyTo.packData = returnData.packData;
            copyTo.colorData = returnData.colorData;
          } else {
            await props.getServiceError(dataReturn);
          }
        }

        let returnProcessAssort = [];
        let processAssignAssort = "";
        let dropDownDataProcessName;
        if (bProcessAssort) {
          const dataUrl = `${commonConfig.server_host}salesorder/getProcessAssort?sModelsId=${sModelsId}`;
          const dataProcessAssort = (await commonServices.postValueService(token, {}, dataUrl)).data;
          if (dataProcessAssort.code === 1) {
            returnProcessAssort = dataProcessAssort.dataset.rows[0].processassort;
            const iIndex = config.processConfig.gdsconfigformslave.findIndex(item => item.sName === "sProcessName");
            if (iIndex > -1) {
              const sqlDropDownData = await props.getSqlDropDownData(sModelsId, "slave", config.processConfig.gdsconfigformslave[iIndex]);
              dropDownDataProcessName = sqlDropDownData.dropDownData;
              processAssignAssort = config.processConfig.gdsconfigformslave[iIndex].sAssignField;
            }
          }
        }
        if (commonUtils.isNotEmptyArr(copyTo.controlData)) {
          // let dProductQty = 0;
          // slaveData.forEach((item) => {
          //   dProductQty += commonUtils.isNull(item.dProductQty, 0) + commonUtils.isNull(item.dGiveQty, 0);
          // });
          const treeCopyNodes = new Map();
          await copyTo.controlData.forEach(async controlItem => {
            newCopyTo.control = controlItem;
            let controlRow = commonFunc.getDefaultData(config.controlConfig, newCopyTo); // 取默认值
            controlRow = {
              ...controlRow,
              ...commonFunc.getAssignFieldValue(controlAssignField, controlItem, newCopyTo),
            }; // 取赋值字段
            controlRow.handleType = "add";
            controlRow.sId = commonUtils.createSid();
            controlRow.sOriginalId = controlItem.sId; /* 复制前的部件表sId */
            controlRow.sParentId = masterData.sId;
            /* 没有sNodeId需要生成一个新的，有的直接带下来 */
            if (commonUtils.isEmptyObject(controlItem.sNodeId)) {
              controlRow.sNodeId = commonUtils.createSid();
            } else {
              controlRow.sNodeId = controlItem.sNodeId;
            }
            /* CopyTo时sAllId,sControlParentId 设置 */
            // const sAllOldId = controlItem.sAllId;
            // let arr = [];
            // if (commonUtils.isNotEmptyObject(sAllOldId)) {
            //   arr = sAllOldId.split(",");
            // }
            // const newId = controlRow.sId;
            // let sOldParentId = "";
            // let sNewParentAllId = "";
            // if (arr.length < 2) {
            //   /* 根节点复制 */
            //   controlRow.sAllId = newId;
            //   sOldParentId = newId;
            //   sNewParentAllId = newId;
            // } else {
            //   sOldParentId = arr[arr.length - 2];
            //   if (treeCopyNodes.has(sOldParentId)) {
            //     sNewParentAllId = treeCopyNodes.get(sOldParentId);
            //   } else {
            //     const obj = arr[arr.length - 1];
            //     sNewParentAllId = sAllOldId.replace(`,${obj}`, "");
            //   }
            //   const sNewArr = sNewParentAllId.split(",");
            //   controlRow.sControlParentId = sNewArr[sNewArr.length - 1];
            //   sNewParentAllId = `${sNewParentAllId},${newId}`;
            //   controlRow.sAllId = sNewParentAllId;
            // }
            // treeCopyNodes.set(controlItem.sId, sNewParentAllId);
            // controlRow.dPartsQty = dProductQty;
            controlData.push(controlRow);

            /* 复制到时增加合版表 */
            if (commonUtils.isNotEmptyArr(copyTo.packData)) {
              await copyTo.packData.filter(item => item.sControlId === controlItem.sId).forEach(async packItem => {
                newCopyTo.pack = packItem;
                let packRow = commonFunc.getDefaultData(config.packConfig, newCopyTo); // 取默认值
                packRow = {
                  ...packRow,
                  ...commonFunc.getAssignFieldValue(packAssignField, packItem, newCopyTo),
                }; // 取赋值字段
                packRow.sOriginalId = packItem.sId; /* 翻单前的sId */
                /* sSlaveId赋值 */
                const iSlaveIndex = slaveData.findIndex(item => item.sOriginalId === packItem.sSlaveId || item.sOrderSlaveId === packItem.sSlaveId);
                if (iSlaveIndex > -1) {
                  const slaveDataRow = slaveData[iSlaveIndex];
                  const packRowAdd = props.handlePackDataAdd(slaveDataRow, 0, controlRow.sId, "add");
                  if (commonUtils.isNotEmptyObject(packRowAdd)) {
                    packRow = { ...packRow, ...packRowAdd };

                    /* 将控制表中的合版备注sId为新的sId */
                    let JsonData = [];
                    const jsonStr = controlRow.sCombinedMemo;
                    if (commonUtils.isNotEmptyObject(jsonStr) && commonUtils.isJSON(jsonStr)) {
                      JsonData = JSON.parse(jsonStr);
                      if (commonUtils.isNotEmptyArr(JsonData)) {
                        let sCombinedMemoNew = "";
                        JsonData.forEach((item, index) => {
                          if (item.sId === packItem.sId) {
                            JsonData[index].sId = packRow.sId;
                          }
                        });
                        sCombinedMemoNew = JSON.stringify(JsonData);
                        controlRow.sCombinedMemo = sCombinedMemoNew;
                        const icontrolIndex = controlData.findIndex(item => item.sId === controlRow.sId);
                        if (icontrolIndex) {
                          controlData[icontrolIndex] = {
                            ...controlData[icontrolIndex],
                            sCombinedMemo: sCombinedMemoNew,
                          };
                        }
                      }
                    }

                    packData.push(packRow);
                  }
                }
              });
            }

            if (commonUtils.isNotEmptyArr(copyTo.processData) && commonUtils.isNotEmptyObject(processAssignField)) {
              copyTo.processData.filter(item => item.sControlId === controlItem.sId && item.sType !== "3").forEach(processItem => {
                newCopyTo.process = processItem;
                let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                processRow = {
                  ...processRow,
                  ...commonFunc.getAssignFieldValue(processAssignField, processItem, newCopyTo),
                }; // 取赋值字段
                processRow.handleType = "add";
                processRow.sId = commonUtils.createSid();
                processRow.sParentId = masterData.sId;
                processRow.sControlId = controlRow.sId;
                processRow.sPartsName = controlRow.sPartsName;
                processRow.sType = processItem.sType;
                /* 根据合版表的源sOriginalId找到新sId */
                let sNewIds = "";
                let sNewNames = "";
                const sOldIds = processItem.sCombinePartsName;
                if (commonUtils.isNotEmptyObject(sOldIds)) {
                  const sOldArr = sOldIds.split(",");
                  for (const sId of sOldArr) {
                    const index = packData.findIndex(item => item.sOriginalId === sId);
                    if (index > -1) {
                      const tableDataRow = packData[index];
                      sNewIds += `${tableDataRow.sId},`;
                      sNewNames += `${tableDataRow.sCustomerName}-${tableDataRow.sProductName}-${tableDataRow.sCombinePartsName},`;
                    }
                  }
                  sNewIds = commonUtils.isNotEmptyObject(sNewIds) ? sNewIds.substr(0, sNewIds.length - 1) : "";
                  sNewNames = commonUtils.isNotEmptyObject(sNewNames) ? sNewNames.substr(0, sNewNames.length - 1) : "";
                }
                processRow.sCombinePartsName = sNewIds;
                processRow.sCombinePartsNameNew = sNewNames;
                processData.push(processRow);
                if (bProcessAssort) {
                  returnProcessAssort.filter(item => item.sParentId === processRow.sProcessId).forEach(itemProcessAssort => {
                    const iIndex = dropDownDataProcessName.findIndex(item => item.sId === itemProcessAssort.sProcessId);
                    const iProcessIndex = copyTo.processData.findIndex(
                      item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === controlItem.sId
                    );
                    const iNewProcessIndex = processData.findIndex(
                      item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === controlRow.sId
                    );
                    if (iIndex > -1 && iProcessIndex < 0 && iNewProcessIndex < 0) {
                      let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                      processRow = {
                        ...processRow,
                        ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                      }; // 取赋值字段
                      processRow.handleType = "add";
                      processRow.sId = commonUtils.createSid();
                      processRow.sParentId = masterData.sId;
                      processRow.sControlId = controlRow.sId;
                      processRow.sPartsName = controlRow.sPartsName;
                      processRow.sType = dropDownDataProcessName[iIndex].sType;
                      processData.push(processRow);
                    }
                  });
                }
              });
            }

            if (commonUtils.isNotEmptyArr(copyTo.materialsData) && commonUtils.isNotEmptyObject(materialsAssignField)) {
              await copyTo.materialsData.filter(item => item.sControlId === controlItem.sId && item.sType !== "2").forEach(async materialsItem => {
                newCopyTo.materials = materialsItem;
                let materialsRow = commonFunc.getDefaultData(config.materialsConfig, newCopyTo); // 取默认值
                materialsRow = {
                  ...materialsRow,
                  ...commonFunc.getAssignFieldValue(materialsAssignField, materialsItem, newCopyTo),
                }; // 取赋值字段
                materialsRow.handleType = "add";
                materialsRow.sId = commonUtils.createSid();
                materialsRow.sParentId = masterData.sId;
                materialsRow.sControlId = controlRow.sId;
                materialsRow.sPartsName = controlRow.sPartsName;
                materialsRow.sType = materialsItem.sType;
                if (
                  Object.keys(materialsRow).length > 0 &&
                  Object.keys(materialsRow).findIndex(item => item === "dMaterialsStockAuxiliaryQty") > -1
                ) {
                  const urlMaterialsStock = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
                  const valueMaterialsStock = {
                    sProName: "Sp_Inventory_MaterialsInventoryV56",
                    paramsMap: {
                      sMaterialsGuid: materialsRow.sMaterialsId,
                      sMaterialsStyle: materialsRow.sMaterialsStyle,
                      sWarehouseGuid: materialsRow.sWarehouseId,
                      sLocationalGuid: materialsRow.sLocationId,
                      sWarehouseLocationGuid: materialsRow.sWarehouseLocationId,
                      sDefine_no: materialsRow.sDefineNo,
                      sDefine_no2: materialsRow.sDefineNo2,
                      iGetQty: 1,
                      iHasZero: 1,
                    },
                  };
                  const returnDataMaterialsStock = (await commonServices.postValueService(app.token, valueMaterialsStock, urlMaterialsStock)).data;
                  if (returnDataMaterialsStock.code === 1) {
                    materialsRow.dMaterialsStockAuxiliaryQty = returnDataMaterialsStock.dataset.rows[0].dataSet.outData[0].dAuxiliaryQty;
                  }
                }
                if (
                  Object.keys(materialsRow).length > 0 &&
                  Object.keys(materialsRow).findIndex(item => item === "dMaterialsStockAvailableQty") > -1
                ) {
                  const urlMaterialsAvailableQty = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
                  const valueMaterialsAvailableQty = {
                    sProName: "Sp_Inventory_MaterialsInventoryV56",
                    paramsMap: {
                      sMaterialsGuid: materialsRow.sMaterialsId,
                      sMaterialsStyle: materialsRow.sMaterialsStyle,
                      sWarehouseGuid: materialsRow.sWarehouseId,
                      sLocationalGuid: materialsRow.sLocationId,
                      sWarehouseLocationGuid: materialsRow.sWarehouseLocationId,
                      sDefine_no: materialsRow.sDefineNo,
                      sDefine_no2: materialsRow.sDefineNo2,
                      iGetQty: 2,
                      iHasZero: 1,
                    },
                  };
                  const returnDataMaterialsAvailableQty = (await commonServices.postValueService(
                    app.token,
                    valueMaterialsAvailableQty,
                    urlMaterialsAvailableQty
                  )).data;
                  if (returnDataMaterialsAvailableQty.code === 1) {
                    materialsRow.dMaterialsStockAvailableQty = returnDataMaterialsAvailableQty.dataset.rows[0].dataSet.outData[0].dAuxiliaryQty;
                  }
                }
                // 材料对应工序的ID要变化
                if (commonUtils.isNotEmptyArr(copyTo.processData)) {
                  const iProcessIndex = processData.findIndex(
                    item => item.sControlId === controlRow.sId && item.sSrcProcessTbId === materialsItem.sProcessTbId
                  );
                  if (iProcessIndex > -1) {
                    materialsRow.sProcessTbId = processData[iProcessIndex].sId;
                  }
                }
                materialsData.push(materialsRow);
              });
            }
          });
        }

        if (commonUtils.isNotEmptyArr(copyTo.materialsData) && commonUtils.isNotEmptyObject(materialsAssignField)) {
          await copyTo.materialsData.filter(item => item.sType === "2").forEach(async materialsItem => {
            newCopyTo.materials = materialsItem;
            let materialsRow = commonFunc.getDefaultData(config.materialsConfig, newCopyTo); // 取默认值
            materialsRow = {
              ...materialsRow,
              ...commonFunc.getAssignFieldValue(materialsAssignField, materialsItem, newCopyTo),
            }; // 取赋值字段
            materialsRow.handleType = "add";
            materialsRow.sId = commonUtils.createSid();
            materialsRow.sParentId = masterData.sId;
            materialsRow.sType = materialsItem.sType;

            /* 根据从表源sOriginalId找到新sId */
            let sNewIds = "";
            let sNewNames = "";
            const sOldIds = materialsItem.sCombinePartsName;
            if (commonUtils.isNotEmptyObject(sOldIds)) {
              const sOldArr = sOldIds.split(",");
              for (const sId of sOldArr) {
                const index = slaveData.findIndex(item => item.sOriginalId === sId);
                if (index > -1) {
                  const tableDataRow = slaveData[index];
                  sNewIds += `${tableDataRow.sId},`;
                  sNewNames += `${tableDataRow.sProductName},`;
                }
              }
              sNewIds = commonUtils.isNotEmptyObject(sNewIds) ? sNewIds.substr(0, sNewIds.length - 1) : "";
              sNewNames = commonUtils.isNotEmptyObject(sNewNames) ? sNewNames.substr(0, sNewNames.length - 1) : "";
            }
            materialsRow.sCombinePartsName = sNewIds;
            materialsRow.sCombinePartsNameNew = sNewNames;
            materialsData.push(materialsRow);
          });
        }

        if (commonUtils.isNotEmptyArr(copyTo.processData) && commonUtils.isNotEmptyObject(processAssignField)) {
          copyTo.processData.filter(item => item.sType === "3").forEach(processItem => {
            newCopyTo.process = processItem;
            let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
            processRow = {
              ...processRow,
              ...commonFunc.getAssignFieldValue(processAssignField, processItem, newCopyTo),
            }; // 取赋值字段
            processRow.handleType = "add";
            processRow.sId = commonUtils.createSid();
            processRow.sParentId = masterData.sId;
            processRow.sType = processItem.sType;
            /* 根据从表的源sOriginalId找到新sId */
            let sNewIds = "";
            let sNewNames = "";
            const sOldIds = processItem.sCombinePartsName;
            if (commonUtils.isNotEmptyObject(sOldIds)) {
              const sOldArr = sOldIds.split(",");
              if (sModelsType.includes("workOrderSet")) {
                /* 通用工单的合版部件名称来自于控制表，复制到时需换成新生成的控制表sId */
                const controlFilterData = controlData.filter(item => sOldArr.includes(item.sOriginalId));
                if (commonUtils.isNotEmptyArr(controlFilterData)) {
                  controlFilterData.forEach(item => {
                    sNewIds += `${item.sId},`;
                    sNewNames += `${item.sPartsName},`;
                  });
                }
              } else {
                for (const sId of sOldArr) {
                  const index = slaveData.findIndex(item => item.sOriginalId === sId);
                  if (index > -1) {
                    const tableDataRow = slaveData[index];
                    sNewIds += `${tableDataRow.sId},`;
                    sNewNames += `${tableDataRow.sCustomerName}-${tableDataRow.sProductName},`;
                  }
                }
              }
              sNewIds = commonUtils.isNotEmptyObject(sNewIds) ? sNewIds.substr(0, sNewIds.length - 1) : "";
              sNewNames = commonUtils.isNotEmptyObject(sNewNames) ? sNewNames.substr(0, sNewNames.length - 1) : "";
            }
            processRow.sCombinePartsName = sNewIds;
            processRow.sCombinePartsNameNew = sNewNames;
            processData.push(processRow);

            if (bProcessAssort) {
              returnProcessAssort.filter(item => item.sParentId === processRow.sProcessId).forEach(itemProcessAssort => {
                const iIndex = dropDownDataProcessName.findIndex(item => item.sId === itemProcessAssort.sProcessId);
                const iProcessIndex = copyTo.processData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId);
                const iNewProcessIndex = processData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId);
                if (iIndex > -1 && iProcessIndex < 0 && iNewProcessIndex < 0) {
                  if (itemProcessAssort.sType === "single") {
                    let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                    processRow = {
                      ...processRow,
                      ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                    }; // 取赋值字段
                    processRow.handleType = "add";
                    processRow.sId = commonUtils.createSid();
                    processRow.sParentId = masterData.sId;
                    processRow.sType = dropDownDataProcessName[iIndex].sType;
                    processData.push(processRow);
                  } else if (itemProcessAssort.sType === "all") {
                    controlData.forEach(controlItem => {
                      let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                      processRow = {
                        ...processRow,
                        ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                      }; // 取赋值字段
                      processRow.handleType = "add";
                      processRow.sId = commonUtils.createSid();
                      processRow.sParentId = masterData.sId;
                      processRow.sControlId = controlItem.sId;
                      processRow.sPartsName = controlItem.sPartsName;
                      processRow.sType = dropDownDataProcessName[iIndex].sType;
                      processData.push(processRow);
                    });
                  }
                }
              });
            }
          });
        }
        if (commonUtils.isNotEmptyArr(copyTo.colorData)) {
          if (commonUtils.isNotEmptyObject(config.colorConfig)) {
            copyTo.colorData.forEach(colorItem => {
              newCopyTo.color = colorItem;
              let colorRow = commonFunc.getDefaultData(config.colorConfig, newCopyTo); // 取默认值
              colorRow = {
                ...colorRow,
                ...commonFunc.getAssignFieldValue(colorAssignField, colorItem, newCopyTo),
              }; // 取赋值字段
              colorRow.handleType = "add";
              colorRow.sId = commonUtils.createSid();
              colorRow.sParentId = masterData.sId;
              colorData.push(colorRow);
            });
          }
        }

        if (commonUtils.isNotEmptyArr(copyTo.visionData)) {
          if (commonUtils.isNotEmptyObject(config.visionConfig)) {
            copyTo.visionData.forEach(visionItem => {
              newCopyTo.vision = visionItem;
              let visionRow = commonFunc.getDefaultData(config.visionConfig, newCopyTo); // 取默认值
              visionRow = {
                ...visionRow,
                ...commonFunc.getAssignFieldValue(visionAssignField, visionItem, newCopyTo),
              }; // 取赋值字段
              visionRow.handleType = "add";
              visionRow.sId = commonUtils.createSid();
              visionRow.sParentId = masterData.sId;
              visionData.push(visionRow);
            });
          }
        }
      }
      if (controlData.length === 0) {
        if (!commonUtils.isEmpty(slaveData[0].sProductId)) {
          const iIndex = config.slaveConfig.gdsconfigformslave.findIndex(item => item.sName === "sProductName");
          if (iIndex > -1) {
            const sqlDropDownData = await props.getSqlDropDownData(sModelsId, "slave", config.slaveConfig.gdsconfigformslave[iIndex]);
            const dropDownData = sqlDropDownData.dropDownData;
            const [changeData] = dropDownData.filter(item => item.sProductId === slaveData[0].sProductId);
            const sParentId = commonUtils.isEmpty(changeData) ? "" : changeData.sParentId;
            if (!commonUtils.isEmpty(sParentId)) {
              const iIndex = config.masterConfig.gdsconfigformslave.findIndex(item => item.sName === "sProductClassifyName");
              if (iIndex > -1) {
                let dProductQty = 0;
                slaveData.forEach(item => {
                  if (dProductQty) {
                    dProductQty += commonUtils.isNull(item.dProductQty, 0);
                  } else {
                    dProductQty +=
                      commonUtils.isNull(item.dProductQty, 0) + commonUtils.isNull(item.dGiveQty, 0) + commonUtils.isNull(item.dStockupQty, 0);
                  }
                });
                const sqlDropDownData = await props.getSqlDropDownData(sModelsId, "master", config.masterConfig.gdsconfigformslave[iIndex]);
                const dropDownData = sqlDropDownData.dropDownData;
                const [changeData] = dropDownData.filter(item => item.sId === sParentId);
                const sAllPartsName = commonUtils.isEmpty(changeData) ? "" : changeData.sAllPartsName;
                if (commonUtils.isNotEmptyStr(sAllPartsName)) {
                  const sAssignFieldObj = sAllPartsName.split(",");
                  for (const child of sAssignFieldObj) {
                    let allTableData = {};
                    allTableData = {};
                    allTableData.master = masterData;
                    allTableData.slave = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0];
                    const tableDataRow = commonFunc.getDefaultData(config.controlConfig, allTableData);
                    tableDataRow.handleType = "add";
                    tableDataRow.sId = commonUtils.createSid();
                    tableDataRow.sParentId = masterData && masterData.sId ? masterData.sId : null;
                    tableDataRow.key = tableDataRow.sId;
                    tableDataRow.bDefault = false;
                    tableDataRow.iOrder = 0;
                    tableDataRow.sPartsName = child;
                    tableDataRow.dPartsQty = dProductQty;
                    tableDataRow.sAllId = tableDataRow.sId; /* 第一级sAllId等于sId */
                    controlData.push(tableDataRow);
                  }
                }
              }
            }
          }
        }
      } else {
        processData = props.sortData(controlData, processData);
      }
    }
    if (controlData.length === 0) {
      const allTableData = {};
      allTableData.master = masterData;
      allTableData.slave = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0];
      const tableDataRow = commonFunc.getDefaultData(config.controlConfig, allTableData);
      tableDataRow.handleType = "add";
      tableDataRow.sId = commonUtils.createSid();
      tableDataRow.sNodeId = commonUtils.createSid();
      tableDataRow.sParentId = masterData && masterData.sId ? masterData.sId : null;
      tableDataRow.key = tableDataRow.sId;
      tableDataRow.bDefault = false;
      tableDataRow.iOrder = 1; /* 序号从1开始 */
      tableDataRow.sCombinedMemo = "合版信息";
      tableDataRow.sAllId = tableDataRow.sId;

      if (commonUtils.isEmptyObject(tableDataRow.sPartsName)) {
        tableDataRow.sPartsName = commonUtils.isNotEmptyArr(slaveData) ? slaveData[0].sProductName : "";
      }

      const bProductQtySelf = masterConfig.gdsconfigformslave.some(item => item.sControlName === "bProductQtySelf");

      let dProductQty = 0;
      slaveData.forEach(item => {
        if (bProductQtySelf) {
          dProductQty += commonUtils.isNull(item.dProductQty, 0);
        } else {
          dProductQty += commonUtils.isNull(item.dProductQty, 0) + commonUtils.isNull(item.dGiveQty, 0) + commonUtils.isNull(item.dStockupQty, 0);
        }
      });
      tableDataRow.dPartsQty = dProductQty;
      /* 点击新增按钮 控制表自动默认增一条 同时默认新增一条合版表 */
      if (commonUtils.isNotEmptyArr(slaveData) && slaveData.length === 1 && commonUtils.isEmptyArr(packData)) {
        const packDataRow = props.handlePackDataAdd(slaveData[0], 0, tableDataRow.sId, "add");
        packDataRow.dCombineQty = 1; /* 排版数 */
        if (commonUtils.isNotEmptyObject(packDataRow) && commonUtils.isNotEmptyObject(packDataRow.sProductId)) {
          /* 从表要选择产品 */
          const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty, sCombinePartsName } = packDataRow;
          const tableCombineSelectedData = [];
          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; /* 合版部件名称 */
          tableCombineSelectedData.push(jsonObj);
          const sCombinedMemo = commonUtils.isNotEmptyArr(tableCombineSelectedData)
            ? JSON.stringify(tableCombineSelectedData)
            : ""; /* JSON对象转换为字符串存放到合版信息中 */
          tableDataRow.sCombinedMemo = commonUtils.isNotEmptyObject(sCombinedMemo) ? sCombinedMemo : "合版信息";
        }
        packData.push(packDataRow);
      }
      controlData.push(tableDataRow);
    }
    const treeState = { treeData: [] }; /* 加载树形结构数据 */
    const stateNew = {
      ...state,
      ...treeState,
      slaveData,
      controlData,
      controlSelectedRowKeys: [],
      packData,
      packSelectedRowKeys: [],
      materialsData,
      materials0Data: materialsData,
      materialsSelectedRowKeys: [],
      processData,
      processSelectedRowKeys: [],
      colorData,
      colorSelectedRowKeys: [],
      visionData,
      visionSelectedRowKeys: [],
      checkProcessClassifyData: [],
    };
    if (isWait) {
      return stateNew;
    } else {
      props.onSaveState(stateNew);
    }
  };

  // 表格添加表格空行
  const handleTableAdd = (...args) => {
    const [name0] = args;
    const name = name0.includes("materials") ? "materials" : name0;
    dispatchFunc(name, "onDataRowAdd", ["name", "flag", "bchild", "bFinished", "bModalAdd"], args);
  };
  returnProps.onDataRowAdd = handleTableAdd;

  // 删除表格数据
  const handleTableDel = (...args) => {
    const [name0] = args;
    const name = name0.includes("materials") ? "materials" : name0;
    dispatchFunc(name, "onDataRowDel", ["name", "flag", "tableSelectedRowKeys"], args);
  };
  returnProps.onDataRowDel = handleTableDel;

  // 从表数据变化
  const handleTableChange = (...args) => {
    const [name0] = args;
    const name = name0.includes("materials") ? "materials" : name0;
    dispatchFunc(name, "onDataChange", ["name", "sFieldName", "changeValue", "sId", "dropDownData"], args);
  };
  returnProps.onDataChange = handleTableChange;

  const handleTableSelectRowChange = (...args) => {
    const [name0] = args;
    const name = name0.includes("materials") ? "materials" : name0;
    dispatchFunc(name, "onTableSelectRowChange", ["name", "selectedRowKeys"], args);
  };
  returnProps.onTableSelectRowChange = handleTableSelectRowChange;

  // 各种超链接点击
  const handleViewChoose = (...args) => {
    const [name0] = args;
    const name = name0.includes("materials") ? "materials" : name0;
    dispatchFunc(name, "onViewChoose", ["name", "sName", "record"], args);
  };
  returnProps.onViewChoose = handleViewChoose;

  // toolbar按钮操作事件
  const handleButtonClick = async name => {
    if (name === "BtnCalculation") {
      props.onSaveState({
        loading: true,
      });
      props.handleCalculation("workOrder");
    } else if (name === "BtnChooseProcess") {
      const { slaveData, controlData, slaveSelectedRowKeys, masterConfig, app } = props;
      if (commonUtils.isEmptyArr(slaveData)) {
        message.error(commonFunc.showMessage(app.commonConst, "NoSlaveData")); /* 请填写从表数据 */
        return;
      }
      const slaveSelectedData = slaveData.filter(item => item.sId === slaveSelectedRowKeys[0]);
      if (commonUtils.isEmptyArr(slaveSelectedData)) {
        message.error(commonFunc.showMessage(app.commonConst, "pleaseChooseSlaveData")); /* 请选择从表数据 */
        return;
      }
      if (commonUtils.isEmptyStr(slaveSelectedData[0].sProductId)) {
        message.error(commonFunc.showMessage(app.commonConst, "pleaseChooseProduct")); /* 请选择产品 */
        return;
      }
      if (commonUtils.isEmptyObject(controlData)) {
        message.error(commonFunc.showMessage(app.commonConst, "NoControlData")); /* 请填写控制表数据 */
        return;
      }
      const iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === name);
      if (iIndex > -1) {
        props.onBtnChoose("process", name, masterConfig.gdsconfigformslave[iIndex]);
      }
    } else if (name === "BtnChooseMaterials") {
      const { slaveData, controlData, slaveSelectedRowKeys, masterConfig, app } = props;
      if (commonUtils.isEmptyArr(slaveData)) {
        message.error(commonFunc.showMessage(app.commonConst, "NoSlaveData")); /* 请填写从表数据 */
        return;
      }
      const slaveSelectedData = slaveData.filter(item => item.sId === slaveSelectedRowKeys[0]);
      if (commonUtils.isEmptyArr(slaveSelectedData)) {
        message.error(commonFunc.showMessage(app.commonConst, "pleaseChooseSlaveData")); /* 请选择从表数据 */
        return;
      }
      if (commonUtils.isEmptyStr(slaveSelectedData[0].sProductId)) {
        message.error(commonFunc.showMessage(app.commonConst, "pleaseChooseProduct")); /* 请选择产品 */
        return;
      }
      if (commonUtils.isEmptyObject(controlData)) {
        message.error(commonFunc.showMessage(app.commonConst, "NoControlData")); /* 请填写控制表数据 */
        return;
      }
      const iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === name);
      if (iIndex > -1) {
        props.onBtnChoose("materials", name, masterConfig.gdsconfigformslave[iIndex]);
      }
    } else if (name === "BtnCombine") {
      const { slaveData: slaveDataOld, controlData: controlDataOld } = props;
      let dMaxQty = 0;
      let dSumMachineQty = 0;
      slaveDataOld.forEach(item => {
        if (commonUtils.isEmpty(item.dCombineQty) || item.dCombineQty === 0 ? 0 : item.dSrcQty / item.dCombineQty > dMaxQty) {
          dMaxQty = Math.ceil(commonUtils.isEmpty(item.dCombineQty) || item.dCombineQty === 0 ? 0 : item.dSrcQty / item.dCombineQty);
        }
      });
      const controlData = [];
      if (commonUtils.isNotEmptyArr(controlDataOld)) {
        controlDataOld.forEach(item => {
          let controlRow = { ...item, dPartsQty: dMaxQty };
          controlRow = props.singlePQtyChange(controlRow);
          controlData.push(controlRow);
        });
        dSumMachineQty = controlData[0].dSumMachineQty;
      }
      const slaveData = [];
      slaveDataOld.forEach(item => {
        slaveData.push({ ...item, dProductQty: dSumMachineQty * item.dCombineQty });
      });
      props.onSaveState({ slaveData, controlData });
    } else if (name === "BtnDraft") {
      const {
        masterConfig,
        masterData,
        slaveConfig,
        slaveData,
        slaveDelData,
        controlConfig,
        controlData,
        controlDelData,
        materialsConfig,
        materials0Data : materialsData,
        materialsDelData,
        processConfig,
        processData,
        processDelData,
        colorConfig,
        colorData,
        colorDelData,
        packConfig,
        packData,
        packDelData,
      } = props;
      const data = [];
      slaveConfig.gdsconfigformslave.forEach(itemConfig => {
        slaveData.filter(itemData => itemData.handleType === "add" || itemData.handleType === "update").forEach(itemData => {
          itemData.NoVerify = "NoVerify";
          const firstDataIndex = itemConfig.sName.substring(0, 1);
          if (commonUtils.isEmpty(itemData[itemConfig.sName])) {
            itemData[itemConfig.sName] =
              firstDataIndex === "s"
                ? ""
                : firstDataIndex === "d" || firstDataIndex === "i"
                  ? 0
                  : firstDataIndex === "b"
                    ? false
                    : firstDataIndex === "t"
                      ? moment(new Date()).format(props.app.dateFormat)
                      : undefined;
          }
        });
      });
      controlConfig.gdsconfigformslave.forEach(itemConfig => {
        controlData.filter(itemData => itemData.handleType === "add" || itemData.handleType === "update").forEach(itemData => {
          itemData.NoVerify = "NoVerify";
          const firstDataIndex = itemConfig.sName.substring(0, 1);
          if (commonUtils.isEmpty(itemData[itemConfig.sName])) {
            itemData[itemConfig.sName] =
              firstDataIndex === "s"
                ? ""
                : firstDataIndex === "d" || firstDataIndex === "i"
                  ? 0
                  : firstDataIndex === "b"
                    ? false
                    : firstDataIndex === "t"
                      ? moment(new Date()).format(props.app.dateFormat)
                      : undefined;
          }
        });
      });

      materialsConfig.gdsconfigformslave.forEach(itemConfig => {
        materialsData.filter(itemData => itemData.handleType === "add" || itemData.handleType === "update").forEach(itemData => {
          itemData.NoVerify = "NoVerify";
          const firstDataIndex = itemConfig.sName.substring(0, 1);
          if (commonUtils.isEmpty(itemData[itemConfig.sName])) {
            itemData[itemConfig.sName] =
              firstDataIndex === "s"
                ? ""
                : firstDataIndex === "d" || firstDataIndex === "i"
                  ? 0
                  : firstDataIndex === "b"
                    ? false
                    : firstDataIndex === "t"
                      ? moment(new Date()).format(props.app.dateFormat)
                      : undefined;
          }
        });
      });

      processConfig.gdsconfigformslave.forEach(itemConfig => {
        processData.filter(itemData => itemData.handleType === "add" || itemData.handleType === "update").forEach(itemData => {
          itemData.NoVerify = "NoVerify";
          const firstDataIndex = itemConfig.sName.substring(0, 1);
          if (commonUtils.isEmpty(itemData[itemConfig.sName])) {
            itemData[itemConfig.sName] =
              firstDataIndex === "s"
                ? ""
                : firstDataIndex === "d" || firstDataIndex === "i"
                  ? 0
                  : firstDataIndex === "b"
                    ? false
                    : firstDataIndex === "t"
                      ? moment(new Date()).format(props.app.dateFormat)
                      : undefined;
          }
        });
      });

      if (commonUtils.isNotEmptyObject(packConfig)) {
        packConfig.gdsconfigformslave.forEach(itemConfig => {
          packData.filter(itemData => itemData.handleType === "add" || itemData.handleType === "update").forEach(itemData => {
            itemData.NoVerify = "NoVerify";
            const firstDataIndex = itemConfig.sName.substring(0, 1);
            if (commonUtils.isEmpty(itemData[itemConfig.sName])) {
              itemData[itemConfig.sName] =
                firstDataIndex === "s"
                  ? ""
                  : firstDataIndex === "d" || firstDataIndex === "i"
                    ? 0
                    : firstDataIndex === "b"
                      ? false
                      : firstDataIndex === "t"
                        ? moment(new Date()).format(props.app.dateFormat)
                        : undefined;
            }
          });
        });
      }

      if (commonUtils.isNotEmptyObject(colorConfig)) {
        colorConfig.gdsconfigformslave.forEach(itemConfig => {
          colorData.filter(itemData => itemData.handleType === "add" || itemData.handleType === "update").forEach(itemData => {
            itemData.NoVerify = "NoVerify";
            const firstDataIndex = itemConfig.sName.substring(0, 1);
            if (commonUtils.isEmpty(itemData[itemConfig.sName])) {
              itemData[itemConfig.sName] =
                firstDataIndex === "s"
                  ? ""
                  : firstDataIndex === "d" || firstDataIndex === "i"
                    ? 0
                    : firstDataIndex === "b"
                      ? false
                      : firstDataIndex === "t"
                        ? moment(new Date()).format(props.app.dateFormat)
                        : undefined;
            }
          });
        });
      }

      data.push(commonBusiness.mergeData("master", masterConfig.sTbName, [masterData]));
      data.push(commonBusiness.mergeData("slave", slaveConfig.sTbName, slaveData, slaveDelData));
      data.push(commonBusiness.mergeData("control", controlConfig.sTbName, controlData, controlDelData));
      data.push(commonBusiness.mergeData("materials", materialsConfig.sTbName, materialsData, materialsDelData));
      data.push(commonBusiness.mergeData("process", processConfig.sTbName, processData, processDelData));
      if (commonUtils.isNotEmptyObject(colorConfig)) {
        data.push(commonBusiness.mergeData("color", colorConfig.sTbName, colorData, colorDelData));
      }
      if (commonUtils.isNotEmptyObject(packConfig)) {
        data.push(commonBusiness.mergeData("pack", packConfig.sTbName, packData, packDelData));
      }
      props.onSaveData({
        data,
        sClientType: "1",
        loading: false,
        sSysLogSrcId: masterData.sId,
        bIsUnCcg: false,
      });
    } else if (name === "BtnWorkFlow") {
      const dataUrl = `${commonConfig.server_host}workOrderFlow/getWorkOrderFlow/`;
      let { token } = props.app;
      let { slaveData, controlData, materials0Data, processData, packData } = props;
      const value = {
        slave: slaveData,
        control: controlData,
        materials: materials0Data,
        process: processData,
        pack: packData,
      };
      let dataReturn = (await commonServices.postValueService(token, value, dataUrl)).data;
      if (commonUtils.isNotEmptyObject(dataReturn)) {
        if (dataReturn.code === 1) {
          const flowData = dataReturn.dataset.rows[0];
          console.log(flowData);
          if (commonUtils.isNotEmptyObject(flowData)) {
            props.onSaveState({
              flowData: flowData,
              workFlowVisible: true,
            });
          }
        } else {
          props.getServiceError(dataReturn);
        }
      }
    } else {
      props.onButtonClick(name);
    }
  };
  returnProps.onButtonClick = handleButtonClick;

  // 复制到
  const handleCopyTo = async (name, sActiveId) => {
    /*   待用数据声明   */
    const {
      masterConfig,
      masterData,
      slaveData,
      controlData,
      materials0Data,
      processData,
      colorData,
      sModelsId,
      packData,
      visionData,
      formRoute,
    } = props;

    const handleDispatch = (copyTo, sActiveId) => {
      const { dispatch } = props;
      dispatch({
        type: "content/onRouter",
        payload: {
          url: `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}` /*   接口地址   */,
          sSrcModelsId: props.sModelsId,
          copyTo,
        },
      });
    };

    // 从表有sCopyToCondition则不能复制，并提示
    if (commonUtils.isNotEmptyArr(slaveData) && name.includes(".")) {
      const sCopyToConditionIndex = slaveData.findIndex(item => item.sCopyToCondition);
      if (sCopyToConditionIndex !== -1) {
        message.warning(slaveData[sCopyToConditionIndex].sCopyToCondition);
        return;
      }
    }

    const copyTo = {};
    const copyToConfig = masterConfig.gdsconfigformslave.filter(item => item.sControlName.includes(name));
    copyTo.name = name;
    copyTo.config = copyToConfig;
    copyTo.masterData = masterData;
    copyTo.slaveData = slaveData;
    copyTo.controlData = controlData;
    copyTo.materialsData = materials0Data;
    copyTo.materials0Data = materials0Data;
    copyTo.processData = processData;
    copyTo.packData = packData;
    copyTo.colorData = colorData;
    copyTo.visionData = visionData;
    copyTo.srcFormRoute = formRoute;
    const tbSuffix = "";
    let sId = "";
    if (!commonUtils.isEmpty(slaveData)) {
      sId = slaveData[0].sId;
    }

    const dataUrl = `${commonConfig.server_host
      }bill/billCopyToCheck/?sModelsId=${sModelsId}&sActiveId=${sActiveId}&tbSuffix=${tbSuffix}&sName=${formRoute}`;
    const values = { sSlaveId: sId };
    const dataReturn = (await commonServices.postValueService(token, values, dataUrl)).data;
    if (dataReturn.code === 1) {
      if (dataReturn.dataset.rows.length > 0) {
        Modal.confirm({
          title: commonFunc.showMessage(app.commonConst, "beUsedToNew") /* 单据已存在，是否填写新单据 */,
          onOk() {
            handleDispatch(copyTo, sActiveId);
          },
          onCancel() { },
        });
      } else {
        handleDispatch(copyTo, sActiveId);
      }
    }
  };
  returnProps.onCopyTo = handleCopyTo;

  // 弹窗选择确定
  const handleSelect = async (name, selectConfig, selectData) => {
    if (name === "materials") {
      name = "materials0";
    }
    const {
      [`${name}Data`]: tableData,
      [`${name}Config`]: tableConfig,
      masterConfig,
      controlSelectedRowKeys,
      processSelectedRowKeys,
      sModelsId,
      token,
      slaveConfig,
      controlConfig,
      materialsConfig,
      processConfig,
      colorConfig,
      packConfig,
      slaveData,
      controlData: controlDataOld,
      materials0Data: materialsDataOld,
      processData: processDataOld,
      colorData: colorDataOld,
      packData: packDataOld,
      controlDelData: controlDelDataOld,
      materials0DelData: materialsDelDataOld,
      processDelData: processDelDataOld,
      colorDelData: colorDelDataOld,
      packDelData: packDelDataOld,
    } = props;
    let { masterData, slaveSelectedRowKeys } = props;
    const bTmpInfoBySql = selectConfig?.sControlName?.toLowerCase().includes("tmpinfobysql");
    if (name === "productProcessInfo" && !bTmpInfoBySql) {
      message.info("productProcessInfo已废弃，请改成TmpInfoBySql！");
      return;
    }
    if (bTmpInfoBySql) {
      /* 复制从部件 根据配置下拉sql获取数据源 通过按钮名称是否包含add来判断数据源新增还是删除 */
      const addState = {};
      let controlData = commonUtils.isEmptyArr(controlDataOld) ? [] : controlDataOld;
      let materialsData = commonUtils.isEmptyArr(materialsDataOld) ? [] : materialsDataOld;
      let processData = commonUtils.isEmptyArr(processDataOld) ? [] : processDataOld;
      let colorData = commonUtils.isEmptyArr(colorDataOld) ? [] : colorDataOld;
      let packData = commonUtils.isEmptyArr(packDataOld) ? [] : packDataOld;

      const config = {};
      config.masterConfig = masterConfig;
      config.slaveConfig = slaveConfig;
      config.controlConfig = controlConfig;
      config.materialsConfig = materialsConfig;
      config.processConfig = processConfig;
      config.colorConfig = colorConfig;
      config.packConfig = packConfig;

      const dataUrl = `${commonConfig.server_host}salesorder/getTmpInfoBySql/?sModelsId=${sModelsId}`;
      const sConfigformId = commonUtils.isEmpty(selectConfig) ? "" : selectConfig.sParentId;
      const sRowData = selectData;
      const sControlName = selectConfig.sControlName; /* 按钮名称 */
      // const sSqlCondition = { sId: selectData[0].sSlaveId }; /* 后台根据rowData自己取 */
      const condition = { sConfigformId, sControlName, sRowData };
      const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
      console.log("aaaadataReturn", dataReturn);
      if (dataReturn.code === 1) {
        const copyTo = {
          config: masterConfig.gdsconfigformslave,
          name: selectConfig.sControlName,
        };
        const returnDataSet = dataReturn.dataset.rows[0];
        const returnData = {};
        const copyToMasterDetailConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}`.toLowerCase());
        const copyToSlaveDetailConfig = copyTo.config.filter(
          item =>
            item.sControlName
              .toLowerCase()
              .replace("_add", "")
              .replace("_edit", "")
              .trim() === `${copyTo.name}.slave`.toLowerCase()
        );
        const copyToControlConfig = copyTo.config.filter(
          item =>
            item.sControlName
              .toLowerCase()
              .replace("_add", "")
              .replace("_edit", "")
              .trim() === `${copyTo.name}.control`.toLowerCase()
        );
        const copyToMaterialsConfig = copyTo.config.filter(
          item =>
            item.sControlName
              .toLowerCase()
              .replace("_add", "")
              .replace("_edit", "")
              .trim() === `${copyTo.name}.materials`.toLowerCase()
        );
        const copyToProcessConfig = copyTo.config.filter(
          item =>
            item.sControlName
              .toLowerCase()
              .replace("_add", "")
              .replace("_edit", "")
              .trim() === `${copyTo.name}.process`.toLowerCase()
        );
        const copyToPackConfig = copyTo.config.filter(
          item =>
            item.sControlName
              .toLowerCase()
              .replace("_add", "")
              .replace("_edit", "")
              .trim() === `${copyTo.name}.pack`.toLowerCase()
        );
        const masterDetailAssignField = commonUtils.isNotEmptyArr(copyToMasterDetailConfig) ? copyToMasterDetailConfig[0].sAssignField : "";
        const slaveDetailAssignField = commonUtils.isNotEmptyArr(copyToSlaveDetailConfig) ? copyToSlaveDetailConfig[0].sAssignField : "";
        const copyToColorConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.color`.toLowerCase()
          || item.sControlName.toLowerCase() === `${copyTo.name}.param`.toLowerCase());
        const controlAssignField = commonUtils.isNotEmptyArr(copyToControlConfig) ? copyToControlConfig[0].sAssignField : "";
        const materialsAssignField = commonUtils.isNotEmptyArr(copyToMaterialsConfig) ? copyToMaterialsConfig[0].sAssignField : "";
        const processAssignField = commonUtils.isNotEmptyArr(copyToProcessConfig) ? copyToProcessConfig[0].sAssignField : "";
        const colorAssignField = commonUtils.isNotEmptyArr(copyToColorConfig) ? copyToColorConfig[0].sAssignField : "";
        const packAssignField = commonUtils.isNotEmptyArr(copyToPackConfig) ? copyToPackConfig[0].sAssignField : "";

        /* 判断是插入 还是删除  */
        if (commonUtils.isNotEmptyArr(copyToControlConfig)) {
          if (!copyToControlConfig[0].sControlName.includes("_add") && !copyToControlConfig[0].sControlName.includes("_edit")) {
            /* 删除 */
            controlData = [];
            const controlDelData = commonUtils.isEmptyArr(controlDelDataOld) ? [] : controlDelDataOld;
            const controlDataFilterData = controlDataOld.filter(obj => controlSelectedRowKeys.includes(obj.sId));
            if (commonUtils.isNotEmptyArr(controlDataFilterData)) {
              controlDataFilterData.forEach(item => {
                item.handleType = "del";
                controlDelData.push(item);
              });
            }
            addState.controlDelData = controlDelData;
          }
        }
        console.log('333', controlData);

        if (commonUtils.isNotEmptyArr(copyToMaterialsConfig)) {
          if (!copyToMaterialsConfig[0].sControlName.includes("_add") && !copyToMaterialsConfig[0].sControlName.includes("_edit")) {
            /* 删除 */
            materialsData = [];
            const materialsDelData = commonUtils.isEmptyArr(materialsDelDataOld) ? [] : materialsDelDataOld;
            const materialsDataFilterData = materialsDataOld.filter(obj => controlSelectedRowKeys.includes(obj.sControlId));
            if (commonUtils.isNotEmptyArr(materialsDataFilterData)) {
              materialsDataFilterData.forEach(item => {
                item.handleType = "del";
                materialsDelData.push(item);
              });
              addState.materialsDelData = materialsDelData;
            }
          }
        }

        if (commonUtils.isNotEmptyArr(copyToProcessConfig)) {
          if (!copyToProcessConfig[0].sControlName.includes("_add") && !copyToProcessConfig[0].sControlName.includes("_edit")) {
            /* 删除 */
            processData = [];
            const processDelData = commonUtils.isEmptyArr(processDelDataOld) ? [] : processDelDataOld;
            const processDataFilterData = processDataOld.filter(obj => controlSelectedRowKeys.includes(obj.sControlId));
            if (commonUtils.isNotEmptyArr(processDataFilterData)) {
              processDataFilterData.forEach(item => {
                item.handleType = "del";
                processDelData.push(item);
              });
              addState.processDelData = processDelData;
            }
          }
        }

        if (commonUtils.isNotEmptyArr(copyToColorConfig)) {
          if (!copyToColorConfig[0].sControlName.includes("_add") && !copyToColorConfig[0].sControlName.includes("_edit")) {
            /* 删除 */
            colorData = [];
            const colorDelData = commonUtils.isEmptyArr(colorDelDataOld) ? [] : colorDelDataOld;
            if (commonUtils.isNotEmptyArr(colorDataOld) && colorDataOld.length > 0) {
              colorDataOld.forEach(item => {
                item.handleType = "del";
                colorDelData.push(item);
              });
            }
            addState.colorDelData = colorDelData;
          }
        }
        if (commonUtils.isNotEmptyArr(packAssignField)) {
          if (!copyToPackConfig[0].sControlName.includes("_add") && !copyToPackConfig[0].sControlName.includes("_edit")) {
            /* 删除 */
            packData = [];
            const packDelData = commonUtils.isEmptyArr(packDelDataOld) ? [] : packDelDataOld;
            if (commonUtils.isNotEmptyArr(packDataOld) && packDataOld.length > 0) {
              packDataOld.forEach(item => {
                item.handleType = "del";
                packDelData.push(item);
              });
            }
            addState.packDelData = packDelData;
          }
        }

        const newCopyTo = {};
        newCopyTo.master = copyTo.masterData;
        newCopyTo.slave = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0];
        let iSlaveIndex = -1;
        if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
          iSlaveIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys.toString());
        } else if (slaveData.length > 0) {
          iSlaveIndex = 0;
        }

        if (iSlaveIndex > -1) {
          slaveData[iSlaveIndex] = {
            ...slaveData[iSlaveIndex],
            ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, selectData[0], newCopyTo),
          }; // 取赋值字段
        }
        let controlSelectedRow = {}; /* 控制表选中行  */
        let iControlIndex = -1;
        if (!commonUtils.isEmpty(controlSelectedRowKeys)) {
          iControlIndex = controlData.findIndex(item => controlSelectedRowKeys.includes(item.sId));
          if (iControlIndex > -1) {
            controlSelectedRow = controlData[iControlIndex];
          }
        }

        const bProcessAssort = false;
        let returnProcessAssort = [];
        let processAssignAssort = "";
        let dropDownDataProcessName;
        if (bProcessAssort) {
          const dataUrl = `${commonConfig.server_host}salesorder/getProcessAssort?sModelsId=${sModelsId}`;
          const dataProcessAssort = (await commonServices.postValueService(token, {}, dataUrl)).data;
          if (dataProcessAssort.code === 1) {
            returnProcessAssort = dataProcessAssort.dataset.rows[0].processassort;
            const iIndex = config.processConfig.gdsconfigformslave.findIndex(item => item.sName === "sProcessName");
            if (iIndex > -1) {
              const sqlDropDownData = await props.getSqlDropDownData(sModelsId, "slave", config.processConfig.gdsconfigformslave[iIndex]);
              dropDownDataProcessName = sqlDropDownData.dropDownData;
              processAssignAssort = config.processConfig.gdsconfigformslave[iIndex].sAssignField;
            }
          }
        }
        if (commonUtils.isNotEmptyObject(returnDataSet)) {
          /* 数据塞到Data中 */
          for (const key of Object.keys(returnDataSet)) {
            const sName = `${key}Data`;
            returnData[sName] = returnDataSet[key];
          }
        }
        if (commonUtils.isNotEmptyArr(returnData.slaveData)) {
          masterData = {
            ...masterData,
            ...commonFunc.getAssignFieldValue(masterDetailAssignField, returnData.slaveData[0], newCopyTo),
          }; // 取赋值字段
        }
        let dProductQty = 0;
        if (commonUtils.isNotEmptyObject(copyToSlaveDetailConfig)) {
          /* 主表配置bProductQtyAdd 则代表产品数量不叠加备货数 赠送数 */
          let bProductQtySelf = false;
          if (commonUtils.isNotEmptyObject(props.masterConfig) && commonUtils.isNotEmptyArr(props.masterConfig.gdsconfigformslave)) {
            const iIndex = props.masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === "bProductQtySelf");
            if (iIndex > -1) {
              bProductQtySelf = true;
            }
          }

          if (commonUtils.isNotEmptyArr(returnData.slaveData)) {
            returnData.slaveData.forEach((slaveItem, iIndex) => {
              /* 从工艺卡数据集 找到从表相同产品ID,客户ID */
              let iSameIndex = slaveData.findIndex(itemCurrent => itemCurrent.sProductId === slaveItem.sProductId && itemCurrent.sCustomerId === slaveItem.sCustomerId);
              if (iSameIndex === -1) {
                /* 复制从历史工单 只要把数据赋值到选中行即可 */
                iSameIndex = iSlaveIndex;
              }
              if (iSameIndex > -1 && iIndex === 0) { /* 把返回结果集的第一行数据放在选中行上 */
                if (commonUtils.isNotEmptyObject(slaveDetailAssignField)) {
                  slaveData[iSameIndex] = { ...slaveData[iSameIndex], ...commonFunc.getAssignFieldValue(slaveDetailAssignField, slaveItem, newCopyTo) }; // 取赋值字段
                }
                slaveData[iSameIndex].sOriginalId = commonUtils.isNotEmptyObject(slaveItem.sSlaveId) ? slaveItem.sSlaveId : slaveItem.sId;  /* 原始sId */
                if (bProductQtySelf) {
                  dProductQty += commonUtils.isNull(slaveData[iSameIndex].dProductQty, 0);
                } else {
                  dProductQty += commonUtils.isNull(slaveData[iSameIndex].dProductQty, 0) + commonUtils.isNull(slaveData[iSameIndex].dGiveQty, 0) +
                    commonUtils.isNull(slaveData[iSameIndex].dStockupQty, 0);
                }
              } else if (commonUtils.isNotEmptyObject(slaveDetailAssignField)) {
                /* 其他数据 新增 */
                newCopyTo.slave = slaveItem;
                let slaveRow = {};
                slaveRow = {
                  ...slaveRow,
                  ...commonFunc.getAssignFieldValue(slaveDetailAssignField, slaveItem, newCopyTo),
                }; // 取赋值字段
                slaveRow.handleType = "add";
                slaveRow.sId = commonUtils.createSid();
                slaveRow.sParentId = masterData.sId;
                slaveRow.sOriginalId = commonUtils.isNotEmptyObject(slaveItem.sSlaveId) ? slaveItem.sSlaveId : slaveItem.sId; /* 原始sId */
                slaveData.push(slaveRow);
              }
            });
          }
        }
        if (commonUtils.isNotEmptyArr(returnData.controlData) && commonUtils.isNotEmptyObject(controlAssignField)) {
          const treeCopyNodes = new Map();
          returnData.controlData.forEach(controlItem => {
            newCopyTo.control = controlItem;
            let controlRow = commonFunc.getDefaultData(config.controlConfig, newCopyTo); // 取默认值
            if (copyToControlConfig[0].sControlName.includes("_edit")) {
              controlRow = {
                ...controlSelectedRow,
                ...commonFunc.getAssignFieldValue(controlAssignField, controlItem, newCopyTo),
              }; // 取赋值字段
              if (iControlIndex > -1) {
                controlData[iControlIndex] = {
                  ...controlSelectedRow,
                  ...controlRow,
                };
              }
            } else {
              controlRow = {
                ...controlRow,
                ...commonFunc.getAssignFieldValue(controlAssignField, controlItem, newCopyTo),
              }; // 取赋值字段
              controlRow.handleType = "add";
              controlRow.sId = commonUtils.createSid();
              controlRow.sParentId = masterData.sId;
              controlRow.dPartsQty = dProductQty;
              const sAllOldId = controlItem.sAllId;
              let arr = [];
              if (commonUtils.isNotEmptyObject(sAllOldId)) {
                arr = sAllOldId.split(",");
              }
              const newId = controlRow.sId;
              let sOldParentId = "";
              let sNewParentAllId = "";
              if (arr.length < 2) {
                /* 根节点复制 */
                controlRow.sAllId = newId;
                sOldParentId = newId;
                sNewParentAllId = newId;
              } else {
                sOldParentId = arr[arr.length - 2];
                if (treeCopyNodes.has(sOldParentId)) {
                  sNewParentAllId = treeCopyNodes.get(sOldParentId);
                } else {
                  const obj = arr[arr.length - 1];
                  sNewParentAllId = sAllOldId.replace(`,${obj}`, "");
                }
                const sNewArr = sNewParentAllId.split(",");
                controlRow.sControlParentId = sNewArr[sNewArr.length - 1];
                sNewParentAllId = `${sNewParentAllId},${newId}`;
                controlRow.sAllId = sNewParentAllId;
              }
              treeCopyNodes.set(controlItem.sId, sNewParentAllId);
              controlData.push(controlRow);
            }

            /* 增加合版表 */
            if (commonUtils.isNotEmptyArr(returnData.packData)) {
              returnData.packData.filter(item => item.sControlId === controlItem.sId).forEach(async (packItem) => {
                newCopyTo.pack = packItem;
                let packRow = commonFunc.getDefaultData(config.packConfig, newCopyTo); // 取默认值
                packRow = { ...packRow, ...commonFunc.getAssignFieldValue(packAssignField, packItem, newCopyTo) }; // 取赋值字段
                packRow.sOriginalId = packItem.sId;/* 翻单前的sId */
                /* sSlaveId赋值 */
                if (iSlaveIndex > -1) {
                  const slaveDataRow = slaveData[iSlaveIndex];
                  const packRowAdd = props.handlePackDataAdd(slaveDataRow, 0, controlRow.sId, 'add');
                  if (commonUtils.isNotEmptyObject(packRowAdd)) {
                    packRow = { ...packRow, ...packRowAdd };
                    /* 将控制表中的合版备注sId为新的sId */
                    let JsonData = [];
                    const jsonStr = controlRow.sCombinedMemo;
                    if (commonUtils.isNotEmptyObject(jsonStr) && jsonStr !== '合版信息' && commonUtils.isJSON(jsonStr)) {
                      JsonData = JSON.parse(jsonStr);
                      if (commonUtils.isNotEmptyArr(JsonData)) {
                        let sCombinedMemoNew = '';
                        JsonData.forEach((item, index) => {
                          if (item.sId === packItem.sId) {
                            JsonData[index].sId = packRow.sId;
                          }
                        });
                        sCombinedMemoNew = JSON.stringify(JsonData);
                        controlRow.sCombinedMemo = sCombinedMemoNew;
                        const icontrolIndex = controlData.findIndex(item => item.sId === controlRow.sId);
                        if (icontrolIndex > -1) {
                          controlData[icontrolIndex] = { ...controlData[icontrolIndex], sCombinedMemo: sCombinedMemoNew };
                        }
                      }
                    } else {
                      packRowAdd.dCombineQty = 1; /* 排版数 */
                      if (commonUtils.isNotEmptyObject(packRowAdd) && commonUtils.isNotEmptyObject(packRowAdd.sProductId)) { /* 从表要选择产品 */
                        const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty, sCombinePartsName } = packRowAdd;
                        const tableCombineSelectedData = [];
                        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; /* 合版部件名称 */
                        tableCombineSelectedData.push(jsonObj);
                        const sCombinedMemo = commonUtils.isNotEmptyArr(tableCombineSelectedData) ? JSON.stringify(tableCombineSelectedData) : ''; /* JSON对象转换为字符串存放到合版信息中 */
                        const sCombinedMemoNew = commonUtils.isNotEmptyObject(sCombinedMemo) ? sCombinedMemo : '合版信息';
                        const icontrolIndex = controlData.findIndex(item => item.sId === controlRow.sId);
                        if (icontrolIndex > -1) {
                          controlData[icontrolIndex] = { ...controlData[icontrolIndex], sCombinedMemo: sCombinedMemoNew };
                        }
                      }
                    }
                    packData.push(packRow);
                  }
                }
              });
            }

            if (commonUtils.isNotEmptyArr(returnData.processData)) {
              returnData.processData.filter(item => item.sControlId === controlItem.sId && item.sType !== "3").forEach(processItem => {
                newCopyTo.process = processItem;
                let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                processRow = {
                  ...processRow,
                  ...commonFunc.getAssignFieldValue(processAssignField, processItem, newCopyTo),
                }; // 取赋值字段
                processRow.handleType = "add";
                processRow.sId = commonUtils.createSid();
                processRow.sParentId = masterData.sId;
                processRow.sControlId = controlRow.sId;
                processRow.sPartsName = controlRow.sPartsName;
                processData.push(processRow);

                // 配套工序
                if (bProcessAssort) {
                  returnProcessAssort.filter(item => item.sParentId === processRow.sProcessId).forEach(itemProcessAssort => {
                    const iIndex = dropDownDataProcessName.findIndex(item => item.sId === itemProcessAssort.sProcessId);
                    const iProcessIndex = returnData.processData.findIndex(
                      item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === controlItem.sId
                    );
                    const iNewProcessIndex = processData.findIndex(
                      item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === controlRow.sId
                    );
                    if (iIndex > -1 && iProcessIndex < 0 && iNewProcessIndex < 0) {
                      let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                      processRow = {
                        ...processRow,
                        ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                      }; // 取赋值字段
                      processRow.handleType = "add";
                      processRow.sId = commonUtils.createSid();
                      processRow.sParentId = masterData.sId;
                      processRow.sControlId = controlRow.sId;
                      processRow.sPartsName = controlRow.sPartsName;
                      processRow.sType = dropDownDataProcessName[iIndex].sType;
                      processData.push(processRow);
                    }
                  });
                }
              });
            }

            if (commonUtils.isNotEmptyArr(returnData.materialsData)) {
              returnData.materialsData.filter(item => item.sControlId === controlItem.sId && item.sType !== "2").forEach(materialsItem => {
                newCopyTo.materials = materialsItem;
                let materialsRow = commonFunc.getDefaultData(config.materialsConfig, newCopyTo); // 取默认值
                materialsRow = {
                  ...materialsRow,
                  ...commonFunc.getAssignFieldValue(materialsAssignField, materialsItem, newCopyTo),
                }; // 取赋值字段
                materialsRow.handleType = "add";
                materialsRow.sId = commonUtils.createSid();
                materialsRow.sParentId = masterData.sId;
                materialsRow.sControlId = controlRow.sId;
                materialsRow.sPartsName = controlRow.sPartsName;
                materialsRow.sOriginalId = materialsItem.sId;
                materialsRow.sZmldlt = materialsItem.sZmldlt;
                materialsRow.sInkFatherMaterialsTbId = materialsItem.sInkFatherMaterialsTbId;
                // 材料对应工序的ID要变化
                if (commonUtils.isNotEmptyArr(returnData.processData)) {
                  const iProcessIndex = processData.findIndex(
                    item => item.sControlId === controlRow.sId && item.sSrcProcessTbId === materialsItem.sProcessTbId
                  );
                  if (iProcessIndex > -1) {
                    materialsRow.sProcessTbId = processData[iProcessIndex].sId;
                  }
                }
                materialsData.push(materialsRow);
              });
            }
            /* 将 materialsData中sParentMaterialsId替换为最新的sid */
            if (commonUtils.isNotEmptyArr(materialsData)) {
              const materialsFilterData = materialsData.filter(item => commonUtils.isNotEmptyObject(item.sParentMaterialsId));
              if (commonUtils.isNotEmptyArr(materialsFilterData)) {
                materialsFilterData.forEach((filterItem, index) => {
                  const iIndex = materialsData.findIndex(item => item.sOriginalId === filterItem.sParentMaterialsId);
                  if (iIndex > -1) {
                    const iNexIndex = materialsData.findIndex(item => item.sId === filterItem.sId);
                    if (iNexIndex > -1) {
                      materialsData[iNexIndex] = {
                        ...materialsData[iNexIndex],
                        sParentMaterialsId: materialsData[iIndex].sId,
                      };
                    }
                  }
                });
              }

              const materialsInkFilterData = materialsData.filter(item => commonUtils.isNotEmptyObject(item.sInkFatherMaterialsTbId));
              if (commonUtils.isNotEmptyArr(materialsInkFilterData)) {
                materialsInkFilterData.forEach((filterItem, index) => {
                  const iIndex = materialsData.findIndex(item => item.sOriginalId === filterItem.sInkFatherMaterialsTbId);
                  if (iIndex > -1) {
                    const iNexIndex = materialsData.findIndex(item => item.sId === filterItem.sId);
                    if (iNexIndex > -1) {
                      materialsData[iNexIndex] = {
                        ...materialsData[iNexIndex],
                        sInkFatherMaterialsTbId: materialsData[iIndex].sId,
                      };
                    }
                  }
                });
              }
            }
          });
        }
        if (commonUtils.isNotEmptyArr(returnData.materialsData) && materialsAssignField) {
          returnData.materialsData.filter(item => item.sType === "2").forEach(materialsItem => {
            newCopyTo.materials = materialsItem;
            let materialsRow = commonFunc.getDefaultData(config.materialsConfig, newCopyTo); // 取默认值
            materialsRow = {
              ...materialsRow,
              ...commonFunc.getAssignFieldValue(materialsAssignField, materialsItem, newCopyTo),
            }; // 取赋值字段
            materialsRow.handleType = "add";
            materialsRow.sId = commonUtils.createSid();
            materialsRow.sParentId = masterData.sId;
            materialsData.push(materialsRow);
          });
        }

        if (commonUtils.isNotEmptyArr(returnData.processData) && processAssignField) {
          returnData.processData.filter(item => item.sType === "3").forEach(processItem => {
            newCopyTo.process = processItem;
            let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
            processRow = {
              ...processRow,
              ...commonFunc.getAssignFieldValue(processAssignField, processItem, newCopyTo),
            }; // 取赋值字段
            processRow.handleType = "add";
            processRow.sId = commonUtils.createSid();
            processRow.sParentId = masterData.sId;
            processRow.sOriginalId = processItem.sId;
            /* 根据合版表的源sOriginalId找到新sId */
            let sNewIds = "";
            let sNewNames = "";
            const sOldIds = processItem.sCombinePartsName;
            if (commonUtils.isNotEmptyObject(sOldIds)) {
              const sOldArr = sOldIds.split(",");
              for (const sId of sOldArr) {
                const index = slaveData.findIndex(item => item.sOriginalId === sId);
                if (index > -1) {
                  const tableDataRow = slaveData[index];
                  sNewIds += `${tableDataRow.sId},`;
                  sNewNames += `${tableDataRow.sCustomerName}-${tableDataRow.sProductName},`;
                }
              }
            } else if (iSlaveIndex > -1) {
              sNewIds = slaveData[iSlaveIndex].sId;
              sNewNames = `${slaveData[iSlaveIndex].sCustomerName}-${slaveData[iSlaveIndex].sProductName},`;
            }
            sNewIds = commonUtils.isNotEmptyObject(sNewIds) ? sNewIds.substr(0, sNewIds.length - 1) : "";
            sNewNames = commonUtils.isNotEmptyObject(sNewNames) ? sNewNames.substr(0, sNewNames.length - 1) : "";
            processRow.sCombinePartsName = sNewIds;
            processRow.sCombinePartsNameNew = sNewNames;
            processData.push(processRow);

            // 成品配套工序
            if (bProcessAssort) {
              returnProcessAssort.filter(item => item.sParentId === processRow.sProcessId).forEach(itemProcessAssort => {
                const iIndex = dropDownDataProcessName.findIndex(item => item.sId === itemProcessAssort.sProcessId);
                const iProcessIndex = returnData.processData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId);
                const iNewProcessIndex = processData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId);
                if (iIndex > -1 && iProcessIndex < 0 && iNewProcessIndex < 0) {
                  if (itemProcessAssort.sType === "single") {
                    let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                    processRow = {
                      ...processRow,
                      ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                    }; // 取赋值字段
                    processRow.handleType = "add";
                    processRow.sId = commonUtils.createSid();
                    processRow.sParentId = masterData.sId;
                    processRow.sType = dropDownDataProcessName[iIndex].sType;
                    processData.push(processRow);
                  } else if (itemProcessAssort.sType === "all") {
                    controlData.forEach(controlItem => {
                      let processRow = commonFunc.getDefaultData(config.processConfig, newCopyTo); // 取默认值
                      processRow = {
                        ...processRow,
                        ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                      }; // 取赋值字段
                      processRow.handleType = "add";
                      processRow.sId = commonUtils.createSid();
                      processRow.sParentId = masterData.sId;
                      processRow.sControlId = controlItem.sId;
                      processRow.sPartsName = controlItem.sPartsName;
                      processRow.sType = dropDownDataProcessName[iIndex].sType;
                      processData.push(processRow);
                    });
                  }
                }
              });
            }
          });
        }
        console.log('1122221', returnData.colorData, colorAssignField);
        if (commonUtils.isNotEmptyArr(returnData.colorData)) {
          if (commonUtils.isNotEmptyObject(config.colorConfig)) {
            returnData.colorData.forEach(colorItem => {
              newCopyTo.color = colorItem;
              let colorRow = commonFunc.getDefaultData(config.colorConfig, newCopyTo); // 取默认值
              colorRow = {
                ...colorRow,
                ...commonFunc.getAssignFieldValue(colorAssignField, colorItem, newCopyTo),
              }; // 取赋值字段
              colorRow.handleType = "add";
              colorRow.sId = commonUtils.createSid();
              colorRow.sParentId = masterData.sId;
              colorData.push(colorRow);
            });
          }
        }
        const treeState = { treeData: [] }; /* 加载树形结构数据 */
        addState.materials0DelData = addState.materialsDelData;
        addState.materials0Data = materialsData;
        props.onSaveState({
          [`${name}ChooseVisible`]: false,
          processData,
          materialsData,
          controlData,
          ...treeState,
          colorData,
          masterData,
          packData,
          controlSelectedRowKeys: [],
          materialsSelectedRowKeys: [],
          processSelectedRowKeys: [],
          ...addState,
        });
      } else {
        props.getServiceError(dataReturn.msg);
      }
    } else {
      const { controlData } = props;
      const iControlIndex = commonUtils.isNotEmptyArr(controlSelectedRowKeys)
        ? controlData.findIndex(item => item.sId === controlSelectedRowKeys[0])
        : -1;
      const iProcessIndex = commonUtils.isNotEmptyArr(processDataOld)
        ? commonUtils.isNotEmptyArr(processSelectedRowKeys)
          ? processDataOld.findIndex(item => item.sId === processSelectedRowKeys[0])
          : 0
        : -1;
      if (commonUtils.isNotEmptyArr(selectData)) {
        const bProcessAssort = name === "process";
        let returnProcessAssort = [];
        let processAssignAssort = "";
        let dropDownDataProcessName = [];
        if (bProcessAssort) {
          // 配套数据 */
          if (
            commonUtils.isJSON(localStorage.getItem(`${commonConfig.prefix}processAssort`)) &&
            JSON.parse(localStorage.getItem(`${commonConfig.prefix}processAssort`)).length > 0
          ) {
            returnProcessAssort = JSON.parse(localStorage.getItem(`${commonConfig.prefix}processAssort`));
          }
          if (
            commonUtils.isJSON(localStorage.getItem(`${commonConfig.prefix}dropDownDataProcess`)) &&
            JSON.parse(localStorage.getItem(`${commonConfig.prefix}dropDownDataProcess`)).length > 0
          ) {
            dropDownDataProcessName = JSON.parse(localStorage.getItem(`${commonConfig.prefix}dropDownDataProcess`));
          }
          if (!isProcessAssortApiCalled.current && commonUtils.isEmptyArr(returnProcessAssort)) {
            isProcessAssortApiCalled.current = true;
            const dataUrl = `${commonConfig.server_host}salesorder/getProcessAssort?sModelsId=${sModelsId}`;
            const dataProcessAssort = (await commonServices.postValueService(token, {}, dataUrl)).data;
            if (dataProcessAssort.code === 1) {
              returnProcessAssort = dataProcessAssort.dataset.rows[0].processassort;
              const iIndex = processConfig.gdsconfigformslave.findIndex(item => item.sName === "sProcessName");
              if (iIndex > -1 && commonUtils.isEmptyArr(dropDownDataProcessName)) {
                const sqlDropDownData = await props.getSqlDropDownData(sModelsId, "slave", processConfig.gdsconfigformslave[iIndex]);
                dropDownDataProcessName = sqlDropDownData.dropDownData;
                processAssignAssort = processConfig.gdsconfigformslave[iIndex].sAssignField;
                localStorage.setItem(`${commonConfig.prefix}dropDownDataProcess`, JSON.stringify(dropDownDataProcessName));
              }
              localStorage.setItem(`${commonConfig.prefix}processAssort`, JSON.stringify(returnProcessAssort));
            }
          }
        }

        for (const item of selectData) {
          const newCopyTo = {};
          newCopyTo.master = masterData;
          if (iControlIndex > -1) {
            newCopyTo.control = controlData[iControlIndex];
          }
          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 (name === "process") {
            /* 设置工单参数下拉 */
            if (commonUtils.isNotEmptyObject(tableDataRow.sWorkOrderParam)) {
              tableDataRow = {
                ...tableDataRow,
                ...commonUtils.convertStrToObj(tableDataRow.sWorkOrderParam),
              };
              tableDataRow.sParams = item.sParams;
            }
            // 如果合板信息只有一条，默认加上
            const { packData = [] } = props;
            if (packData.length === 1) {
              let sCombinedStr = "";
              let sCombinedId = "";
              packData.forEach(item => {
                const { sId } = item;
                let { sProductName } = item;
                let { sCombinePartsName } = item;
                sProductName = commonUtils.isNotEmptyObject(sProductName) ? sProductName : "";
                sCombinePartsName = commonUtils.isNotEmptyObject(sCombinePartsName) ? sCombinePartsName : "";
                if (commonUtils.isNotEmptyObject(sCombinePartsName)) {
                  sCombinedStr += `${sProductName}-${sCombinePartsName},`;
                  sCombinedId += `${sId},`;
                } else {
                  sCombinedStr += `${sProductName},`;
                  sCombinedId += `${sId},`;
                }
              });
              if (commonUtils.isNotEmptyObject(sCombinedStr)) {
                sCombinedStr = commonUtils.isNotEmptyObject(sCombinedStr) ? sCombinedStr.slice(0, -1) : "";
              }
              if (commonUtils.isNotEmptyObject(sCombinedId)) {
                sCombinedId = commonUtils.isNotEmptyObject(sCombinedId) ? sCombinedId.slice(0, -1) : "";
              }
              tableDataRow.sCombinePartsNameNew = sCombinedStr;
              tableDataRow.sCombineProductNameNew = sCombinedStr;
              tableDataRow.sCombinePartsName = sCombinedId;
            }
            // 配套工序
            if (bProcessAssort) {
              returnProcessAssort.filter(item => item.sParentId === tableDataRow.sProcessId).forEach(itemProcessAssort => {
                const iIndex = dropDownDataProcessName.findIndex(item => item.sId === itemProcessAssort.sProcessId);
                if (iIndex > -1) {
                  const iProcessIndex = selectData.findIndex(item => item.sId === itemProcessAssort.sProcessId);
                  const iNewProcessIndex =
                    tableDataRow.sType === "3"
                      ? tableData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId)
                      : tableData.findIndex(
                        item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === controlData[iControlIndex].sId
                      );
                  if (iProcessIndex < 0 && iNewProcessIndex < 0) {
                    let processRow = commonFunc.getDefaultData(processConfig, newCopyTo); // 取默认值
                    processRow = {
                      ...processRow,
                      ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                    }; // 取赋值字段
                    processRow.handleType = "add";
                    processRow.sId = commonUtils.createSid();
                    processRow.sParentId = masterData.sId;
                    processRow.sType = dropDownDataProcessName[iIndex].sType;
                    if (iControlIndex > -1 && processRow.sType !== "3") {
                      processRow.sControlId = controlData[iControlIndex].sId;
                      processRow.sPartsName = controlData[iControlIndex].sPartsName;
                    }
                    tableData.push(processRow);

                    if (itemProcessAssort.sType === "all") {
                      controlData.filter(item => item.sId !== controlData[iControlIndex].sId).forEach(controlTableRow => {
                        const iNewProcessIndex =
                          dropDownDataProcessName[iIndex].sType === "3"
                            ? tableData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId)
                            : tableData.findIndex(
                              item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === controlTableRow.sId
                            );
                        if (iNewProcessIndex < 0) {
                          let processRow = commonFunc.getDefaultData(processConfig, newCopyTo); // 取默认值
                          processRow = {
                            ...processRow,
                            ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                          }; // 取赋值字段
                          processRow.handleType = "add";
                          processRow.sId = commonUtils.createSid();
                          processRow.sParentId = masterData.sId;
                          processRow.sType = dropDownDataProcessName[iIndex].sType;
                          if (iControlIndex > -1 && processRow.sType !== "3") {
                            processRow.sControlId = controlTableRow.sId;
                            processRow.sPartsName = controlTableRow.sPartsName;
                          }
                          tableData.push(processRow);
                        }
                      });
                    }
                  }
                }
              });
            }
          } else if (name === "materials0") {
            if (iProcessIndex > -1) {
              tableDataRow.sProcessId = processDataOld[iProcessIndex].sProcessId; /* 工序ID */
              tableDataRow.sProcessTbId = processDataOld[iProcessIndex].sId; /* 工序表格ID */
              tableDataRow.sMaterialsProcessNameOrder = processDataOld[iProcessIndex].sProcessName; /* 工序ID */
              tableDataRow.sMaterialsProcessName = processDataOld[iProcessIndex].sProcessName; /* 工序ID */
            }
          }
          if (iControlIndex > -1 && tableDataRow.sType !== "3") {
            tableDataRow.sControlId = controlData[iControlIndex].sId;
            tableDataRow.sPartsName = controlData[iControlIndex].sPartsName;

            const processLen = tableData.filter(item => item.sType !== "3").length + 1; /* 工序序号 */
            tableDataRow.iOrder = processLen;
            tableData.push(tableDataRow);
          } else if (tableDataRow.sType === "3") {
            const processLen = tableData.filter(item => item.sType === "3").length + 1; /* 工序序号 */
            tableDataRow.iOrder = processLen;
            tableData.push(tableDataRow);
          }
        }
      }
      const tableDataNew = props.sortData(controlData, tableData);
      props.onSaveState({
        [`${name}Data`]: tableDataNew,
        [`${name}ChooseVisible`]: false,
        materialsConfig,
        materialsSelectedRowKeys: [],
      });
    }
  };

  returnProps.onSelect = handleSelect;

  // 主表变化（待优化）
  const handleMasterChange = async (name, sFieldName, changeValue, sId, dropDownData, config, isWait) => {
    /* 数据集类型，对象型为Map 数组型为List */
    const { sModelsId, app } = props;
    const masterData = commonUtils.isEmpty(config) ? props.masterData : config.masterData;
    const masterConfig = commonUtils.isEmpty(config) ? props.masterConfig : config.masterConfig;
    const { token } = app;
    let { sBackProcessClassifyData } = props;
    let { sAllPartsName } = masterData;
    let backProcessData;
    if (
      sFieldName === "sProductClassifyId" ||
      sFieldName === "sProductId" ||
      sFieldName === "sProductClassifyName" ||
      sFieldName === "sProductName"
    ) {
      backProcessData = await handleBackProcessData(config, true);
      let allPartsName = [];
      if (sAllPartsName !== undefined) {
        allPartsName = sAllPartsName.split(",");
      }
      if (
        allPartsName.length > 0 &&
        masterConfig.gdsconfigformslave.filter(item => item.sName === `sMaterialsName${allPartsName[0]}`).length > 0 &&
        (sBackProcessClassifyData !== undefined &&
          sBackProcessClassifyData !== "" &&
          sBackProcessClassifyData.length > 0 &&
          masterConfig.gdsconfigformslave.filter(item => item.sName === `${sBackProcessClassifyData[0].sId}${allPartsName[0]}`).length > 0)
      ) {
        let iIndex;
        allPartsName.forEach(sPartsName => {
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `dSumPQty${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `sMaterialsName${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `iPrintModePo${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }
          iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === `iPositiveColor${sPartsName}`);
          if (iIndex > -1) {
            masterConfig.gdsconfigformslave.splice(iIndex, 1);
          }

          if (sBackProcessClassifyData !== "") {
            sBackProcessClassifyData.filter(processClassify => processClassify.sType !== "3").forEach(processClassify => {
              iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === processClassify.sId + sPartsName);
              if (iIndex > -1) {
                masterConfig.gdsconfigformslave.splice(iIndex, 1);
              }
            });
          }
        });
        if (sBackProcessClassifyData !== "") {
          sBackProcessClassifyData.filter(processClassify => processClassify.sType === "3").forEach(processClassify => {
            iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === processClassify.sId);
            if (iIndex > -1) {
              masterConfig.gdsconfigformslave.splice(iIndex, 1);
            }
          });
        }
      }

      let sProductClassifyId;
      if (changeValue !== null && changeValue !== undefined) {
        sProductClassifyId = commonUtils.isEmpty(changeValue.sProductClassifyId) ? masterData.sProductClassifyId : changeValue.sProductClassifyId;
        sAllPartsName = commonUtils.isEmpty(changeValue.sAllPartsName) ? masterData.sAllPartsName : changeValue.sAllPartsName;
      } else {
        sProductClassifyId = masterData.sProductClassifyId;
      }
      if (commonUtils.isEmpty(sProductClassifyId)) {
        return;
      }
      const sBackProcessClassify = masterConfig.gdsconfigformslave.filter(item => item.sName.toLowerCase() === "sbackprocessclassify")[0];

      const values = { sKeyUpFilterName: "", sSqlCondition: { sProductClassifyId } };
      const dataReturn = (await commonServices.postValueService(
        token,
        values,
        `${commonConfig.server_host}business/getSelectDataBysControlId/${sBackProcessClassify.sId}?sModelsId=${sModelsId}`
      )).data;
      /*   接收返回值   */
      /*   成功的话刷新页面(同步主表和从表数据),不成功就弹出错误提示   */
      if (dataReturn.code === 1) {
        /*   成功   */
        const { rows } = dataReturn.dataset;

        allPartsName = [];
        if (sAllPartsName !== undefined) {
          allPartsName = sAllPartsName.split(",");
        }

        sBackProcessClassifyData = rows;
        if (
          allPartsName.length > 0 &&
          masterConfig.gdsconfigformslave.filter(item => item.sName === `sMaterialsName${allPartsName[0]}`).length <= 0 &&
          sBackProcessClassifyData !== undefined &&
          sBackProcessClassifyData !== "" &&
          sBackProcessClassifyData.length > 0 &&
          masterConfig.gdsconfigformslave.filter(item => item.sName === `${sBackProcessClassifyData[0].sId}${allPartsName[0]}`).length <= 0
        ) {
          const sumPQtyConfig =
            masterConfig.gdsconfigformslave.filter(item => item.sName === "dSumPQty").length > 0
              ? masterConfig.gdsconfigformslave.filter(item => item.sName === "dSumPQty")[0]
              : [];
          const materialsNameConfig =
            masterConfig.gdsconfigformslave.filter(item => item.sName === "sMaterialsName").length > 0
              ? masterConfig.gdsconfigformslave.filter(item => item.sName === "sMaterialsName")[0]
              : [];
          const printModePoConfig =
            masterConfig.gdsconfigformslave.filter(item => item.sName === "iPrintModePo").length > 0
              ? masterConfig.gdsconfigformslave.filter(item => item.sName === "iPrintModePo")[0]
              : [];
          const positiveColorConfig =
            masterConfig.gdsconfigformslave.filter(item => item.sName === "iPositiveColor").length > 0
              ? masterConfig.gdsconfigformslave.filter(item => item.sName === "iPositiveColor")[0]
              : [];
          const processNameConfig =
            masterConfig.gdsconfigformslave.filter(item => item.sName === "sProcessName").length > 0
              ? masterConfig.gdsconfigformslave.filter(item => item.sName === "sProcessName")[0]
              : [];

          let ConfigNew;
          allPartsName.forEach(item => {
            ConfigNew = { ...sumPQtyConfig };
            ConfigNew.sName = `dSumPQty${item}`;
            ConfigNew.sAssignField = commonUtils.isEmpty(ConfigNew.sAssignField) ? "" : ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);

            ConfigNew = { ...materialsNameConfig };
            ConfigNew.sName = `sMaterialsName${item}`;
            ConfigNew.sAssignField = commonUtils.isEmpty(ConfigNew.sAssignField) ? "" : ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);

            ConfigNew = { ...printModePoConfig };
            ConfigNew.sName = `iPrintModePo${item}`;
            ConfigNew.sAssignField = commonUtils.isEmpty(ConfigNew.sAssignField) ? "" : ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);

            ConfigNew = { ...positiveColorConfig };
            ConfigNew.sName = `iPositiveColor${item}`;
            ConfigNew.sAssignField = commonUtils.isEmpty(ConfigNew.sAssignField) ? "" : ConfigNew.sAssignField.replace(/:/g, `${item}:`);
            masterConfig.gdsconfigformslave.push(ConfigNew);
            if (sBackProcessClassifyData !== "") {
              sBackProcessClassifyData.filter(processClassify => processClassify.sType !== "3").forEach(processClassify => {
                ConfigNew = { ...processNameConfig };
                ConfigNew.sName = processClassify.sId + item;
                masterConfig.gdsconfigformslave.push(ConfigNew);
              });
            }
          });
          if (sBackProcessClassifyData !== "") {
            sBackProcessClassifyData.filter(processClassify => processClassify.sType === "3").forEach(processClassify => {
              ConfigNew = { ...processNameConfig };
              ConfigNew.sName = processClassify.sId;
              masterConfig.gdsconfigformslave.push(ConfigNew);
            });
          }
        }
        const returnChange = await props.onChange(name, sFieldName, changeValue, sId, dropDownData, true, masterData);
        const masterDataDefault = commonFunc.getDefaultData(masterConfig, {});
        returnChange.masterData = { ...masterDataDefault, ...returnChange.masterData };
        if (isWait) {
          return {
            ...returnChange,
            sBackProcessClassifyData,
            masterConfig,
            ...backProcessData,
          };
        } else {
          props.onSaveState({
            ...returnChange,
            sBackProcessClassifyData,
            masterConfig,
            ...backProcessData,
          });
        }
      } else {
        /*   失败   */
        props.getServiceError(dataReturn);
      }
    } else if (sFieldName === "sCustomerId" || sFieldName === "sCustomerNo" || sFieldName === "sCustomerName") {
      const returnChange = await props.onChange(name, sFieldName, changeValue, sId, dropDownData, true);
      if (returnChange !== undefined && returnChange.masterData !== undefined) {
        returnChange.masterData.sProductId = "";
        returnChange.masterData.sProductNo = "";
        returnChange.masterData.sProductName = "";
      }
      props.onSaveState({ ...returnChange });
    } else {
      props.onChange(name, sFieldName, changeValue, sId, dropDownData);
    }
  };

  returnProps.onMasterChange = handleMasterChange;

  const [form, setForm] = useState(null);
  const handleSave = () => {
    form.validateFields(async err => {
      if (err) {
        // 验证失败
        const language = props?.app?.userinfo?.sLanguage || 'sChinese'; // 默认简体中文
        const requiredText = language === 'sEnglish' ? 'is Required' :
          (language === 'sBig5' ? '為必填項' : '为必填项');
        for (const key of Object.keys(err)) {
          const sContent = err[key].errors[0].message?.replace('为必填项', requiredText);
          message.warning(sContent);
        }
        props.onSaveState({
          loading: false,
        });
        return;
      }

      // 验证成功
      const {
        masterConfig,
        masterData,
        slaveConfig,
        slaveData,
        slaveDelData,
        controlConfig,
        controlData,
        controlDelData,
        materials0Config: materialsConfig,
        materials0Data: materialsData,
        processConfig,
        processData,
        processDelData,
        colorConfig,
        colorData,
        colorDelData,
        packConfig,
        packData,
        packDelData,
        calculated,
        sModelsType,
        addStateMap,
      } = props;
      if (commonUtils.isEmptyArr(slaveData)) {
        message.warning(`从表${commonFunc.showMessage(props.app.commonConst, "isNotNull")}`);
        props.onSaveState({
          loading: false,
        });
        return;
      }
      if (
        !commonBusiness.validateTable(slaveConfig, slaveData, props) ||
        !commonBusiness.validateTable(controlConfig, controlData, props) ||
        !commonBusiness.validateTable(materialsConfig, materialsData, props) ||
        !commonBusiness.validateTable(processConfig, processData, props) ||
        !commonBusiness.validateTable(colorConfig, colorData, props)
      ) {
        props.onSaveState({
          loading: false,
        });
        return;
      }
      const calculating = commonFunc.showLocalMessage(props, 'calculating', '自动计算中，请稍后再试。');

      if (sModelsType.includes("manufacture/workOrder") && !calculated) {
        message.warning(calculating);
        await props.handleCalculation("workOrder", true);
      } else {
        const data = [];
        data.push(commonBusiness.mergeData("master", masterConfig.sTbName, [masterData]));
        data.push(commonBusiness.mergeData("slave", slaveConfig.sTbName, slaveData, slaveDelData));
        data.push(commonBusiness.mergeData("control", controlConfig.sTbName, controlData, controlDelData));
        // data.push(commonBusiness.mergeData('materials', materialsConfig.sTbName, materialsData, materialsDelData));
        data.push(commonBusiness.mergeData("process", processConfig.sTbName, processData, processDelData));
        if (commonUtils.isNotEmptyObject(colorConfig)) {
          data.push(commonBusiness.mergeData("color", colorConfig.sTbName, colorData, colorDelData));
        }
        if (commonUtils.isNotEmptyObject(packConfig)) {
          data.push(commonBusiness.mergeData("pack", packConfig.sTbName, packData, packDelData));
        }

        if (commonUtils.isNotEmptyObject(addStateMap)) {
          for (const childConfig of Object.keys(addStateMap)) {
            const tableName = childConfig.replace("Config", "").trim();
            const { [`${tableName}Data`]: tableData, [`${tableName}Config`]: tableConfig, [`${tableName}DelData`]: tableDelData } = props;
            if (tableConfig.sTbName !== "noTable") {
              data.push(commonBusiness.mergeData(tableName, tableConfig.sTbName, tableData, tableDelData));
            }
          }
        }

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

  returnProps.currentForm = form;
  returnProps.setForm = setForm;
  returnProps.onSubmit = handleSave;

  const handleBackProcessData = async (config, isWait) => {
    const { token } = props.app;
    const { sModelsId, sBackProcessData } = props;
    const masterConfig = commonUtils.isEmpty(config) ? props.masterConfig : config.masterConfig;
    if (sBackProcessData === undefined || sBackProcessData === "") {
      const sBackProcess = masterConfig.gdsconfigformslave.filter(item => item.sName === "sBackProcess")[0];
      const url = `${commonConfig.server_host}business/getSelectDataBysControlId/${sBackProcess.sId}?sModelsId=${sModelsId}`;
      const values = { sKeyUpFilterName: "", sSqlCondition: {} };

      const masterReturn = (await commonServices.postValueService(token, values, url)).data;
      if (masterReturn.code === 1) {
        const sBackProcessDataValue = masterReturn.dataset.rows;
        if (isWait) {
          return { sBackProcessData: sBackProcessDataValue };
        } else {
          props.onSaveState({ sBackProcessData: sBackProcessDataValue });
        }
      } else {
        message.warn(masterReturn.msg);
      }
    }
  };

  return {
    ...props,
    ...returnProps,
  };
};

// 从表相关事件
const slaveProps = props => {
  const returnProps = {};
  returnProps.onDataRowAdd = ({ name, bchild }) => {
    const { [`${name}SelectedRowKeys`]: tableSelectedRowKeys, app, slaveData, [`${name}Data`]: tableData } = props;
    const { expKeys = [] } = props;
    const tableDataRow = props.onDataRowAdd(name, true);
    if (commonUtils.isNotEmptyArr(slaveData) && commonUtils.isEmptyArr(tableSelectedRowKeys)) {
      message.warning(commonFunc.showMessage(app.commonConst, "selectedRowKeysNo"));
      return;
    }
    if (bchild === "childNode") {
      /* 添加子级 */
      const iIndex = tableData.findIndex(item => item.sId === tableSelectedRowKeys[0]);
      if (iIndex > -1) {
        const sNodeId = tableData[iIndex].sNodeId;
        if (commonUtils.isEmptyObject(sNodeId)) {
          message.warn("数据生成错误，请删除父级后重新添加"); // 获取父节点的sAllId
          return;
        }
        tableDataRow.sFatherSlaveId = sNodeId;
        const sAllId = tableData[iIndex].sAllId || sNodeId;
        // if (commonUtils.isEmptyObject(sAllId)) {
        //   message.warn("子部件数据生成错误！[sAllId为空]"); // 获取父节点的sAllId
        //   return;
        // }
        tableDataRow.sAllId = `${tableData[iIndex].sAllId},${tableDataRow.sNodeId}`;
      }
      /* 新增子级时 子级展开 */
      expKeys.push(tableSelectedRowKeys[0]); /* 展开只要展开父级即可 */
    }
    if (bchild !== "sameNode" && bchild !== "childNode") {
      /* 列头新增 */
      tableDataRow.sAllId = tableDataRow.sNodeId;
    }
    tableData.push(tableDataRow);
    props.onSaveState({
      [`${name}Data`]: tableData,
      [`${name}SelectedRowKeys`]: [tableDataRow.sId],
      expKeys,
    });
  };
  returnProps.onDataRowDel = ({ name }) => {
    /* 删除sSlaveId关联的合版表 */
    const { [`${name}SelectedRowKeys`]: tableSelectedRowKeys } = props;
    if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) {
      const packReturnData = props.otherTableDel("pack", tableSelectedRowKeys, "sSlaveId");
      const materielReturnData = props.otherTableDel("materials", tableSelectedRowKeys, "sCombinePartsName"); /* 删除成品材料 */
      const processReturnData = props.otherTableDel("process", tableSelectedRowKeys, "sCombinePartsName"); /* 删除成品工序 */
      const slaveReturnData = props.onDataRowDel(name, true, tableSelectedRowKeys);
      props.onSaveState({
        ...materielReturnData,
        ...processReturnData,
        ...packReturnData,
        ...slaveReturnData,
      });
      return true;
    } else {
      message.warn("请选择要删除的部件！");
      return false;
    }
  };
  returnProps.onDataChange = async ({ name, sFieldName, changeValue, sId, dropDownData }) => {
    const { sModelsId, masterConfig, controlConfig, masterData, [`${name}Data`]: tableData, controlData: controlDataOld, packData } = props;
    const tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (tableDataRow === undefined) return;
    const iIndex = tableData.findIndex(item => item.sId === sId);
    tableData[iIndex] = tableDataRow;
    const addState = {};
    let bProductQtySelf = false;
    if (commonUtils.isNotEmptyObject(props.masterConfig) && commonUtils.isNotEmptyArr(props.masterConfig.gdsconfigformslave)) {
      const iProductQtyIndex = props.masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === "bProductQtySelf");
      if (iProductQtyIndex > -1) {
        bProductQtySelf = true; /* 生产数量无需叠加 */
      }
    }
    if (sFieldName === "dProductQty" || sFieldName === "dGiveQty" || sFieldName === "dStockupQty") {
      let dPartsQty = 0;
      tableData.forEach(item => {
        if (bProductQtySelf) {
          dPartsQty += commonUtils.isNull(item.dProductQty, 0);
        } else {
          dPartsQty += commonUtils.isNull(item.dProductQty, 0) + commonUtils.isNull(item.dGiveQty, 0) + commonUtils.isNull(item.dStockupQty, 0);
        }
      });
      /* 找到所有一级部件 */
      const controlRootData = commonUtils.isNotEmptyArr(controlDataOld)
        ? controlDataOld.filter(item => commonUtils.isEmpty(item.sControlParentId))
        : [];
      if (commonUtils.isNotEmptyArr(controlRootData)) {
        controlRootData.forEach(item => {
          let itemNew = { ...item };
          /*  父级的dPartsQty为dPartsQty */
          itemNew.dPartsQty = dPartsQty;
          itemNew = props.singlePQtyChange(itemNew);
          /* 找到子部件 */
          const controlChildData = controlDataOld.filter(
            itemOld => commonUtils.isNotEmptyObject(itemOld.sAllId) && itemOld.sAllId.indexOf(item.sId) > -1 && itemOld.sId !== item.sId
          );
          if (commonUtils.isNotEmptyArr(controlChildData)) {
            const { dMachineQty } = itemNew;
            controlChildData.forEach(child => {
              let tableDataRow = { ...child };
              const iIndex = controlDataOld.findIndex(item => item.sId === child.sId);
              if (iIndex > -1) {
                /* 子部件部件数量为父部件上机数量  */
                tableDataRow.dPartsQty = dMachineQty;
                tableDataRow = props.singlePQtyChange(tableDataRow);
                controlDataOld[iIndex] = tableDataRow;
              }
            });
          }
          const addStata = {};
          addStata.dPartsQty = dPartsQty;
          const iRootIndex = controlDataOld.findIndex(itemControl => itemControl.sId === item.sId);
          controlDataOld[iRootIndex] = { ...controlDataOld[iRootIndex], ...itemNew };
        });
      }
      addState.controlData = controlDataOld;
    } else if (sFieldName === "sCustomerId" || sFieldName === "sCustomerNo" || sFieldName === "sCustomerName") {
      let tableDataRowNew = {};
      tableDataRowNew.sProductId = "";
      tableDataRowNew.sProductNo = "";
      tableDataRowNew.sProductName = "";
      tableData[iIndex] = { ...tableDataRowNew, ...tableDataRow };
    } else if (sFieldName === "sProductId" || sFieldName === "sProductNo" || sFieldName === "sProductName") {
      const iProductIdIndex = dropDownData.findIndex(item => item.sId === tableData[0].sProductId);
      if (
        tableDataRow.handleType === "add" &&
        iProductIdIndex > -1 &&
        tableDataRow.sProductId !== tableDataRow.sProductName &&
        commonUtils.isEmptyArr(controlDataOld)
      ) {
        const changeData = dropDownData[iProductIdIndex];
        const sParentId = commonUtils.isEmpty(changeData) ? "" : changeData.sParentId;
        if (!commonUtils.isEmpty(sParentId)) {
          const iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === "sProductClassifyName");
          if (iIndex > -1) {
            let dProductQty = 0;
            tableData.forEach(item => {
              if (bProductQtySelf) {
                dProductQty += commonUtils.isNull(item.dProductQty, 0);
              } else {
                dProductQty +=
                  commonUtils.isNull(item.dProductQty, 0) + commonUtils.isNull(item.dGiveQty, 0) + commonUtils.isNull(item.dStockupQty, 0);
              }
            });
            const sqlDropDownData = await props.getSqlDropDownData(sModelsId, "master", masterConfig.gdsconfigformslave[iIndex]);
            const dropDownData = sqlDropDownData.dropDownData;
            const [changeData] = dropDownData.filter(item => item.sId === sParentId);
            const sAllPartsName = commonUtils.isEmpty(changeData) ? "" : changeData.sAllPartsName;
            if (commonUtils.isNotEmptyStr(sAllPartsName)) {
              const sAssignFieldObj = sAllPartsName.split(",");
              const controlData = [];
              for (const child of sAssignFieldObj) {
                let allTableData = {};
                allTableData = {};
                allTableData.master = masterData;
                allTableData.slave = commonUtils.isEmptyArr(tableData) ? {} : tableData[0];
                const tableDataRow = commonFunc.getDefaultData(controlConfig, allTableData);
                tableDataRow.handleType = "add";
                tableDataRow.sId = commonUtils.createSid();
                tableDataRow.sParentId = masterData && masterData.sId ? masterData.sId : null;
                tableDataRow.key = tableDataRow.sId;
                tableDataRow.bDefault = false;
                tableDataRow.iOrder = controlData.length + 1;
                tableDataRow.sPartsName = child;
                tableDataRow.dPartsQty = dProductQty;
                controlData.push(tableDataRow);
              }
              addState.controlData = controlData;
            }
          }
        }
      }
      /* 从表产品改变带动合版表产品与部件表合版信息 同步改变 */
      const controlDataNew = commonUtils.isNotEmptyArr(addState.controlData) ? addState.controlData : controlDataOld;
      /* 如果packData只有一条数据 则同步合版数据 及增加控制表合版备注 */
      if (commonUtils.isNotEmptyArr(packData) && packData.length === 1 && packData[0].sSlaveId === tableDataRow.sId) {
        let packDataRow = packData[0];
        const sControlId = packDataRow.sControlId;
        packDataRow = props.handlePackDataAdd(tableDataRow, 0, sControlId);
        packDataRow.dCombineQty = 1;
        packData[0] = { ...packData[0], ...packDataRow };

        if (commonUtils.isNotEmptyObject(packData[0])) {
          const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty, sCombinePartsName } = packData[0];
          const tableCombineSelectedData = [];
          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; /* 合版部件名称 */
          tableCombineSelectedData.push(jsonObj);
          const sCombinedMemo = commonUtils.isNotEmptyArr(tableCombineSelectedData)
            ? JSON.stringify(tableCombineSelectedData)
            : ""; /* JSON对象转换为字符串存放到合版信息中 */
          if (commonUtils.isNotEmptyArr(controlDataNew)) {
            const iControlIndex = controlDataNew.findIndex(item => item.sId === sControlId);
            if (iControlIndex > -1) {
              controlDataNew[iControlIndex].sCombinedMemo = sCombinedMemo;
              controlDataNew[iControlIndex].sPartsName = tableDataRow.sProductName;
            }
            addState.controlData = controlDataNew;
          }
        }
      } else if (packData.length > 1) {
        const packFilterData = packData.filter(item => item.sSlaveId === tableDataRow.sId);
        if (commonUtils.isNotEmptyArr(packFilterData)) {
          packFilterData.forEach((itemPack, index) => {
            let packDataRow = itemPack;
            const sControlId = packDataRow.sControlId;
            packDataRow = props.handlePackDataAdd(tableDataRow, 0, sControlId);
            const pIndex = packData.findIndex(item => item.sId === itemPack.sId);
            if (pIndex > -1) {
              packData[pIndex] = { ...packData[pIndex], ...packDataRow }; /* 根据选中的从表 找到所有的合版数据，将合版数据中的产品换成切换后的产品 */
              let sCombinedMemoStr = ""; /* 将控制表合版信息中的产品换成新选择的产品 */
              if (commonUtils.isNotEmptyArr(controlDataNew)) {
                const iControlIndex = controlDataNew.findIndex(item => item.sId === sControlId);
                if (iControlIndex > -1) {
                  sCombinedMemoStr = controlDataNew[iControlIndex].sCombinedMemo;
                  if (sCombinedMemoStr) {
                    const sCombinedMemoArr = commonUtils.isNotEmptyObject(sCombinedMemoStr) ? JSON.parse(sCombinedMemoStr) : {};
                    if (commonUtils.isNotEmptyArr(sCombinedMemoArr)) {
                      const iIndex = sCombinedMemoArr.findIndex(item => item.sId === itemPack.sId);
                      if (iIndex > -1) {
                        const addState = {};
                        addState.sProductId = tableDataRow.sProductId; /* 产品id */
                        addState.sCustomerId = tableDataRow.sCustomerId; /* 客户id */
                        addState.sCustomerName = tableDataRow.sCustomerName; /* 客户名称 */
                        addState.sProductName = tableDataRow.sProductName; /* 产品名称 */
                        addState.sProductNo = tableDataRow.sProductNo; /* 产品编号 */
                        sCombinedMemoArr[iIndex] = { ...sCombinedMemoArr[iIndex], ...addState };
                        const sCombinedMemo = commonUtils.isNotEmptyArr(sCombinedMemoArr)
                          ? JSON.stringify(sCombinedMemoArr)
                          : ""; /* JSON对象转换为字符串存放到合版信息中 */
                        controlDataNew[iControlIndex].sCombinedMemo = sCombinedMemo;
                        controlDataNew[iControlIndex].sPartsName = tableDataRow.sProductName;
                      }
                    }
                  }
                }
              }
            }
          });
          addState.controlData = controlDataNew;
        }
      }
      addState.packData = packData;
    }
    props.onSaveState({ [`${name}Data`]: tableData, ...addState, calculated: false });
  };
  return returnProps;
};

// 控制表相关事件
const controlProps = props => {
  const returnProps = {};
  returnProps.onDataRowAdd = ({ name, bchild }) => {
    /*   外置处理业务   */
    const { slaveData, controlData, controlSelectedRowKeys, slaveSelectedRowKeys, [`${name}Data`]: tableData } = props;
    let { packData } = props;
    /* 增加子部件 */
    const { [`${name}SelectedRowKeys`]: treeSelectedKeys } = props;
    if (
      (bchild === "childNode" || bchild === "sameNode") &&
      (commonUtils.isEmptyArr(treeSelectedKeys) || commonUtils.isEmptyArr(controlSelectedRowKeys))
    ) {
      message.warn("请选择部件！"); // 请选择部件
      return;
    }
    const tableDataRow = props.onDataRowAdd(name, true);
    if (bchild === "sameNode") {
      /* 添加同级 */
      const iIndex = controlData.findIndex(item => item.sId === treeSelectedKeys[0]);
      /* 找到同级子元素的sControlParentId */
      if (iIndex > -1) {
        tableDataRow.sControlParentId = controlData[iIndex].sControlParentId;
        /* 找到同级父级sAllId */
        const pId = controlData[iIndex].sControlParentId;
        const sControlParentId = controlData.findIndex(item => item.sNodeId === pId);
        if (sControlParentId > -1) {
          const sAllId = controlData[sControlParentId].sAllId;
          // if (commonUtils.isEmptyObject(sAllId)) {
          //   message.warn("部件数据生成错误！[sAllId为空]");
          //   return;
          // }
          tableDataRow.sAllId = `${controlData[sControlParentId].sAllId},${tableDataRow.sNodeId}`;
        } else {
          tableDataRow.sAllId = tableDataRow.sNodeId;
        }
      }
    }
    if (bchild === "childNode") {
      /* 添加子级 */
      const iIndex = controlData.findIndex(item => item.sId === treeSelectedKeys[0]);
      if (iIndex > -1) {
        const sNodeId = tableData[iIndex].sNodeId;
        if (commonUtils.isEmptyObject(sNodeId)) {
          message.warn("数据生成错误，请删除父级后重新添加"); // 获取父节点的sAllId
          return;
        }
        tableDataRow.sControlParentId = sNodeId;
        const sAllId = tableData[iIndex].sAllId || sNodeId;
        if (commonUtils.isEmptyObject(sAllId)) {
          message.warn("子部件数据生成错误！[sAllId为空]"); // 获取父节点的sAllId
          return;
        }
        tableDataRow.sAllId = `${controlData[iIndex].sAllId},${tableDataRow.sNodeId}`;
      }
    }
    if (bchild !== "sameNode" && bchild !== "childNode") {
      /* 列头新增 */
      tableDataRow.sAllId = tableDataRow.sNodeId;
    }

    let slaveSelectedRow = {};
    if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
      /* 从表有选中行 */
      const iSlaveIndex = slaveData.findIndex(item => slaveSelectedRowKeys.includes(item.sId));
      if (iSlaveIndex > -1) {
        slaveSelectedRow = slaveData[iSlaveIndex];
      }
    } else {
      /* 没有选中行 */
      if (slaveData.length === 1) {
        slaveSelectedRow = slaveData[0];
      } else {
        message.error("请选择从表！");
      }
    }
    /* 新增工艺卡，部件名称要默认选中从表行的产品名称 */
    tableDataRow.sPartsName = slaveSelectedRow.sProductName;

    /* 部件表新增时,若合版表没有该sControlId 则默认取从表选中行,合拼1 作为一条packData数据 */
    if (commonUtils.isEmptyArr(packData)) {
      packData = [];
    }
    const selectProduct = commonFunc.showLocalMessage(props, 'selectProduct', '请先选择产品');

    const iIndex = packData.findIndex(item => item.sControlId === tableDataRow.sId);
    if (iIndex === -1) {
      if (commonUtils.isEmptyObject(slaveSelectedRow.sProductId)) {
        message.error(selectProduct);
        return;
      }
      if (slaveSelectedRow) {
        const packDataRow = props.handlePackDataAdd(slaveSelectedRow, 0, tableDataRow.sId, "add");
        packDataRow.dCombineQty = 1; /* 排版数 */
        if (packDataRow.sProductId) {
          /* 从表要选择产品 */
          const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty, sCombinePartsName } = packDataRow;
          const tableCombineSelectedData = [];
          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; /* 合版部件名称 */
          tableCombineSelectedData.push(jsonObj);
          const sCombinedMemo = commonUtils.isNotEmptyArr(tableCombineSelectedData)
            ? JSON.stringify(tableCombineSelectedData)
            : ""; /* JSON对象转换为字符串存放到合版信息中 */
          tableDataRow.sCombinedMemo = commonUtils.isNotEmptyObject(sCombinedMemo) ? sCombinedMemo : "合版信息";
        }
        packData.push(packDataRow);
      }
    }

    tableData.push(tableDataRow);
    props.onSaveState({
      treeData: [],
      [`${name}Data`]: tableData,
      [`${name}SelectedRowKeys`]: [tableDataRow.sId],
      treeSelectedKeys: [tableDataRow.sId],
      packData,
    });
  };
  returnProps.onDataRowDel = ({ name }) => {
    const { controlData, [`${name}SelectedRowKeys`]: tableSelectedRowKeys } = props;
    let { treeSelectedKeys } = props;
    if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) {
      const iIndex = controlData.findIndex(item => tableSelectedRowKeys.includes(item.sId) && item.rowTag === 1);
      if (iIndex > -1) {
        /* 如果行被锁定不可更改删除时 */
        return false;
      }
      /* 删除该节点及所有子节点 */
      treeSelectedKeys = treeSelectedKeys || [];
      const tableRow = controlData.find(item => item.sId === tableSelectedRowKeys[0]);
      let controlChildData = [];
      if (commonUtils.isNotEmptyObject(tableRow)) {
        // 使用Set来记录已处理节点，防止循环引用
        const processedNodes = new Set();

        const findChildren = (parentId, allNodes) => {
          // 防止重复处理同一个父节点
          if (processedNodes.has(parentId)) return [];
          processedNodes.add(parentId);

          const children = allNodes.filter(node =>
            node.sControlParentId === parentId && !processedNodes.has(node.sNodeId)
          );

          return children.concat(
            ...children.map(child => findChildren(child.sNodeId, allNodes))
          );
        };

        controlChildData = findChildren(tableRow.sNodeId, controlData);
      }
      if (commonUtils.isNotEmptyArr(controlChildData)) {
        controlChildData.forEach(itemNew => {
          tableSelectedRowKeys.push(itemNew.sId);
        });
      }
      const materialsReturnData = props.otherTableDel("materials", tableSelectedRowKeys);
      const materials0ReturnData = props.otherTableDel("materials0", tableSelectedRowKeys);
      const processReturnData = props.otherTableDel("process", tableSelectedRowKeys);
      const packReturnData = props.otherTableDel("pack", tableSelectedRowKeys);
      const controlReturnData = props.onDataRowDel(name, true, tableSelectedRowKeys);
      const treeState = { treeData: [] };
      props.onSaveState({
        ...treeState,
        ...materialsReturnData,
        ...materials0ReturnData,
        ...processReturnData,
        ...packReturnData,
        ...controlReturnData,
      });
      return true;
    } else {
      message.warn("请选择要删除的部件！");
      return false;
    }
  };
  returnProps.onDataChange = async ({ name, sFieldName, changeValue, sId, dropDownData }) => {
    const { [`${name}Data`]: tableData, materialsData: materialsDataOld, processData: processDataOld, packData } = props;
    let tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (tableDataRow === undefined) return;
    if (
      sFieldName === "dSinglePQty" ||
      sFieldName === "dPartsQty" ||
      sFieldName === "dSumPQty" ||
      sFieldName === "iPrintModePo" ||
      sFieldName === "iPrintMode" ||
      sFieldName === "iPrintModePo" ||
      sFieldName === "iPositiveColor" ||
      sFieldName === "iPositiveSpecialColor" ||
      sFieldName === "iOppositeColor" ||
      sFieldName === "iOppositeSpecialColor"
    ) {
      if (sFieldName === "iPrintModePo") {
        if (tableDataRow.iPrintModePo === 0) {
          tableDataRow.iPrintMode = 3;
          if (tableDataRow.iPositiveColor === 0) {
            tableDataRow.iPositiveColor = tableDataRow.iPositiveColor === 0 ? 4 : tableDataRow.iPositiveColor;
            tableDataRow.iOppositeColor = 0;
            tableDataRow.iOppositeSpecialColor = 0;
          } else {
            tableDataRow.iOppositeColor = 0;
            tableDataRow.iOppositeSpecialColor = 0;
          }
        } else if (tableDataRow.iPrintModePo === 1) {
          tableDataRow.iPrintMode = 3;
          if (tableDataRow.iPositiveColor === 0) {
            tableDataRow.iPositiveColor = 0;
            tableDataRow.iPositiveSpecialColor = 0;
            tableDataRow.iOppositeColor = tableDataRow.iOppositeColor === 0 ? 4 : tableDataRow.iOppositeColor;
          } else {
            tableDataRow.iPositiveColor = 0;
            tableDataRow.iPositiveSpecialColor = 0;
          }
        } else {
          tableDataRow.iPositiveColor = tableDataRow.iPositiveColor === 0 ? 4 : tableDataRow.iPositiveColor;
          tableDataRow.iOppositeColor = tableDataRow.iOppositeColor === 0 ? tableDataRow.iPositiveColor : tableDataRow.iOppositeColor;
        }
      } else if (sFieldName === "iPrintMode") {
        if (tableDataRow.iPrintMode === 0 || tableDataRow.iPrintMode === 1) {
          tableDataRow.iPositiveColor =
            commonUtils.isEmpty(tableDataRow.iPositiveColor) || tableDataRow.iPositiveColor === 0 ? 4 : tableDataRow.iPositiveColor;
          tableDataRow.iOppositeColor = tableDataRow.iPositiveColor;
          tableDataRow.iOppositeSpecialColor = tableDataRow.iPositiveSpecialColor;
        } else if (tableDataRow.iPrintMode === 2) {
          tableDataRow.iPositiveColor = tableDataRow.iPositiveColor === 0 ? 4 : tableDataRow.iPositiveColor;
          tableDataRow.iOppositeColor = tableDataRow.iOppositeColor === 0 ? tableDataRow.iPositiveColor : tableDataRow.iOppositeColor;
        } else if (tableDataRow.iPrintMode === 3) {
          tableDataRow.iPositiveColor = tableDataRow.iPositiveColor === 0 ? 4 : tableDataRow.iPositiveColor;
          tableDataRow.iOppositeColor = 0;
          tableDataRow.iOppositeSpecialColor = 0;
        } else if (tableDataRow.iPrintMode === 4) {
          tableDataRow.iPositiveColor = 0;
          tableDataRow.iPositiveSpecialColor = 0;
          tableDataRow.iOppositeColor = 0;
          tableDataRow.iOppositeSpecialColor = 0;
        }
      } else if (sFieldName === "iPositiveColor" || sFieldName === "iPositiveSpecialColor") {
        if (tableDataRow.iPrintMode === 0 || tableDataRow.iPrintMode === 1) {
          tableDataRow.iOppositeColor = tableDataRow.iPositiveColor;
          tableDataRow.iOppositeSpecialColor = tableDataRow.iPositiveSpecialColor;
        }
      } else if (sFieldName === "dSinglePQty") {
        /* 排版数改变时 如果该控制表合版数据只有一条 则改变packData该条的拼版数 改变备注 */
        if (commonUtils.isNotEmptyArr(packData)) {
          const packFilterData = packData.filter(item => item.sControlId === tableDataRow.sId && item.dCombineQty > 0);
          if (commonUtils.isNotEmptyArr(packFilterData) && packFilterData.length === 1) {
            const iIndex = packData.findIndex(itemPack => itemPack.sId === packFilterData[0].sId);
            const addState = {};
            if (tableDataRow.dSinglePQty > 0) {
              addState.dCombineQty = tableDataRow.dSinglePQty;
              addState.handleType = commonUtils.isEmpty(tableDataRow.handleType) ? "update" : tableDataRow.handleType;
              if (iIndex > -1) {
                packData[iIndex] = { ...packData[iIndex], ...addState };
                const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty, sCombinePartsName } = packData[iIndex];
                const tableCombineSelectedData = [];
                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; /* 合版部件名称 */
                tableCombineSelectedData.push(jsonObj);
                const sCombinedMemo = commonUtils.isNotEmptyArr(tableCombineSelectedData)
                  ? JSON.stringify(tableCombineSelectedData)
                  : ""; /* JSON对象转换为字符串存放到合版信息中 */
                tableDataRow.sCombinedMemo = commonUtils.isNotEmptyObject(sCombinedMemo) ? sCombinedMemo : "合版信息";
              }
            }
          }
        }
      }
      tableDataRow = props.singlePQtyChange(tableDataRow);
      /* 上机数量改变时,子级部件数量同步改变 */
      const { dMachineQty } = tableDataRow;
      /* 查找该节的所有子节点，将上机数量改为部件数量 */
      tableData.forEach((item, index) => {
        if (commonUtils.isNotEmptyObject(item.sAllId) && item.sAllId.indexOf(tableDataRow.sId) > -1 && item.sId !== tableDataRow.sId) {
          const addstate = {};
          addstate.dPartsQty = dMachineQty;
          tableData[index] = { ...tableData[index], ...addstate };
        }
      });
    } else if (sFieldName === "dMachineLength" || sFieldName === "dMachineWidth") {
      /* 控制表长宽改变 关联材料表type为0的上机长宽对应改变 */
      if (commonUtils.isNotEmptyArr(materialsDataOld)) {
        materialsDataOld.forEach((item, index) => {
          const itemNew = { ...item };
          if (itemNew.sControlId === tableDataRow.sId && itemNew.sType === "0") {
            itemNew.sMachineStyle = `${(tableDataRow.dMachineLength || 0).toString()}*${(tableDataRow.dMachineWidth || 0).toString()}`;
            itemNew.handleType = commonUtils.isEmpty(itemNew.handleType) ? "update" : itemNew.handleType;
          }
          materialsDataOld[index] = { ...materialsDataOld[index], ...itemNew };
        });
      }
    }
    const materialsData = [];
    const processData = [];
    materialsDataOld?.forEach(item => {
      const itemNew = { ...item };
      if (itemNew.sControlId === sId) {
        itemNew.sPartsName = tableDataRow.sPartsName;
      }
      materialsData.push(itemNew);
    });
    processDataOld.forEach(item => {
      const itemNew = { ...item };
      if (itemNew.sControlId === sId) {
        itemNew.sPartsName = tableDataRow.sPartsName;
      }
      processData.push(itemNew);
    });
    const materialsDataNew = props.sortData(tableData, materialsData);
    const processDataNew = props.sortData(tableData, processData);
    if (sFieldName === "sPartsName") {
      /* 部件名称与子部件同步 */
      const { sPartsName } = tableDataRow;
      const { treeSelectedKeys, treeData } = props;
      if (commonUtils.isNotEmptyArr(treeSelectedKeys)) {
        props.handleSearchNodes(treeSelectedKeys[0], treeData, sPartsName);
      }
    }
    const iIndex = tableData.findIndex(item => item.sId === sId);
    tableData[iIndex] = tableDataRow;
    props.onSaveState({
      [`${name}Data`]: tableData,
      materialsData: materialsDataNew,
      processData: processDataNew,
      calculated: false,
      packData,
    });
  };
  returnProps.onTableSelectRowChange = async ({ name, selectedRowKeys }) => {
    const addState = await props.onTableSelectRowChange(name, selectedRowKeys, true);
    props.onSaveState({ addState, processSelectedRowKeys: [] });
  }
  returnProps.onViewChoose = ({ name, sName, record }) => {
    const { sId } = record; /* 控制表主键 */
    const { enabled, slaveData } = props;
    let { packData } = props;
    if (sName === "sCombinedMemo") {
      const packSelectedRowKeys = [];

      /* 合并从表相同客户、产品数据 */
      const slaveDataMerge = [];
      slaveData.forEach(item => {
        const itemNew = JSON.parse(JSON.stringify(item));
        slaveDataMerge.push(itemNew);
      });

      /* 填充合版信息数值 如果packData为空，则填充从表所有数据 */
      if (commonUtils.isNotEmptyArr(slaveDataMerge)) {
        const sCombinedMemo = record?.sCombinedMemo;
        /* 根据部件 找到包含的产品 */
        slaveDataMerge.forEach((item, index) => {
          const packDataFilter = packData.filter(itemNew => itemNew.sSlaveId === item.sId && itemNew.sControlId === sId);
          if (commonUtils.isNotEmptyArr(packDataFilter)) {
            packDataFilter.forEach((itemPack) => {
              const iIndex = packData.findIndex(child => child.sId === itemPack.sId);
              if (iIndex > -1) {
                const packRowAdd = props.handlePackDataAdd(item);
                if (commonUtils.isNotEmptyObject(packRowAdd)) {
                  packData[iIndex] = { ...packData[iIndex], ...packRowAdd };
                  if (itemPack.dCombineQty !== undefined && itemPack.dCombineQty !== null && itemPack.dCombineQty !== 0
                  ) {
                    if (sCombinedMemo.includes(packData[iIndex].sProductNo)) {
                      packSelectedRowKeys.push(packData[iIndex].sId);
                    }
                  }
                }
              }
            });
          } else {
            const tableDataRow = props.handlePackDataAdd(item, index, sId, "add");
            if (commonUtils.isNotEmptyObject(tableDataRow)) {
              packData.push(tableDataRow);
            }
          }
        });
      }
      props.onSaveState({
        productCombinationVisible: true,
        sCombinationsControlId: sId /* 合版产品控制表sId */,
        enabled,
        packSelectedRowKeys,
        packData,
      });
    } else {
      props.onViewChoose(name, sName, record);
    }
  };
  return returnProps;
};

// 工序表相关事件
const processProps = props => {
  const returnProps = {};
  returnProps.onDataRowAdd = ({ name, bFinished, bModalAdd }) => {
    bModalAdd = bFinished;
    const { masterConfig } = props;
    if (bModalAdd === true) {
      let iIndex = -1;
      if (bFinished) {
        iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === "BtnChooseProductProcess");
        if (iIndex > -1) {
          props.onBtnChoose("productProcess", "process", masterConfig.gdsconfigformslave[iIndex]);
        }
      } else {
        iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === "BtnChooseProcess");
        if (iIndex > -1) {
          props.onBtnChoose("process", "process", masterConfig.gdsconfigformslave[iIndex]);
        }
      }
      return;
    }
    /*   外置处理业务   */
    const { gdsformconst, slaveData, controlData, controlSelectedRowKeys, slaveSelectedRowKeys, [`${name}Data`]: tableData = [] } = props;
    const tableDataRow = props.onDataRowAdd(name, true);
    if (commonUtils.isEmptyArr(controlSelectedRowKeys) && !bFinished) {
      message.warn(commonFunc.showMessage(gdsformconst, "pleaseChooseParts")); // 请选择部件
      return;
    }
    if (bFinished) {
      const iIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys[0]);
      if (iIndex > -1) {
        tableDataRow.sCombinePartsNameNew = `${slaveData[iIndex].sCustomerName}-${slaveData[iIndex].sProductName}`;
        tableDataRow.sCombinePartsName = slaveData[iIndex].sId;
        if (name === "materials") {
          /*  新增成品材料 */
          tableDataRow.sType = "2";
        }
        if (name === "process") {
          /*  新增成品工序 */
          tableDataRow.sType = "3";
        }
      }
    } else {
      const iIndex = controlData.findIndex(item => item.sId === controlSelectedRowKeys[0]);
      if (iIndex > -1) {
        if (commonUtils.isEmpty(controlData[iIndex].sPartsName) === "") {
          message.warn(commonFunc.showMessage(gdsformconst, "partsNameNotNull")); // 部件名称不能为空
          return;
        }
        tableDataRow.sControlId = controlData[iIndex].sId;
        tableDataRow.sPartsName = controlData[iIndex].sPartsName;
        if (name === "materials" && bFinished) {
          /*  新增成品材料 */
          tableDataRow.sType = "2";
        }
        if (name === "process" && bFinished) {
          /*  新增成品工序 */
          tableDataRow.sType = "3";
        }
      }
    }
    tableData.push(tableDataRow);
    props.onSaveState({
      [`${name}Data`]: tableData,
      [`${name}SelectedRowKeys`]: [tableDataRow.sId],
    });
  };
  returnProps.onDataRowDel = ({ name, tableSelectedRowKeys }) => {
    const { [`${name}Data`]: tableData, materialsConfig, materials0Data: materialsData } = props;
    let { materialsDelData } = props;
    if (commonUtils.isEmptyArr(materialsDelData)) {
      materialsDelData = [];
    }
    const iIndex = tableData.findIndex(item => item.sId === tableSelectedRowKeys.toString());

    const tableDelData = [];
    let returnProcessAssort = [];

    const sProcessId = tableData[iIndex].sProcessId;
    const sControlId = tableData[iIndex].sControlId;
    const processReturnData = props.onDataRowDel(name, true, tableSelectedRowKeys);

    returnProcessAssort.filter(item => item.sParentId === sProcessId).forEach(itemProcessAssort => {
      const iProcessIndex = processReturnData.processData.findIndex(
        item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === sControlId
      );
      if (iProcessIndex > -1) {
        const slaveDataFilter = processReturnData.processData[iProcessIndex];
        tableData.splice(iProcessIndex, 1);
        slaveDataFilter.handleType = "del";
        tableDelData.push(slaveDataFilter);

        /* 删除配套材料 */
        const iMaterialsIndex = materialsData.findIndex(
          item => item.sMaterialsName === slaveDataFilter.sProcessName && item.sControlId === sControlId
        );
        if (iMaterialsIndex > -1) {
          const materialsDataRow = materialsData[iMaterialsIndex];
          materialsData.splice(iMaterialsIndex, 1);
          materialsDataRow.handleType = "del";
          materialsDelData.push(materialsDataRow);
        }
      }
    });

    processReturnData.processDelData.concat(tableDelData);
    /* 删除工序对应的材料 */
    const materialsFilterDelData = materialsData.filter(item => tableSelectedRowKeys.includes(item.sProcessTbId) && item.sProcessId === sProcessId);
    let materialsSelectedDelRowKeys = [];
    if (commonUtils.isNotEmptyArr(materialsFilterDelData)) {
      materialsFilterDelData.forEach(item => {
        const materialsChildFilter = materialsData.filter(
          row => commonUtils.isNotEmptyObject(row.sParentMaterialsId) && row.sParentMaterialsId === item.sId
        ); /* 删除对应的替代料 */
        if (commonUtils.isNotEmptyArr(materialsChildFilter)) {
          materialsChildFilter.forEach(child => {
            materialsSelectedDelRowKeys.push(child.sId);
          });
        }
        materialsSelectedDelRowKeys.push(item.sId);
      });
    }
    let materialsReturnData = {};
    if (commonUtils.isNotEmptyArr(materialsSelectedDelRowKeys)) {
      materialsReturnData = props.onDataRowDel("materials0", true, materialsSelectedDelRowKeys);
      if (commonUtils.isNotEmptyObject(materialsReturnData) && commonUtils.isNotEmptyArr(materialsReturnData.materials0DelData)) {
        materialsReturnData.materials0DelData = materialsReturnData.materials0DelData.concat(materialsDelData);
      }
    }
    props.onSaveState({
      ...processReturnData,
      ...materialsReturnData,
      materialsConfig,
      materialsSelectedRowKeys: [],
    });
    return true;
  };
  returnProps.onDataChange = async ({ name, sFieldName, changeValue, sId, dropDownData }) => {
    const {
      [`${name}Data`]: tableData,
      sModelsId,
      masterData,
      slaveData,
      controlData,
      controlSelectedRowKeys,
      materials0Data: materialsData,
      processConfig,
      token,
    } = props;
    let { processDelData, materialsDelData } = props;
    const tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (tableDataRow === undefined) return;
    let iIndex = tableData.findIndex(item => item.sId === sId);
    let tableDataRowOld = {};
    let iMaterialsIndex = -1;
    let sControlId = "";
    if (iIndex > -1) {
      iMaterialsIndex = materialsData.findIndex(
        item => item.sControlId === tableData[iIndex].sControlId && item.sProcessId === tableData[iIndex].sProcessId
      );
      tableDataRowOld = tableData[iIndex];
      tableData[iIndex] = tableDataRow;
      sControlId = tableData[iIndex].sControlId;
    }
    const addState = {};
    if (sFieldName === "sProcessId" || sFieldName.includes("sProcessName")) {
      const bProcessAssort = false;
      let returnProcessAssort = [];
      let processAssignAssort = "";
      let dropDownDataProcessName;
      const sProcessParamStriIndex = processConfig.gdsconfigformslave.findIndex(item => item.sName === "sProcessParamStr" && item.bVisible);
      if (sProcessParamStriIndex > -1 && commonUtils.isNotEmptyObject(tableData[iIndex].sWorkOrderParam)) {
        tableData[iIndex].sProcessParamStr = "工艺参数";
      } else if (sProcessParamStriIndex > -1) {
        tableData[iIndex].sProcessParamStr = "";
      }
      /* 设置工单参数下拉 */
      if (commonUtils.isNotEmptyObject(tableData[iIndex].sWorkOrderParam)) {
        tableData[iIndex] = { ...tableData[iIndex], ...commonUtils.convertStrToObj(tableData[iIndex].sWorkOrderParam) };
      }
      if (bProcessAssort) {
        const dataUrl = `${commonConfig.server_host}salesorder/getProcessAssort?sModelsId=${sModelsId}`;
        const dataProcessAssort = (await commonServices.postValueService(token, {}, dataUrl)).data;
        if (dataProcessAssort.code === 1) {
          returnProcessAssort = dataProcessAssort.dataset.rows[0].processassort;
          const iIndex = processConfig.gdsconfigformslave.findIndex(item => item.sName === "sProcessName");
          if (iIndex > -1) {
            const sqlDropDownData = await props.getSqlDropDownData(sModelsId, "slave", processConfig.gdsconfigformslave[iIndex]);
            dropDownDataProcessName = sqlDropDownData.dropDownData;
            processAssignAssort = processConfig.gdsconfigformslave[iIndex].sAssignField;
          }
        }
      }
      const iControlIndex = commonUtils.isEmptyArr(controlSelectedRowKeys)
        ? -1
        : controlData.findIndex(item => item.sId === controlSelectedRowKeys[0]);
      // 配套工序
      if (bProcessAssort) {
        const newCopyTo = {};
        newCopyTo.master = masterData;
        if (commonUtils.isNotEmptyArr(slaveData)) {
          newCopyTo.slave = slaveData[0];
        }
        /* 切换工序时 先删除原工序配套工序 */
        if (commonUtils.isEmptyArr(processDelData)) {
          processDelData = [];
        }
        if (commonUtils.isEmptyArr(materialsDelData)) {
          materialsDelData = [];
        }
        returnProcessAssort.filter(item => item.sParentId === tableDataRowOld.sProcessId).forEach(itemProcessAssort => {
          const iProcessIndex = tableData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === sControlId);
          if (iProcessIndex > -1) {
            const processDataRow = tableData[iProcessIndex];
            tableData.splice(iProcessIndex, 1);
            processDataRow.handleType = "del";
            processDelData.push(processDataRow);
            /* 删除配套材料 */
            const iMaterialsIndex = materialsData.findIndex(
              item => item.sMaterialsName === processDataRow.sProcessName && item.sControlId === sControlId
            );
            if (iMaterialsIndex > -1) {
              const materialsDataRow = materialsData[iMaterialsIndex];
              materialsData.splice(iMaterialsIndex, 1);
              materialsDataRow.handleType = "del";
              materialsDelData.push(materialsDataRow);
            }
          }
        });
        if (commonUtils.isNotEmptyArr(processDelData)) {
          addState.processDelData = processDelData;
        }
        if (commonUtils.isNotEmptyArr(materialsDelData)) {
          addState.materialsDelData = materialsDelData;
        }
        iIndex = tableData.findIndex(item => item.sId === tableDataRow.sId);
        returnProcessAssort.filter(item => item.sParentId === tableDataRow.sProcessId).forEach(itemProcessAssort => {
          const iIndex = dropDownDataProcessName.findIndex(item => item.sId === itemProcessAssort.sProcessId);
          if (iIndex > -1) {
            const iNewProcessIndex =
              dropDownDataProcessName[iIndex].sType === "3"
                ? tableData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId)
                : tableData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === controlData[iControlIndex].sId);
            if (iNewProcessIndex < 0) {
              let processRow = commonFunc.getDefaultData(processConfig, newCopyTo); // 取默认值
              processRow = { ...processRow, ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo) }; // 取赋值字段
              processRow.handleType = "add";
              processRow.sId = commonUtils.createSid();
              processRow.sParentId = masterData.sId;
              processRow.sType = dropDownDataProcessName[iIndex].sType;
              if (iControlIndex > -1 && processRow.sType !== "3") {
                processRow.sControlId = controlData[iControlIndex].sId;
                processRow.sPartsName = controlData[iControlIndex].sPartsName;
              }
              tableData.push(processRow);
              if (itemProcessAssort.sType === "all") {
                controlData.filter(item => item.sId !== controlData[iControlIndex].sId).forEach(controlTableRow => {
                  const iNewProcessIndex =
                    dropDownDataProcessName[iIndex].sType === "3"
                      ? tableData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId)
                      : tableData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === controlTableRow.sId);
                  if (iNewProcessIndex < 0) {
                    let processRow = commonFunc.getDefaultData(processConfig, newCopyTo); // 取默认值
                    processRow = {
                      ...processRow,
                      ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iIndex], newCopyTo),
                    }; // 取赋值字段
                    processRow.handleType = "add";
                    processRow.sId = commonUtils.createSid();
                    processRow.sParentId = masterData.sId;
                    processRow.sType = dropDownDataProcessName[iIndex].sType;
                    if (iControlIndex > -1 && processRow.sType !== "3") {
                      processRow.sControlId = controlTableRow.sId;
                      processRow.sPartsName = controlTableRow.sPartsName;
                    }
                    tableData.push(processRow);
                  }
                });
              }
            }
          }
        });
      }
      if (tableData[iIndex].sType === "3") {
        tableData[iIndex].sControlId = "";
        tableData[iIndex].sPartsName = "";
      } else if (iControlIndex > -1) {
        tableData[iIndex].sControlId = controlData[iControlIndex].sId;
        tableData[iIndex].sPartsName = controlData[iControlIndex].sPartsName;
        if (iMaterialsIndex > -1) {
          materialsData[iMaterialsIndex].sProcessId = tableData[iIndex].sProcessId;
          materialsData[iMaterialsIndex].sProcessTbId = tableData[iIndex].sId;
          materialsData[iMaterialsIndex].sMaterialsProcessName = tableData[iIndex].sProcessName;
        }
      }
    }
    props.onSaveState({
      [`${name}Data`]: tableData,
      materials0SelectedRowKeys: [],
      ...addState,
      calculated: false,
    });
  };
  returnProps.onViewChoose = ({ name, sName, record }) => {
    const { sId } = record; /* 控制表主键 */
    const { slaveData, processConfig = {} } = props;
    let { packData } = props;
    const { gdsconfigformslave = [] } = processConfig;
    const bSWorkOrderParams = gdsconfigformslave.some(item => item.sName === "sParams" && item.sControlName === "sWorkOrder");
    const bNotSWorkOrderParams = gdsconfigformslave.some(item => item.sName === "sParams")
    if (["sCombinePartsNameNew", "sCombineProductNameNew"].includes(sName)) {
      const { [`${name}Data`]: tableData } = props;
      const iIndex = tableData.findIndex(item => item.sId === sId);
      let packDataFilter = [];
      const combinePartsSelectedRowKeys = [];
      if (iIndex > -1) {
        if (commonUtils.isNotEmptyArr(slaveData)) {
          if (tableData[iIndex].sType === "3") {
            /* 成品工序跟着从表走 */
            packDataFilter = JSON.parse(JSON.stringify(slaveData));
            packDataFilter.forEach((_, index) => {
              const packRowAdd = {};
              packRowAdd.sSlaveOldId = packRowAdd.sSlaveId;
              packRowAdd.sSlaveId = commonUtils.createSid();
              packDataFilter[index] = { ...packDataFilter[index], ...packRowAdd };
            });
          } else {
            /* 成品工序跟着合版表走 */
            packDataFilter = packData.filter(itemNew => itemNew.sControlId === tableData[iIndex].sControlId && itemNew.dCombineQty > 0);
            if (commonUtils.isNotEmptyArr(packDataFilter)) {
              packDataFilter.forEach((itemPack, index) => {
                let slaveDataRow = {};
                let packRowAdd = {};
                const iIndex = slaveData.findIndex(itemSlave => itemSlave.sId === itemPack.sSlaveId);
                if (iIndex > -1) {
                  slaveDataRow = slaveData[iIndex];
                }
                if (commonUtils.isNotEmptyObject(slaveDataRow)) {
                  packRowAdd = props.handlePackDataAdd(slaveDataRow);
                }
                packRowAdd.sSlaveOldId = packRowAdd.sSlaveId;
                packRowAdd.sSlaveId = commonUtils.createSid();
                packDataFilter[index] = { ...packDataFilter[index], ...packRowAdd };
              });
            }
          }
        }
        const sCombinePartsIds = tableData[iIndex].sCombinePartsName;
        if (commonUtils.isNotEmptyObject(sCombinePartsIds) && commonUtils.isNotEmptyArr(packDataFilter)) {
          const DataIds = sCombinePartsIds.split(",");
          for (const sId of DataIds) {
            const index = packDataFilter.findIndex(item => item.sId === sId);
            if (index > -1) {
              const rowKey = packDataFilter[index].sSlaveId;
              combinePartsSelectedRowKeys.push(rowKey);
            }
          }
        }
      }
      props.onSaveState({
        combinePartsChooseVisible: true,
        combinePartsData: packDataFilter,
        processSelectedRowId: sId /* 工序表选中行sId */,
        combinePartsSelectedRowKeys,
      });
    } else if (sName === "sParams" && bSWorkOrderParams) {
      props.onSaveState({
        sWorkParamsModalVisible: true,
      });
    } else if (sName === "sParams" && bNotSWorkOrderParams) {
      props.onSaveState({
        sWorkParamsModalVisible: true,
      });
    } else {
      props.onViewChoose(name, sName, record);
    }
  };
  return returnProps;
};

// 材料表相关事件
const materialsProps = props => {
  const returnProps = {};
  returnProps.onDataRowAdd = params => {
    const { bFinished } = params;
    let { bModalAdd } = params;
    bModalAdd = bFinished
    const { masterConfig } = props;
    if (bModalAdd === true) {
      let iIndex = -1;
      if (bFinished) {
        iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === "BtnChooseProductMaterials");
        if (iIndex > -1) {
          props.onBtnChoose("productMaterials", "materials", masterConfig.gdsconfigformslave[iIndex]);
        }
      } else {
        iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === "BtnChooseMaterials");
        if (iIndex > -1) {
          props.onBtnChoose("materials", "materials", masterConfig.gdsconfigformslave[iIndex]);
        }
      }
      return;
    } else {
      processProps(props).onDataRowAdd(params);
    }
  };
  returnProps.onDataChange = async ({ name, sFieldName, changeValue, sId, dropDownData }) => {
    const { [`${name}Data`]: tableData, controlData, controlSelectedRowKeys, app, sModelsId } = props;
    const tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (tableDataRow === undefined) return;
    if (Object.keys(changeValue).length > 0 && Object.keys(changeValue).findIndex(item => item === "dMaterialsStockAuxiliaryQty") > -1) {
      const urlMaterialsStock = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
      const valueMaterialsStock = {
        sProName: "Sp_Inventory_MaterialsInventoryV56",
        paramsMap: {
          sMaterialsGuid: tableDataRow.sMaterialsId,
          sMaterialsStyle: tableDataRow.sMaterialsStyle,
          sWarehouseGuid: tableDataRow.sWarehouseId,
          sLocationalGuid: tableDataRow.sLocationId,
          sWarehouseLocationGuid: tableDataRow.sWarehouseLocationId,
          sDefine_no: tableDataRow.sDefineNo,
          sDefine_no2: tableDataRow.sDefineNo2,
          iGetQty: 1,
          iHasZero: 1,
        },
      };
      const returnDataMaterialsStock = (await commonServices.postValueService(app.token, valueMaterialsStock, urlMaterialsStock)).data;
      if (returnDataMaterialsStock.code === 1) {
        tableDataRow.dMaterialsStockAuxiliaryQty = returnDataMaterialsStock.dataset.rows[0].dataSet.outData[0].dAuxiliaryQty;
      }
    }
    if (Object.keys(changeValue).length > 0 && Object.keys(changeValue).findIndex(item => item === "dMaterialsStockAvailableQty") > -1) {
      const urlMaterialsAvailableQty = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
      const valueMaterialsAvailableQty = {
        sProName: "Sp_Inventory_MaterialsInventoryV56",
        paramsMap: {
          sMaterialsGuid: tableDataRow.sMaterialsId,
          sMaterialsStyle: tableDataRow.sMaterialsStyle,
          sWarehouseGuid: tableDataRow.sWarehouseId,
          sLocationalGuid: tableDataRow.sLocationId,
          sWarehouseLocationGuid: tableDataRow.sWarehouseLocationId,
          sDefine_no: tableDataRow.sDefineNo,
          sDefine_no2: tableDataRow.sDefineNo2,
          iGetQty: 2,
          iHasZero: 1,
        },
      };
      const returnDataMaterialsAvailableQty = (await commonServices.postValueService(app.token, valueMaterialsAvailableQty, urlMaterialsAvailableQty))
        .data;
      if (returnDataMaterialsAvailableQty.code === 1) {
        tableDataRow.dMaterialsStockAvailableQty = returnDataMaterialsAvailableQty.dataset.rows[0].dataSet.outData[0].dAuxiliaryQty;
      }
    }
    const iIndex = tableData.findIndex(item => item.sId === sId);
    if (iIndex > -1) {
      tableData[iIndex] = tableDataRow;
    }
    if (sFieldName === "sType") {
      if (tableData[iIndex].sType === "2") {
        tableData[iIndex].sControlId = "";
        tableData[iIndex].sPartsName = "";
      } else {
        const iControlIndex = commonUtils.isEmptyArr(controlSelectedRowKeys)
          ? -1
          : controlData.findIndex(item => item.sId === controlSelectedRowKeys[0]);
        if (iControlIndex > -1) {
          tableData[iIndex].sControlId = controlData[iControlIndex].sId;
          tableData[iIndex].sPartsName = controlData[iControlIndex].sPartsName;
        }
      }
    }
    props.onSaveState({ [`${name}Data`]: tableData, calculated: false });
  };
  returnProps.onViewChoose = ({ name, sName, record }) => {
    const { sId } = record; /* 控制表主键 */
    const { slaveData } = props;
    if (["sCombinePartsNameNew", "sCombineProductNameNew"].includes(sName)) {
      const { [`${name}Data`]: tableData } = props;
      const iIndex = tableData.findIndex(item => item.sId === sId);
      let packDataFilter = [];
      const combinePartsSelectedRowKeys = [];
      if (iIndex > -1) {
        if (commonUtils.isNotEmptyArr(slaveData)) {
          if (tableData[iIndex].sType === "2") {
            /* 成品材料跟着从表走 */
            packDataFilter = JSON.parse(JSON.stringify(slaveData));
            packDataFilter.forEach((_, index) => {
              const packRowAdd = {};
              packRowAdd.sSlaveOldId = packRowAdd.sSlaveId;
              packRowAdd.sSlaveId = commonUtils.createSid();
              packDataFilter[index] = { ...packDataFilter[index], ...packRowAdd };
            });
          }
        }
        const sCombinePartsIds = tableData[iIndex].sCombinePartsName;
        if (commonUtils.isNotEmptyObject(sCombinePartsIds) && commonUtils.isNotEmptyArr(packDataFilter)) {
          const DataIds = sCombinePartsIds.split(",");
          for (const sId of DataIds) {
            const index = packDataFilter.findIndex(item => item.sId === sId);
            if (index > -1) {
              const rowKey = packDataFilter[index].sSlaveId;
              combinePartsSelectedRowKeys.push(rowKey);
            }
          }
        }
      }
      props.onSaveState({
        combinePartsChooseVisible: true,
        combinePartsData: packDataFilter,
        materialsSelectedRowId: sId /* 工序表选中行sId */,
        openTable: "materials",
        combinePartsSelectedRowKeys,
      });
    } else {
      props.onViewChoose(name, sName, record);
    }
  };
  return returnProps;
};

// 合版信息相关事件
const packProps = props => {
  const returnProps = {};
  returnProps.onDataChange = async ({ name, sFieldName, changeValue, sId, dropDownData }) => {
    const { packData, packSelectedRowKeys } = props;
    const tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (tableDataRow === undefined) return;
    const iIndex = packData.findIndex(item => item.sId === sId);
    packData[iIndex] = tableDataRow;
    if (sFieldName === "dCombineQty" || sFieldName === "dProductQty") {
      props.handleGetdFactProductQty(packSelectedRowKeys, packData);
    }
    props.onSaveState({ packData, calculated: false });
  };
  return returnProps;
};

// 入口
const WorkOrderPackTableTreeNew = baseProps => {
  const commonPackProps = { ...baseProps, ...CommonPackEvent(baseProps) };
  const otherProps = {
    slaveProps: slaveProps(commonPackProps),
    controlProps: controlProps(commonPackProps),
    processProps: processProps(commonPackProps),
    materialsProps: materialsProps(commonPackProps),
    packProps: packProps(commonPackProps),
  };
  const props = WorkOrderPackTableTreeNewEvent({ ...commonPackProps, ...otherProps });
  const { masterData } = props;
  if (!masterData) return "";

  return <WorkOrderPackTableTreeNewComponent {...props} />;
};

// 包一层Form
const WorkOrderPackTableTreeNewComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData, masterConfig } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form, masterConfig);
    return obj;
  },
})(props => {
  props.onReturnForm(props.form);
  if (!props.currentForm) {
    props.setForm(props.form);
  }
  const { currentPane } = props.app;
  let  bFlow = currentPane?.bFlow; /* 是否需要展示审批流程信息 */
  return (
    <div className={`xly-workorder-list ${styles.WorkOrderPackTableTreeNew}`} style={{ display: bFlow ? 'flex':'block' }} >
      <ToolBarComponent {...props} />
      <div className={styles.content}   style={{ width: bFlow ? '75%':'100%' }}>
        <AvatarComponent {...props} />
        <MasterComponent {...props} />
        <SlaveComponent {...props} />
        <ControlComponent {...props} />
        <OtherComponent {...props} />
      </div>
        {
          bFlow ?
          <div id='examInfo' style={{ float:'left', width:'25%', textAlign:'center', height:'900px', maxHeight: 'calc(100vh - 130px)' , backgroundColor:'#f0f0f0'}}>
            <CommonExamInfo {...props} />
          </div>
          : ''
        }
      <CommonModal {...props} />
    </div>
  );
});

// ToolBar
const ToolBarComponent = props => {
  return (
    <div className={styles.header}>
      <Toolbar {...props} className="billBtnGroup" style={{ backgroundColor: "#646464", color: "rgb(255,255,255)" }} />
    </div>
  );
};

// 审核状态
const AvatarComponent = props => {
  const { masterData, sModelsType, app } = props;
  const imgSrc = commonBusiness.handleAddIcon(masterData, sModelsType, app);
  if (!imgSrc) return "";
  return (
    <div className={styles.avatar}>
      <Avatar src={imgSrc} />
    </div>
  );
};

// 主表
const MasterComponent = props => {
  const { masterConfig: masterConfigOld } = props;
  const addProps = {};
  if (commonUtils.isNotEmptyObject(masterConfigOld)) {
    const masterConfig = JSON.parse(JSON.stringify(masterConfigOld));
    const delList = ["dProductQty", "sCustomerName", "sProductClassifyName", "sProductName", "sProductStyle"];

    delList.forEach(delName => {
      const iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === delName);
      if (iIndex > -1) {
        masterConfig.gdsconfigformslave.splice(iIndex, 1);
      }
    });

    addProps.masterConfig = masterConfig;
  }

  const propsType = {
    ...props,
    ...addProps,
    onChange: props.onMasterChange,
  };
  return (
    <div className={`bill-search-group ${styles.masterView}`}>
      <CommonView {...propsType} />
    </div>
  );
};

// 从表
const SlaveComponent = props => {
  const { sTableType, slaveData, slavePagination } = props;

  let slaveTreeData = slaveData;
  const bTree = sTableType === "single" && slaveData?.some(item => !!item.sFatherSlaveId);

  if (bTree) {
    slaveTreeData = useMemo(() => commonUtils.genTreeByArr(slaveData, "sNodeId", "sFatherSlaveId"), [JSON.stringify(slaveData)]);
  }

  const pagination = {
    total: slaveData?.length || 0,
    current: slavePagination?.current || 1,
    size: "large",
    pageSize: commonConfig.pageSize,
    showQuickJumper: true,
    hideOnSinglePage: true,
  };

  const { setAdd, setCopy, setDelete } = props.handleGetIcon();

  const slaveTableProps = {
    ...commonBusiness.getTableTypes("slave", props),
    onKeyDown: props.onKeyDown,
    data: slaveTreeData,
    tableProps: {
      rowSelection: null,
      pagination,
      onChange: props.onTitleChange,
      setAdd,
      setCopy,
      setDelete,
      AutoTableHeight: "100%",
      bShowTreeAddChild: true,
    },
    onExpand: props.onExpandTreeSingle,
    onTreeAdd: props.onDataRowAdd,
    onTreeAddChild: props.onDataRowAdd,
    onTreeCopyAll: props.onDataRowCopyAll,
    onTreeDel: props.onDataRowDel,
  };
  return (
    <div className={styles.slaveTable}>
      <StaticEditTable {...slaveTableProps} setOpterationColumn="Y" selfTableHeight={82} noVlist />
      {props.getCustomTabPaneExtra("slave")}
    </div>
  );
};

// 控制表
const ControlComponent = props => {
  const {
    masterConfig,
    slaveData = [],
    slaveSelectedRowKeys = [],
    controlConfig,
    controlData = [],
    controlSelectedRowKeys = [],
    showAllTreeVisible,
  } = props;

  if (!controlConfig) return "";

  let bControlShow = masterConfig.gdsconfigformslave.find(item => item.sControlName === "tbControl")?.bVisible;
  bControlShow = bControlShow === undefined ? true : bControlShow;
  if (!bControlShow) return "";

  // 关联slave合版进行筛选control的数据
  let controlTableData = [];
  const iSlaveIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys[0]);
  const slaveSelectedRow = iSlaveIndex !== -1 ? slaveData[iSlaveIndex] : { sProductNo: 0 };
  if (iSlaveIndex !== -1) {
    controlData.forEach(item => {
      if (item.sCombinedMemo && item.sCombinedMemo !== "合版信息") {
        const sCombinedMemoArr = commonUtils.convertStrToObj(item.sCombinedMemo, []);

        const slaveSelectedRowChildren = props.handleGetSlaveSelectedRowChildren(slaveData, slaveSelectedRow.sId);
        const slaveRows = [slaveSelectedRow, ...slaveSelectedRowChildren];
        const len = sCombinedMemoArr.filter(item => item.sProductNo && slaveRows.some(slaveRow => slaveRow.sProductNo === item.sProductNo)).length;
        if (len) {
          controlTableData.push(item);
        }
      } else {
        controlTableData.push(item);
      }
    });
  } else {
    controlTableData = controlData.slice(0);
  }
  // 之前代码默认会选中第一行，第一行可能已经被筛选掉，需要判断
  if (
    controlTableData.length &&
    controlSelectedRowKeys[0] !== controlTableData[0].sId &&
    !controlTableData.map(item => item.sId).includes(controlSelectedRowKeys[0])
  ) {
    if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
      props.onSaveState({
        controlSelectedRowKeys: [controlTableData[0].sId],
      });
    }
  }

  const { setCopy } = props.handleGetIcon();

  const bShowProcess = masterConfig.gdsconfigformslave.some(item => item.sControlName === "BtnChooseProcess");

  const bShowMaterials = masterConfig.gdsconfigformslave.some(item => item.sControlName === "BtnChooseMaterials");

  const chooseProcessConfigRow = masterConfig.gdsconfigformslave.find(item => item.sControlName === "BtnChooseProcess");
  const chooseMaterialsConfigRow = masterConfig.gdsconfigformslave.find(item => item.sControlName === "BtnChooseMaterials");

  const bDragConfig = controlConfig.gdsconfigformslave.find(item => item.sControlName === "bTableDrag")?.bVisible || false;

  const controlPropsType = {
    ...commonBusiness.getTableTypes("control", props),
    data: commonUtils.genTreeByArr(controlTableData, "sNodeId", "sControlParentId"),
    onKeyDown: props.onKeyDown,
    tableProps: {
      setCopy,
      setProcess: bShowProcess,
      setMaterial: bShowMaterials,
      bShowTreeAdd: true,
      bShowTreeAddChild: true,
      bShowTreeDel: true,
      bShowTreeCopyAll: true,
      setNoCommonOperate: true,
      chooseProcessConfigRow,
      chooseMaterialsConfigRow,
      AutoTableHeight: 232,
    },
    onTreeAdd: props.onDataRowAdd,
    onTreeAddChild: props.onDataRowAdd,
    onTreeCopyAll: props.onDataRowCopyAll,
    onTreeDel: props.onDataRowDel,
    onMoveRow: props.onMoveRow,
    isDragAndDrop: bDragConfig,
    bRowClickRepeat: true,
    bRowClick: true,
  };

  const controlShowPropsType = {
    ...commonBusiness.getTableTypes("control", props),
    data: commonUtils.genTreeByArr(controlTableData, "sId", "sControlParentId"),
    onKeyDown: props.onKeyDown,
    bMutiSelect1: true, // 设置点击整行勾选框不勾选，只有点击勾选框才勾选
    tableProps: {
      AutoTableHeight: 550,
      expandable: props.controlShowExpandedRowKeys,
    },
    onExpand: props.onExpandTreeSingleShow,
  };

  const onCancel = () => {
    props.onSaveState({ showAllTreeVisible: false });
  };
  const DisplayComponentStructure = commonFunc.showLocalMessage(props, "DisplayComponentStructure", "展示部件结构");
  return (
    <div className={styles.controlTable}>
      <StaticEditTable {...controlPropsType} setOpterationColumn="Y" selfTableHeight={82} noVlist />
      {props.getCustomTabPaneExtra("control")}
      {showAllTreeVisible && (
        <AntdDraggableModal
          width={1300}
          title={DisplayComponentStructure}
          open={showAllTreeVisible}
          onCancel={onCancel}
          bodyStyle={{
            padding: 0,
            mxHeight: "650px",
            overflow: "auto",
            backgroundColor: "#ffffff",
            paddingTop: -34,
          }}
          footer={null}
        >
          <div className="processList" style={{ marginBottom: "0px", position: "sticky", top: "0px", zIndex: 99 }}>
            <StaticEditTable {...controlShowPropsType} tableBelone="list" noVlist />
          </div>
        </AntdDraggableModal>
      )}
    </div>
  );
};

// 其他表布局
const OtherComponent = props => {
  const { app, materialsChildInfoList, colorConfig , masterConfig } = props;

  if (materialsChildInfoList === undefined) return "";

  const { commonConst } = app;

  let bSplitProcess = false; /* 拆分工序 */
  if (commonUtils.isNotEmptyObject(masterConfig)) {
    const iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === 'bSplitProcess');
    if (iIndex > -1) {
      bSplitProcess = masterConfig.gdsconfigformslave[iIndex].bVisible;
    }
  }


  let bSplitMaterials = false; /* 拆分材料 */
  if (commonUtils.isNotEmptyObject(masterConfig)) {
    const iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === 'bSplitMaterials');
    if (iIndex > -1) {
      bSplitMaterials = masterConfig.gdsconfigformslave[iIndex].bVisible;
    }
  }

  const [processTabValue, setProcessTabValue] = useState("processInfo");
  const processInfo = commonFunc.showMessage(commonConst, "processInfo"); // 工序信息
  const dailyInfo = commonFunc.showMessage(commonConst, "dailyInfo"); // 日志信息
  // const visionInfo = "改版记录";
  // const colorInfo = "工艺颜色";
  const visionInfo = commonUtils.isNotEmptyObject(commonFunc.showMessage(commonConst, "visionInfo")) ?
    commonFunc.showMessage(commonConst, "visionInfo") : '改版记录';
  const colorInfo = commonUtils.isNotEmptyObject(colorConfig) && commonUtils.isNotEmptyObject(colorConfig.showName) ?
    colorConfig.showName :
    commonUtils.isNotEmptyObject(commonFunc.showMessage(commonConst, "colorInfo")) ?
      commonFunc.showMessage(commonConst, "colorInfo") : '工艺颜色'; //  "工艺颜色";

  const productMaterialsInfo = commonFunc.showMessage(app.commonConst, 'productMaterialsInfo');/* 成品材料 */
  const productProcessInfo = commonFunc.showMessage(app.commonConst, 'productProcessInfo');/* 成品工序 */

  const [materialsTabValue, setMaterialsTabValue] = useState(12);

  const panelExtra = (type, { selfName, selfId } = {}) => {
    let str = "";
    if (type === "material") {
      const radioConfigArr = props.formData.filter(item => item.sGrd?.includes(type) && item.bGrdVisible);

      str = (
        <div>
          <Radio.Group
            defaultValue={materialsTabValue}
            onChange={e => {
              setMaterialsTabValue(e.target.value);
            }}
          >
            {radioConfigArr.map((child, index) => {
              const radioTitle = child.showName;
              const radioValue = index + 2 + 10;
              return <Radio value={radioValue}>{radioTitle}</Radio>;
            })}
            {bSplitMaterials ? <Radio value={22}>{productMaterialsInfo}</Radio> : ""}
          </Radio.Group>
        </div>
      );
    } else if (type === "process") {
      str = (
        <div>
          <Radio.Group
            defaultValue={processTabValue}
            onChange={e => {
              setProcessTabValue(e.target.value);
            }}
          >
            <Radio value={"processInfo"}>{processInfo}</Radio>
            {bSplitProcess ? <Radio value={'productProcessInfo'}>{productProcessInfo}</Radio> : ""}
          </Radio.Group>
        </div>
      );
    } else if (type === "daily") {
      str = (
        <div>
          <Radio.Group defaultValue="daily">
            <Radio value="daily">{dailyInfo}</Radio>
          </Radio.Group>
        </div>
      );
    } else if (type === "vision") {
      str = (
        <div>
          <Radio.Group defaultValue="vision">
            <Radio value="vision">{visionInfo}</Radio>
          </Radio.Group>
        </div>
      );
    } else if (type === "color") {
      str = (
        <div>
          <Radio.Group defaultValue="color">
            <Radio value="color">{colorInfo}</Radio>
          </Radio.Group>
        </div>
      );
    } else if (selfName) {
      str = (
        <div>
          <Radio.Group defaultValue={selfId}>
            <Radio value={selfId}>{selfName}</Radio>
          </Radio.Group>
        </div>
      );
    }
    return str;
  };

  const [activeKey, setActiveKey] = useState(["process", "material", "color", "vision", ...materialsChildInfoList]);
  const getHeaderIcon = tablename => (
    <RightOutlined
      style={{
        fontSize: 11,
        transition: "ease 0.3s",
        transform: `rotate(${activeKey.includes(tablename) ? "90deg" : "0deg"})`,
      }}
    />
  );

  // 过滤出不是替代料的子表
  const materialsChildInfoListFilter = materialsChildInfoList.filter(tablename => props[`${tablename}Config`]?.sChinese !== "替代料") || [];

  return (
    <Collapse defaultActiveKey={activeKey} onChange={setActiveKey} className={`custom-collapse ${styles.collapse}`}>
      <Panel collapsible="header" header={getHeaderIcon("process")} showArrow={false} extra={panelExtra("process")} key="process">
        {processTabValue === "processInfo" && <ProcessComponent {...props} />}
        { processTabValue === "productProcessInfo" &&  <ProductProcessComponent {...props} /> }
      </Panel>

      <Panel collapsible="header" header={getHeaderIcon("material")} showArrow={false} extra={panelExtra("material")} key="material">
        <MaterialsComponent {...props} materialsTabValue={materialsTabValue} />
        { materialsTabValue === 22 &&  <ProductMaterialsComponent {...props} /> }
      </Panel>
      {materialsChildInfoListFilter.map(tablename => {
        const { sChinese } = props[`${tablename}Config`];
        return (
          <Panel
            collapsible="header"
            header={getHeaderIcon(tablename)}
            showArrow={false}
            extra={panelExtra("", { selfName: sChinese, selfId: tablename })}
            key={tablename}
          >
            <MaterialsChildComponent {...props} materialsChildName={tablename} />
          </Panel>
        );
      })}

      {props.colorConfig && (
        <Panel collapsible="header" header={getHeaderIcon("color")} showArrow={false} extra={panelExtra("color")} key="color">
          <ColorComponent {...props} />
        </Panel>
      )}

      {props.visionConfig && (
        <Panel collapsible="header" header={getHeaderIcon("vision")} showArrow={false} extra={panelExtra("vision")} key="vision">
          <VisionComponent {...props} />
        </Panel>
      )}

      {props.dailyConfig && (
        <Panel collapsible="header" header={getHeaderIcon("daily")} showArrow={false} extra={panelExtra("daily")} key="daily">
          <DailyComponent {...props} />
        </Panel>
      )}
    </Collapse>
  );
};

// 工序表
const ProcessComponent = props => {
  const { processConfig, controlSelectedRowKeys } = props;
  if (!processConfig) return "";

  const processTableId = useRef(`processTableId_${commonUtils.createSid()}`);
  const { setAdd, setCopy, setDelete } = props.handleGetIcon();

  const bProcessSort = processConfig.gdsconfigformslave.find(item => item.sControlName === "handleSort")?.bVisible || false;

  const baseData = commonBusiness.getTableTypes("process", props);
  const processPropsType = {
    ...baseData,
    data: props.dataFilter(props, baseData, "process"),
    filteredValue: controlSelectedRowKeys,
    onFilterData: props.onFilterData,
    OnGetFilterData: props.OnGetFilterData,
    onKeyDown: props.onKeyDown,
    tableProps: {
      rowSelection: null,
      setAdd,
      setCopy,
      setDelete,
      AutoTableHeight: "100%",
      sticky: true,
      // sticky: layoutChange ? { offsetHeader: stickyHeight } : true
    },
    onDrag: props.onDrag,
    isDragAndDrop: false,
    setOpterationColumn: "Y",
    bModalAdd: true,
    dragHandle: bProcessSort && props.enabled,
    selfTableHeight: 330,
    noVlist: true,
    tableId: processTableId.current,
  };

  const getProcessTable = () => <StaticEditTable {...processPropsType} />;

  const showLeftConfig = processConfig.gdsconfigformslave.find(item => item.sControlName === "bShowLeft");

  if (showLeftConfig) {
    const { iColValue, showName: processShowTitle } = showLeftConfig;

    const processTitleWidth = processConfig.gdsconfigformslave.find(item => item.sControlName === "titleWidth")?.sDefault;
    const commonViewDragableProps = {
      ...props,
      hideTabsNav: true,
      processTitleWidth,
      comparedTableId: processTableId.current,
      sParamData: [
        {
          sParamType: "sWorkOrder",
          sParamName: "工单参数",
        },
      ],
      tableName: "process",
    };
    return (
      <Row gutter={[8, 0]}>
        <Col span={iColValue} order={1} id={processTableId.current}>
          {getProcessTable()}
        </Col>
        <Col span={24 - iColValue} order={2}>
          {processShowTitle && (
            <Divider className="workOrderDivider" orientation="center">
              {processShowTitle}
            </Divider>
          )}
          <CommonViewDragable {...commonViewDragableProps} />
        </Col>
      </Row>
    );
  } else {
    return getProcessTable();
  }
};

// 成品工序表
const ProductProcessComponent = props => {
  const { finishedProcessConfig, controlSelectedRowKeys } = props;
  if (!finishedProcessConfig) return "";

  const productProcessTableId = useRef(`productProcessTableId_${commonUtils.createSid()}`);
  const { setAdd, setCopy, setDelete } = props.handleGetIcon();

  const bProcessSort = finishedProcessConfig.gdsconfigformslave.find(item => item.sControlName === "handleSort")?.bVisible || false;

  const baseData = commonBusiness.getTableTypes("process", props);
  const finishedProcessPropsType = {
    ...baseData,
    configName: 'finishedProcess',
    config: finishedProcessConfig,
    data: props.processFilteNew(props, baseData, 'process', true),
    filteredValue: controlSelectedRowKeys,
    onFilterData: props.onFilterData,
    OnGetFilterData: props.OnGetFilterData,
    onKeyDown: props.onKeyDown,
    tableProps: {
      rowSelection: null,
      setAdd,
      setCopy,
      setDelete,
      AutoTableHeight: "100%",
      sticky: true,
      // sticky: layoutChange ? { offsetHeader: stickyHeight } : true
    },
    onDrag: props.onDrag,
    isDragAndDrop: false,
    setOpterationColumn: "Y",
    bModalAdd: true,
    dragHandle: bProcessSort && props.enabled,
    selfTableHeight: 330,
    noVlist: true,
    tableId: productProcessTableId.current,
  };

  const getProductProcessTable = () => <StaticEditTable {...finishedProcessPropsType}  bFinished  bModalAdd />;

  const showLeftConfig = finishedProcessConfig.gdsconfigformslave.find(item => item.sControlName === "bShowLeft");

  if (showLeftConfig) {
    const { iColValue, sChinese: processShowTitle } = showLeftConfig;

    const processTitleWidth = finishedProcessConfig.gdsconfigformslave.find(item => item.sControlName === "titleWidth")?.sDefault;
    const commonViewDragableProps = {
      ...props,
      hideTabsNav: true,
      processTitleWidth,
      comparedTableId: productProcessTableId.current,
      sParamData: [
        {
          sParamType: "sWorkOrder",
          sParamName: "工单参数",
        },
      ],
      tableName: "process",
    };
    return (
      <Row gutter={[8, 0]}>
        <Col span={iColValue} order={1} id={productProcessTableId.current}>
          {getProductProcessTable()}
        </Col>
        <Col span={24 - iColValue} order={2}>
          {processShowTitle && (
            <Divider className="workOrderDivider" orientation="center">
              {processShowTitle}
            </Divider>
          )}
          <CommonViewDragable {...commonViewDragableProps} />
        </Col>
      </Row>
    );
  } else {
    return getProductProcessTable();
  }
};

// 材料表
const MaterialsComponent = props => {
  const { materialsInfoList = [], materialsChildInfoList = [], materialsTabValue } = props;

  const { setAdd, setCopy, setDelete } = props.handleGetIcon();

  // 主材料表格配置
  const materialsTablePropsList = {};
  materialsInfoList.forEach((item, index) => {
    const baseProps = commonBusiness.getTableTypes(`materials${index}`, props);

    /* 全部材料 是否可排序 */
    const bMaterialsSort = baseProps.config.gdsconfigformslave.find(item => item.sControlName === "handleSort")?.bVisible;

    materialsTablePropsList[`materialsTable${index}Props`] = {
      ...baseProps,
      onKeyDown: props.onKeyDown,
      data: props.materialsFilterNew(props, baseProps, `materials${index}`),
      tableProps: {
        setAdd,
        setCopy,
        setDelete,
        AutoTableHeight: "100%",
      },
      setOpterationColumn: "Y",
      noVlist: true,
      dragHandle: bMaterialsSort,
      selfTableHeight: 82,
    };
  });

  // 子材料表配置
  const materialsChildTablePropsList = {};
  // 只过滤出替代料
  const materialsChildInfoListFilter = materialsChildInfoList.filter(tablename => props[`${tablename}Config`]?.sChinese === "替代料");
  materialsChildInfoListFilter.forEach(item => {
    const baseProps = commonBusiness.getTableTypes(`${item}`, props);
    materialsChildTablePropsList[`${item}TableProps`] = {
      ...baseProps,
      data: props.materialsFilterNew(props, baseProps, item),
      tableProps: {
        setAdd,
        setCopy,
        setDelete,
        AutoTableHeight: "100%",
      },
      onDrag: props.onDrag,
      setOpterationColumn: "Y",
      noVlist: true,
      selfTableHeight: 82,
    };
  });

  return materialsInfoList.map((item, index) => {
    let num = 12 + index;
    const materialsOtherPropsType = materialsTablePropsList[`materialsTable${index}Props`];
    let sWidth = "100%";
    let sRightWidth = "100%";

    /* 找到子级 左右列 */
    let materialsChildTableProps;
    let materialsChildTableTitle = "子表记录";
    if (commonUtils.isNotEmptyArr(materialsChildInfoListFilter)) {
      const iIndex = materialsChildInfoListFilter.findIndex(child => child.includes(item));
      if (iIndex > -1) {
        materialsChildTableProps = materialsChildTablePropsList[`${item}ChildTableProps`];
        sWidth = "58.5%";
        sRightWidth = "42%";
        materialsChildTableTitle = materialsChildTableProps.config.showName || "";
      }
    } else {
      sWidth = "100%";
    }

    // 限制编辑-劲嘉定制
    if (index === 0 || index === 3) {
      materialsOtherPropsType.otherlimitDisabled = params => {
        const { record, sName } = params;
        let { enabledNew } = params;
        if (!["101251240115016082594412050"].includes(props.sModelsId)) return enabledNew;
        if (enabledNew && ["dAuxiThousheetQty"].includes(sName) && record.dPackageQty > 0) {
          enabledNew = false;
        }
        return enabledNew;
      };
    }

    return (
      materialsTabValue === num && (
        <div className="dlhStyle">
          <div style={{ position: "relative", width: sWidth }}>
            <StaticEditTable {...materialsOtherPropsType} />
            {/* {index === 0 && (
              <div className={styles.delAll}>
                <Button
                  type="primary"
                  disabled={!props.enabled}
                  // onClick={props.onDeleteAllMaterials.bind(
                  //   this,
                  //   materialsOtherPropsType.data
                  // )}
                >
                  删除全部
                </Button>
              </div>
            )} */}
          </div>
          {materialsChildTableProps ? (
            <div style={{ width: sRightWidth, position: "relative" }}>
              <div className="fixChildTitle">
                {" "}
                <Radio.Group defaultValue={1}>
                  <Radio value={1}>{materialsChildTableTitle}</Radio>
                </Radio.Group>{" "}
              </div>
              <StaticEditTable {...materialsChildTableProps} />
            </div>
          ) : (
            ""
          )}
        </div>
      )
    );
  });
};

// 成品材料表
const ProductMaterialsComponent = props => {
  const { finishedMaterialsConfig, controlSelectedRowKeys } = props;
  if (!finishedMaterialsConfig) return "";

  const productMaterialsTableId = useRef(`productMaterialsTableId_${commonUtils.createSid()}`);
  const { setAdd, setCopy, setDelete } = props.handleGetIcon();


  const baseData = commonBusiness.getTableTypes("materials0", props);
  const finishedMaterialsPropsType = {
    ...baseData,
    configName: 'finishedMaterials',
    config: finishedMaterialsConfig,
    data: props.materialsFilterNew(props, baseData, 'finishedMaterials', true),
    filteredValue: controlSelectedRowKeys,
    onFilterData: props.onFilterData,
    OnGetFilterData: props.OnGetFilterData,
    onKeyDown: props.onKeyDown,
    tableProps: {
      rowSelection: null,
      setAdd,
      setCopy,
      setDelete,
      AutoTableHeight: "100%",
      sticky: true,
      // sticky: layoutChange ? { offsetHeader: stickyHeight } : true
    },
    onDrag: props.onDrag,
    isDragAndDrop: false,
    setOpterationColumn: "Y",
    bModalAdd: true,
    selfTableHeight: 330,
    noVlist: true,
    tableId: productMaterialsTableId.current,
  };

  const getProductMaterialsTable = () => <StaticEditTable {...finishedMaterialsPropsType}  bFinished  bModalAdd />;

  return getProductMaterialsTable();
};

// 子材料表
const MaterialsChildComponent = props => {
  const { materialsChildName } = props;

  const { setAdd, setCopy, setDelete } = props.handleGetIcon();

  const baseProps = commonBusiness.getTableTypes(materialsChildName, props);
  const materialsChildProps = {
    ...baseProps,
    data: props.materialsFilterNew(props, baseProps, materialsChildName),
    tableProps: {
      setAdd,
      setCopy,
      setDelete,
      AutoTableHeight: "100%",
    },
    onDrag: props.onDrag,
    setOpterationColumn: "Y",
    noVlist: true,
    selfTableHeight: 82,
  };

  return <StaticEditTable {...materialsChildProps} />;
};

// 工艺颜色
const ColorComponent = props => {
  const { colorData = [], colorPagination } = props;

  const { setAdd, setCopy, setDelete } = props.handleGetIcon();

  const pagination = {
    total: colorData.length,
    current: colorPagination?.current || 1,
    size: "large",
    pageSize: commonConfig.pageSize,
    showQuickJumper: true,
    hideOnSinglePage: true,
  };

  const colorRecordTableProps = {
    ...commonBusiness.getTableTypes("color", props),
    onKeyDown: props.onKeyDown,
    tableProps: {
      rowSelection: null,
      pagination,
      onChange: props.onTitleChange,
      setAdd,
      setCopy,
      setDelete,
      AutoTableHeight: "100%",
      setOpterationColumn: "Y",
      selfTableHeight: 82,
      noVlist: true,
    },
  };

  return <StaticEditTable {...colorRecordTableProps} />;
};

// 改版表
const VisionComponent = props => {
  const { visionData = [], visionPagination } = props;

  const { setAdd, setCopy, setDelete } = props.handleGetIcon();

  const pagination = {
    total: visionData.length,
    current: visionPagination?.current || 1,
    size: "large",
    pageSize: commonConfig.pageSize,
    showQuickJumper: true,
    hideOnSinglePage: true,
  };

  const visionRecordTableProps = {
    ...commonBusiness.getTableTypes("vision", props),
    onKeyDown: props.onKeyDown,
    tableProps: {
      rowSelection: null,
      pagination,
      onChange: props.onTitleChange,
      setAdd,
      setCopy,
      setDelete,
      AutoTableHeight: "100%",
      setOpterationColumn: "Y",
      selfTableHeight: 82,
      noVlist: true,
    },
  };

  return <StaticEditTable {...visionRecordTableProps} />;
};

// 日志表
const DailyComponent = props => {
  const { dailyData = [], dailyPagination } = props;

  const { setAdd, setCopy, setDelete } = props.handleGetIcon();

  const pagination = {
    total: dailyData.length,
    current: dailyPagination?.current || 1,
    size: "large",
    pageSize: commonConfig.pageSize,
    showQuickJumper: true,
    hideOnSinglePage: true,
  };

  const dailyRecordTableProps = {
    ...commonBusiness.getTableTypes("daily", props),
    onKeyDown: props.onKeyDown,
    tableProps: {
      rowSelection: null,
      pagination,
      onChange: props.onTitleChange,
      setAdd,
      setCopy,
      setDelete,
      AutoTableHeight: "100%",
      setOpterationColumn: "Y",
      selfTableHeight: 82,
      noVlist: true,
    },
  };

  return <StaticEditTable {...dailyRecordTableProps} />;
};


// 工艺参数弹窗
const ModalComponent = props => {
  const modalName = 'sWorkParamsModalVisible'; // commonParamVisible
  const sProcessParams = commonFunc.showMessage(props.app.commonConst, 'workParam') || '工单参数';
  const BtnFirst = commonFunc.showMessage(props.app.commonConst, 'BtnFirst') || '首条';

  const BtnLast = commonFunc.showMessage(props.app.commonConst, 'BtnLast') || '末条';

  const BtnPrior = commonFunc.showMessage(props.app.commonConst, 'BtnPrior') || '上一条';

  const BtnNext = commonFunc.showMessage(props.app.commonConst, 'BtnNext') || '下一条';

  const getTableBtnState = (tableName) => {
    let result = false;
    const { enabled, masterData } = props;
    result = enabled;

    const { sInstruct: sInstructStr } = props[`${tableName}Config`];
    const sInstruct = commonUtils.convertStrToObj(sInstructStr, {});
    const { data = [] } = sInstruct;

    const btnConfig = data.find(item => item && item.name === tableName && item.enabled !== undefined);
    if (btnConfig && result) {
      if (!Array.isArray(props[`${tableName}Data`]) || !Array.isArray([`${tableName}SelectedRowKeys`])) {
        return;
      }
      const { enabled: enabledContent } = btnConfig;
      if (typeof enabledContent === 'boolean') {
        result = enabledContent;
      } else if (enabledContent) {
        const tempData = {
          props: {
            enabled
          },
          masterData,
          [tableName]: props[`${tableName}Data`]?.find(i =>
            i && (props[`${tableName}SelectedRowKeys`].includes(i.sId)
              || props[`${tableName}SelectedRowKeys`].includes(i.sSlaveId)))
            || {},
        };
        let strNew = enabledContent;
        Object.keys(tempData).forEach(key => {
          const reg = new RegExp(`${key}\\.`, "g");
          strNew = strNew.replace(reg, `tempData["${key}"].`);
        });
        try {
          const evalStr = eval("`" + strNew + "`");
          result = !!eval(evalStr);
          console.log('=====表格行按钮状态结果', result, { btnName, enabledContent, tempData, strNew, evalStr });
        } catch (error) {
          console.log('=====表格行按钮状态错误', { error, enabledContent, strNew, tempData });
        }
      }
    }
    return result;
  }
  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={() => { props.onBtnParamPage(props, props.processTableId, 'first') }} >{BtnFirst}</Button>
          <Button type='primary' onClick={() => { props.onBtnParamPage(props, props.processTableId, 'before') }} >{BtnPrior}</Button>
          <Button type='primary' onClick={() => { props.onBtnParamPage(props, props.processTableId, 'next') }} >{BtnNext}</Button>
          <Button type='primary' onClick={() => { props.onBtnParamPage(props, props.processTableId, 'last') }} >{BtnLast}</Button>
        </div>
        {
          [''].map(() => {
            const commonViewDragableProps = {
              ...props,
              // comparedTableId: props.processTableId,
              hideTabsNav: true,
              comparedTableId: props.processTableId,
              // bSimpleMode: true,
              sParamData: [
                {
                  sParamType: 'sWorkOrder',
                  sParamName: '工单参数'
                },
              ],
              tableName: 'process',
            }

            commonViewDragableProps.enabled = getTableBtnState(commonViewDragableProps.tableName);

            return <CommonViewDragable {...commonViewDragableProps} />;
          })
        }
      </div>
    </Modal> : ''

};

export default CommonBase(CommonSales(WorkOrderPackTableTreeNew));
