/* eslint-disable */
import React, { useEffect, useState, useMemo, useRef } from "react";
import moment from "moment";
import { Avatar, Collapse, Radio, Row, Col, Divider, message, Modal } 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 styles from "./index.less";

const { Panel } = Collapse;

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

      const fetchData = async () => {
        let addState = {};
        const tableList = [];

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

        // 工序表配置
        const processConfig = formData.filter(item => item.sTbName.toUpperCase() === "mftproductprocess".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 materialsConfig = formData.filter(item => item.sTbName.toUpperCase() === "mftproductmaterials".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]);
        }

        // 颜色配置
        const colorConfig = formData.filter(item => item.sTbName.toUpperCase() === "mftProductparam".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,
            });
            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];

    if (func) {
      return func(params);
    }

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

  // 新增
  const handleAdd = async (config, copyTo, isWait) => {
    let state = await props.onAdd(config, copyTo, true);
    const { masterData, slaveData } = state;

    const { sModelsId, token } = props;

    const controlData = [];
    let packData = [];
    const materialsData = [];
    let processData = [];
    const colorData = [];

    if (commonUtils.isNotEmptyObject(copyTo)) {
      const [copyToSlaveDetailConfig, copyToControlConfig, copyToMaterialsConfig, copyToProcessConfig, copyToColorConfig, copyToPackConfig] = [
        "slave",
        "control",
        "materials",
        "process",
        "param",
        "pack",
      ].map(tablename => copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.${tablename}`.toLowerCase()));

      const slaveDetailAssignField = copyToSlaveDetailConfig[0]?.sAssignField || "";
      const controlAssignField = copyToControlConfig[0]?.sAssignField || "";
      const materialsAssignField = copyToMaterialsConfig[0]?.sAssignField || "";
      const processAssignField = copyToProcessConfig[0]?.sAssignField || "";
      const colorAssignField = copyToColorConfig[0]?.sAssignField || "";
      const packAssignField = copyToPackConfig[0]?.sAssignField || "";

      const newCopyTo = {};
      newCopyTo.master = copyTo.masterData;
      newCopyTo.slave = slaveData?.[0] || {};

      let returnProcessAssort = [];
      let processAssignAssort = "";
      let dropDownDataProcessName;

      /* 列表未清复制到执行逻辑体 */
      if (commonUtils.isEmptyArr(copyTo.controlData) && commonUtils.isNotEmptyArr(copyTo.slaveData)) {
        const { sParentId, sId } = copyTo.slaveData[0];
        const condition = { sParentId: sParentId || sId };
        const dataUrl = `${commonConfig.server_host}salesorder/getPartsInfo?sModelsId=${sModelsId}`;
        const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
        if (dataReturn.code === 1) {
          const returnData = dataReturn.dataset.rows[0];
          copyTo.controlData = returnData.controlData;
          copyTo.materialsData = returnData.materialsData;
          copyTo.processData = returnData.processData;
          copyTo.colorData = returnData.colorData;
          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 sProcessNameConfig = config.processConfig.gdsconfigformslave.find(item => item.sName === "sProcessName");
            if (sProcessNameConfig) {
              const sqlDropDownData = await props.getSqlDropDownData(sModelsId, "slave", sProcessNameConfig);
              dropDownDataProcessName = sqlDropDownData.dropDownData;
              processAssignAssort = sProcessNameConfig.sAssignField;
            }
          }
        } else {
          props.getServiceError(dataReturn);
        }
      }

      if (commonUtils.isNotEmptyArr(copyTo.controlData)) {
        let dProductQty = 0;
        if (commonUtils.isNotEmptyArr(copyTo.slaveData)) {
          if (slaveData.length === 1 && copyTo.slaveData.length === 1) {
            /* 从表与返回数据从表只有一条时 替换该从表数据  */
            slaveData.forEach((item, iSlaveIndex) => {
              item = {
                ...item,
                ...commonFunc.getAssignFieldValue(slaveDetailAssignField, copyTo.slaveData[0], newCopyTo),
              }; // 取赋值字段
              slaveData[iSlaveIndex] = item;
            });
          } else {
            copyTo.slaveData.forEach(slaveItem => {
              /* 从工艺卡数据集 找到从表相同产品ID,客户ID */
              const iSameIndex = slaveData.findIndex(
                itemCurrent => itemCurrent.sProductId === slaveItem.sProductId && itemCurrent.sCustomerId === slaveItem.sCustomerId
              );
              if (iSameIndex > -1) {
                slaveData[iSameIndex].sOriginalId = slaveItem.sSlaveId || slaveItem.sId; /* 原始sId */
              } 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 = slaveItem.sSlaveId || slaveItem.sId;
                slaveData.push(slaveRow);
              }
            });
          }
        }
        const treeCopyNodes = new Map();
        copyTo.controlData.forEach(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;
          controlRow.dPartsQty = dProductQty;
          controlRow.sPartsName = controlRow.sPartsName || slaveData?.[0]?.sPartsName || "";
          /* 没有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);
          controlData.push(controlRow);

          /* 复制到时增加合版表 */
          if (commonUtils.isNotEmptyArr(copyTo.packData)) {
            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);
              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 */
                  const jsonStr = controlRow.sCombinedMemo;
                  const JsonData = commonUtils.convertStrToObj(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,
                      };
                    }
                  }
                  packData.push(packRow);
                }
              }
            });
          }

          if (commonUtils.isNotEmptyArr(copyTo.processData)) {
            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.slice(0, -1) : "";
                sNewNames = commonUtils.isNotEmptyObject(sNewNames) ? sNewNames.slice(0, -1) : "";
              }
              processRow.sCombinePartsName = sNewIds;
              processRow.sCombinePartsNameNew = sNewNames;
              processData.push(processRow);
              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)) {
            copyTo.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.sType = materialsItem.sType;
              materialsRow.sOriginalId = materialsItem.sId;
              materialsRow.sParentMaterialsId = materialsItem.sParentMaterialsId;
              materialsRow.sInkFatherMaterialsTbId = materialsItem.sInkFatherMaterialsTbId;
              // 材料对应工序的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);
            });
            /* 将 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) {
                      const addState = {};
                      addState.sMaterialsNo1 = materialsData[iIndex].sMaterialsNo; /* 原材料编号 */
                      addState.sMaterialsName1 = materialsData[iIndex].sMaterialsName; /* 原材料名称 */
                      addState.bAlternative = true;
                      addState.sParentMaterialsId = materialsData[iIndex].sId;
                      materialsData[iNexIndex] = {
                        ...materialsData[iNexIndex],
                        ...addState,
                      };
                      materialsData[iIndex] = {
                        ...materialsData[iIndex],
                        bTidaibs: true,
                      };
                    }
                  }
                });
              }

              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(copyTo.materialsData)) {
        copyTo.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;
          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.slice(0, -1) : "";
            sNewNames = commonUtils.isNotEmptyObject(sNewNames) ? sNewNames.slice(0, -1) : "";
          }
          materialsRow.sCombinePartsName = sNewIds;
          materialsRow.sCombinePartsNameNew = sNewNames;
          materialsData.push(materialsRow);
        });
      }

      if (commonUtils.isNotEmptyArr(copyTo.processData)) {
        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(",");
            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.slice(0, -1) : "";
            sNewNames = commonUtils.isNotEmptyObject(sNewNames) ? sNewNames.slice(0, -1) : "";
          }
          processRow.sCombinePartsName = sNewIds;
          processRow.sCombinePartsNameNew = sNewNames;
          processData.push(processRow);

          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 (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 = changeData?.sParentId || "";
            if (sParentId) {
              const iIndex = config.masterConfig.gdsconfigformslave.findIndex(item => item.sName === "sProductClassifyName");
              if (iIndex > -1) {
                // let dProductQty = 0;
                // slaveData.forEach(item => {
                //   dProductQty += getDProductQty(dProductQty, item);
                // });
                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;
                    controlData.push(tableDataRow);
                  }
                }
              }
            }
          }
        }
      } else {
        processData = props.sortData(controlData, processData);
      }
    } else if (commonUtils.isEmpty(masterData.sProductClassifyId)) {
      const iIndex = config.masterConfig.gdsconfigformslave.findIndex(item => item.sName === "sProductClassifyName");
      if (iIndex > -1) {
        const returnValue = {};
        const { sAssignField } = config.masterConfig.gdsconfigformslave[iIndex];
        const sqlDropDownData = await props.getSqlDropDownData(sModelsId, "master", config.masterConfig.gdsconfigformslave[iIndex]);
        const dropDownData = sqlDropDownData.dropDownData;
        const [changeData] = dropDownData.filter(item => item.sType === "huace");
        if (!commonUtils.isEmpty(sAssignField)) {
          /* 赋值数组 */
          const sAssignFieldObj = sAssignField.split(",");
          if (commonUtils.isNotEmptyObject(changeData)) {
            for (const child of sAssignFieldObj) {
              if (child.indexOf(":") > -1) {
                const sFieldName = child.split(":")[0].trim();
                const sValueName = child.split(":")[1].trim();
                returnValue[sFieldName] = changeData[sValueName];
              }
            }
          }
        }
        const addState = await handleMasterChange(
          "master",
          "sProductClassifyName",
          { ...masterData, ...returnValue },
          masterData.sId,
          null,
          { masterData, masterConfig: config.masterConfig },
          true
        );
        state = { ...state, ...addState };
      }
    }
    if (controlData.length === 0 && commonUtils.isEmptyObject(copyTo)) {
      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;
      tableDataRow.sSlaveId = " ";
      tableDataRow.sCombinedMemo = "合版信息";
      tableDataRow.sAllId = tableDataRow.sId;
      if (commonUtils.isEmptyObject(tableDataRow.sPartsName)) {
        tableDataRow.sPartsName = commonUtils.isNotEmptyArr(slaveData) ? slaveData[0].sProductName : "";
      }
      // let dProductQty = 0;
      // slaveData.forEach(item => {
      //   dProductQty += getDProductQty(dProductQty, item);
      // });
      // 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;
        packData.push(packDataRow);
      }

      controlData.push(tableDataRow);
    }
    const treeState = { treeData: [] }; /* 加载树形结构数据 */
    const stateNew = {
      ...state,
      ...treeState,
      slaveData,
      controlData,
      controlSelectedRowKeys: [],
      materialsData,
      materials0Data: materialsData,
      materialsSelectedRowKeys: [],
      processData,
      packData,
      colorData,
      processSelectedRowKeys: [],
      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();
    } else if (name === "BtnDraft") {
      const { masterData } = props;

      const tableList = ["slave", "control", "process", "materials0", "package", "color"];

      tableList.forEach(tablename => {
        const tableConfig = props[`${tablename}Config`];
        if (!tableConfig?.gdsconfigformslave) return;

        const tableData = props[`${tablename}Data`];
        const filterData = tableData.filter(itemData => ["add", "updata"].includes(itemData.handleType));
        tableConfig.gdsconfigformslave.forEach(itemConfig => {
          filterData.forEach(itemData => {
            itemData.NoVerify = "NoVerify";
            const firstDataIndex = itemConfig.sName.substring(0, 1);
            if (commonUtils.isEmpty(itemData[itemConfig.sName])) {
              const defaultValues = {
                s: "",
                d: 0,
                i: 0,
                b: false,
                t: moment(new Date()).format(props.app.dateFormat),
              };

              itemData[itemConfig.sName] = defaultValues[firstDataIndex] || undefined;
            }
          });
        });
      });

      masterData.bIsUnCcg = false;
      masterData.sStatus = "4";
      masterData.handleType = masterData.handleType || "update";

      const data = tableList.filter(tablename => props[`${tablename}Config`]?.gdsconfigformslave).map(tablename => {
        const tableConfig = props[`${tablename}Config`];
        const tableData = props[`${tablename}Data`];
        const tableDelData = props[`${tablename}DelData`];
        const bMaster = tablename === "master";
        const tablenameNew = tablename === "materials0" ? "materials" : tablename;
        return commonBusiness.mergeData(tablenameNew, tableConfig.sTbName, bMaster ? [tableData] : tableData, bMaster ? undefined : tableDelData);
      });
      data.push(commonBusiness.mergeData('master', masterConfig.sTbName, [masterData]));
      props.onSaveData({
        data,
        sClientType: "1",
        loading: false,
        sSysLogSrcId: masterData.sId,
        bIsUnCcg: false,
      });
    } 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 === "BtnWorkFlow") {
      const dataUrl = `${commonConfig.server_host}workOrderFlow/getWorkOrderFlow/`;
      let { token } = props.app;
      let { slaveData, controlData, materials0Data: materialsData, processData, packData } = props;
      const value = {
        slave: slaveData,
        control: controlData,
        materials: materialsData,
        process: processData,
        pack: packData,
        sModelsType: "processCardPackTableTree",
      };
      let dataReturn = (await commonServices.postValueService(token, value, dataUrl)).data;
      if (commonUtils.isNotEmptyObject(dataReturn)) {
        if (dataReturn.code === 1) {
          const flowData = dataReturn.dataset.rows[0];
          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, 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.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) => {
    const bTmpInfoBySql = selectConfig?.sControlName?.toLowerCase().includes("tmpinfobysql");
    // if (name === "productProcessInfo" && !bTmpInfoBySql) {
    //   message.info("productProcessInfo已废弃，请改成TmpInfoBySql！");
    //   return;
    // }
    if (name === "materials") {
      name = "materials0";
    }
    const {
      [`${name}Data`]: tableData,
      [`${name}Config`]: tableConfig,
      masterConfig,
      slaveSelectedRowKeys,
      controlSelectedRowKeys = [],
      sModelsId,
      token,
      slaveConfig,
      controlConfig,
      materialsConfig,
      materials0Config,
      processConfig,
      colorConfig,
      slaveData,
      controlData: controlDataOld = [],
      materialsData: materialsDataOld,
      processData: processDataOld,
      colorData: colorDataOld,
      packData: packDataOld,
      controlDelData: controlDelDataOld,
      materialsDelData: materialsDelDataOld,
      processDelData: processDelDataOld,
      colorDelData: colorDelDataOld,
      materials0Data: materials0DataOld,
      packDelData: packDelDataOld,
    } = props;
    let { masterData } = props;
    const config = {};
    config.masterConfig = masterConfig;
    config.slaveConfig = slaveConfig;
    config.controlConfig = controlConfig;
    config.materials0Config = materials0Config;
    config.processConfig = processConfig;
    config.colorConfig = colorConfig;
    // 只保留自定义
    if (bTmpInfoBySql) {
      /* 复制从部件 根据配置下拉sql获取数据源 通过按钮名称是否包含add来判断数据源新增还是删除 */
      const addState = {};
      let controlData = commonUtils.isEmptyArr(controlDataOld) ? [] : controlDataOld;
      let materialsData = commonUtils.isEmptyArr(materialsDataOld) ? [] : materialsDataOld;
      let materials0Data = commonUtils.isEmptyArr(materials0DataOld) ? [] : materials0DataOld;
      let processData = commonUtils.isEmptyArr(processDataOld) ? [] : processDataOld;
      let packData = commonUtils.isEmptyArr(packDataOld) ? [] : packDataOld;
      let colorData = commonUtils.isEmptyArr(colorDataOld) ? [] : colorDataOld;

      const dataUrl = `${commonConfig.server_host}salesorder/getTmpInfoBySql/?sModelsId=${sModelsId}`;
      const sConfigformId = commonUtils.isEmpty(selectConfig) ? "" : selectConfig.sParentId;
      const sRowData = selectData;
      const sControlName = selectConfig.sControlName; /* 按钮名称 */
      const condition = { sConfigformId, sControlName, sRowData };
      const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
      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}.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(commonUtils.isEmptyArr(controlSelectedRowKeys) && controlDataOld.length > 0){
            controlSelectedRowKeys.push(controlDataOld[0].sId)
          }
          if (commonUtils.isNotEmptyArr(controlSelectedRowKeys)) {
            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;
            }
          }
        }

        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;
            }

            materials0Data = [];
            const materials0DelData = commonUtils.isEmptyArr(materialsDelDataOld) ? [] : materialsDelDataOld;
            const materials0DataFilterData = materialsDataOld?.filter(obj => controlSelectedRowKeys.includes(obj.sControlId));
            if (commonUtils.isNotEmptyArr(materials0DataFilterData)) {
              materials0DataFilterData.forEach(item => {
                item.handleType = "del";
                materials0DelData.push(item);
              });
              addState.materials0DelData = materials0DelData;
            }
          }
        }

        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(copyToPackConfig)) {
          if (!copyToPackConfig[0].sControlName.includes("_add") && !copyToPackConfig[0].sControlName.includes("_edit")) {
            /* 删除 */
            packData = [];
            const packDelData = commonUtils.isEmptyArr(packDelDataOld) ? [] : packDelDataOld;
            const packDataFilterData = packDataOld.filter(obj => controlSelectedRowKeys.includes(obj.sControlId));
            if (commonUtils.isNotEmptyArr(packDataFilterData)) {
              packDataFilterData.forEach(item => {
                item.handleType = "del";
                packDelData.push(item);
              });
              addState.packDelData = packDelData;
            }
          }
        }

        if (commonUtils.isNotEmptyArr(colorAssignField)) {
          if (!colorAssignField[0].sControlName.includes("_add") && !colorAssignField[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;
          }
        }
        const newCopyTo = {};
        newCopyTo.master = copyTo.masterData;
        newCopyTo.slave = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0];
        let iSlaveIndex = -1;
        if (!commonUtils.isEmpty(slaveSelectedRowKeys)) {
          iSlaveIndex = 0;
        } else {
          iSlaveIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys.toString());
        }
        if (iSlaveIndex > -1) {
          slaveData[iSlaveIndex] = {
            ...slaveData[iSlaveIndex],
            ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, selectData[0], newCopyTo),
          }; // 取赋值字段
        }
        if (commonUtils.isNotEmptyArr(selectData)) {
          masterData = {
            ...masterData,
            ...commonFunc.getAssignFieldValue(masterDetailAssignField, 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 = true;
        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];
          }
        }
        console.log("returnData", returnData);
        if (commonUtils.isNotEmptyArr(returnData.controlData)) {
          let dProductQty = 0;
          /* 主表配置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.isNotEmptyObject(copyToSlaveDetailConfig)) {
            slaveData.forEach((item, iSlaveIndex) => {
              if (commonUtils.isNotEmptyArr(returnData.slaveData)) {
                item = {
                  ...item,
                  ...commonFunc.getAssignFieldValue(slaveDetailAssignField, returnData.slaveData[0], newCopyTo),
                }; // 取赋值字段
              }
              slaveData[iSlaveIndex] = 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 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 (true) {
                let packRow = commonFunc.getDefaultData(config.packConfig, newCopyTo); // 取默认值
                /* sSlaveId赋值 */
                if (iSlaveIndex > -1) {
                  const slaveDataRow = slaveData[iSlaveIndex];
                  const packRowAdd = props.handlePackDataAdd(slaveDataRow, 0, controlRow.sId, 'add');
                  if (commonUtils.isNotEmptyObject(packRowAdd)) {
                    packRow = { ...packRow, ...packRowAdd };
                    packRow.dCombineQty = commonUtils.isNull(controlRow.dSinglePQty, 1); /* 默认是控制表的排版数 */
                    packRow.dProductQty = commonUtils.isNull(slaveDataRow.dProductQty, 0);
                    packRow.dFactProductQty = commonUtils.isNull(slaveDataRow.dProductQty, 0);
                    if(commonUtils.isNotEmptyObject(packRow) && commonUtils.isNotEmptyObject(packRow.sProductId)){ /* 从表要选择产品 */
                      const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty,sCombinePartsName  }= packRow;
                      const tableCombineSelectedData =[];
                      const jsonObj = {};
                      jsonObj.sId = sId;
                      jsonObj.sProductNo = sProductNo; /* 产品编号 */
                      jsonObj.dCombineQty = dCombineQty; /* 排版数 */
                      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对象转换为字符串存放到合版信息中 */
                      controlRow.sCombinedMemo =commonUtils.isNotEmptyObject(sCombinedMemo)? sCombinedMemo: '合版信息';
                    }
                    packData.push(packRow);
                  }
                }
              }

              /* 复制到时增加合版表 */
              if (false && 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 */
                  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 => {
                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;
                // 材料对应工序的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);
                materials0Data.push(materialsRow);
              });
            }
          });
        }
        if (commonUtils.isNotEmptyArr(returnData.materialsData)) {
          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)) {
          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;
            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)) {
          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.materials0Data = materials0Data;
        addState.packData = packData;
        props.onSaveState({
          [`${name}ChooseVisible`]: false,
          processData,
          materialsData,
          controlData,
          ...treeState,
          colorData,
          masterData,
          controlSelectedRowKeys: [],
          materialsSelectedRowKeys: [],
          processSelectedRowKeys: [],
          ...addState,
        });
      } else {
        props.getServiceError(dataReturn.msg);
      }
    } else if (name === 'productProcessInfo') { /* 复制从产品 */
      if (commonUtils.isNotEmptyArr(selectData)) {
        const controlData = [];
        const materialsData = [];
        const processData = [];
        const colorData = [];
        const addState = {};
        const controlDelData = commonUtils.isEmptyArr(controlDelDataOld) ? [] : controlDelDataOld;
        const materialsDelData = commonUtils.isEmptyArr(materialsDelDataOld) ? [] : materialsDelDataOld;
        const processDelData = commonUtils.isEmptyArr(processDelDataOld) ? [] : processDelDataOld;
        const colorDelData = commonUtils.isEmptyArr(colorDelDataOld) ? [] : colorDelDataOld;
        controlDataOld.forEach((item) => {
          item.handleType = 'del';
          controlDelData.push(item);
        });
        addState.controlDelData = controlDelData;
        materialsDataOld.forEach((item) => {
          item.handleType = 'del';
          materialsDelData.push(item);
        });
        addState.materialsDelData = materialsDelData;
        processDataOld.forEach((item) => {
          item.handleType = 'del';
          processDelData.push(item);
        });
        addState.processDelData = processDelData;
        if (commonUtils.isNotEmptyArr(colorDataOld) && colorDataOld.length > 0) {
          colorDataOld.forEach((item) => {
            item.handleType = 'del';
            colorDelData.push(item);
          });
        }
        addState.colorDelData = colorDelData;
        addState.processDelData = processDelData;
        const config = {};
        config.masterConfig = masterConfig;
        config.slaveConfig = slaveConfig;
        config.controlConfig = controlConfig;
        config.materialsConfig = materialsConfig;
        config.processConfig = processConfig;
        config.colorConfig = colorConfig;

        let iSlaveIndex = -1;
        if (!commonUtils.isEmpty(slaveSelectedRowKeys)) {
          iSlaveIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys.toString());
        }

        const condition = { sCardId: selectData[0].sId, sRowData: selectData };
        const dataUrl = `${commonConfig.server_host}salesorder/getProcessCardDataByCustomIdProductId/?sModelsId=${sModelsId}`;
        const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
        console.log('ddddataReturnd', dataReturn);
        if (dataReturn.code === 1) {
          const copyTo = { config: masterConfig.gdsconfigformslave, name: selectConfig.sControlName };
          const returnData = dataReturn.dataset.rows[0];
          const copyToMasterDetailConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}`.toLowerCase());
          const copyToSlaveDetailConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.slave`.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 copyToPackConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${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}.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 : '';
          const newCopyTo = {};
          newCopyTo.master = copyTo.masterData;
          newCopyTo.slave = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0];

          if (iSlaveIndex > -1) {
            slaveData[iSlaveIndex] = { ...slaveData[iSlaveIndex], ...commonFunc.getAssignFieldValue(selectConfig.sAssignField, selectData[0], newCopyTo) }; // 取赋值字段
          }
          const bProcessAssort = true;
          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 this.props.getSqlDropDownData(sModelsId, 'slave', config.processConfig.gdsconfigformslave[iIndex]);
                dropDownDataProcessName = sqlDropDownData.dropDownData;
                processAssignAssort = config.processConfig.gdsconfigformslave[iIndex].sAssignField;
              }
            }
          }

          if (commonUtils.isNotEmptyArr(returnData.controlData)) {
            let dProductQty = 0;
            /* 主表配置bProductQtyAdd 则代表产品数量不叠加备货数 赠送数 */
            let bProductQtySelf = false;
            if (commonUtils.isNotEmptyObject(this.props.masterConfig) && commonUtils.isNotEmptyArr(this.props.masterConfig.gdsconfigformslave)) {
              const iIndex = this.props.masterConfig.gdsconfigformslave.findIndex(item => item.sControlName === 'bProductQtySelf');
              if (iIndex > -1) {
                bProductQtySelf = true;
              }
            }
            if (commonUtils.isNotEmptyArr(returnData.slaveData)) {
              masterData = { ...masterData, ...commonFunc.getAssignFieldValue(masterDetailAssignField, returnData.slaveData[0], newCopyTo) }; // 取赋值字段
            }

            slaveData.forEach((item, iSlaveIndex) => {
              if (commonUtils.isNotEmptyArr(returnData.slaveData)) {
                item = { ...item, ...commonFunc.getAssignFieldValue(slaveDetailAssignField, returnData.slaveData[0], newCopyTo) }; // 取赋值字段
                slaveData[iSlaveIndex].sOriginalId = commonUtils.isNotEmptyObject(item.sSlaveId) ? item.sSlaveId : item.sId;  /* 原始sId */
              }
              slaveData[iSlaveIndex] = 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 treeCopyNodes = new Map();
            returnData.controlData.forEach((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;
              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 (true) {
                let packRow = commonFunc.getDefaultData(config.packConfig, newCopyTo); // 取默认值
                /* sSlaveId赋值 */
                if (iSlaveIndex > -1) {
                  const slaveDataRow = slaveData[iSlaveIndex];
                  const packRowAdd = props.handlePackDataAdd(slaveDataRow, 0, controlRow.sId, 'add');
                  if (commonUtils.isNotEmptyObject(packRowAdd)) {
                    packRow = { ...packRow, ...packRowAdd };
                    packRow.dCombineQty = commonUtils.isNull(controlRow.dSinglePQty, 1); /* 默认是控制表的排版数 */
                    packRow.dProductQty = commonUtils.isNull(slaveDataRow.dProductQty, 0);
                    packRow.dFactProductQty = commonUtils.isNull(slaveDataRow.dProductQty, 0);
                    if(commonUtils.isNotEmptyObject(packRow) && commonUtils.isNotEmptyObject(packRow.sProductId)){ /* 从表要选择产品 */
                      const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty,sCombinePartsName  }= packRow;
                      const tableCombineSelectedData =[];
                      const jsonObj = {};
                      jsonObj.sId = sId;
                      jsonObj.sProductNo = sProductNo; /* 产品编号 */
                      jsonObj.dCombineQty = dCombineQty; /* 排版数 */
                      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对象转换为字符串存放到合版信息中 */
                      controlRow.sCombinedMemo =commonUtils.isNotEmptyObject(sCombinedMemo)? sCombinedMemo: '合版信息';
                    }
                    packData.push(packRow);
                  }
                }
              }
              if (false && 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赋值 */
                  const iSlaveIndex = slaveData.findIndex(item => item.sOriginalId === packItem.sSlaveId);
                  if (iSlaveIndex > -1) {
                    const slaveDataRow = slaveData[iSlaveIndex];
                    const packRowAdd = this.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 > -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;
                  // 材料对应工序的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);
                });
              }
            });
          }
          if (commonUtils.isNotEmptyArr(returnData.materialsData)) {
            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)) {
            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;
              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)) {
            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 = this.handleGetControlTreeData(controlData, true); /* 加载树形结构数据 */
          this.props.onSaveState({
            [`${name}ChooseVisible`]: false,
            processData,
            materialsData,
            controlData,
            ...treeState,
            colorData,
            masterData,
            packData,
            controlSelectedRowKeys: [],
            materialsSelectedRowKeys: [],
            processSelectedRowKeys: [],
            ...addState,
          });
        } else {
          this.props.getServiceError(dataReturn.msg);
        }
      }
    } else {
      const addState = {};
      const { controlData } = props;
      const iControlIndex = commonUtils.isNotEmptyArr(controlSelectedRowKeys)
        ? controlData.findIndex(item => item.sId === controlSelectedRowKeys[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") {
            /* 设置工单参数下拉 */
            tableDataRow.sParams = item.sParams;
            ["sProcess", "sReport", "sWorkOrder", "sNorm", "sTest"].forEach(key => {
              // 将各种参数的默认值保存到sParams中
              const sKeyParam = commonUtils.convertStrToObj(tableDataRow[`${key}Param`] || item[`${key}Param`], {});
              if (commonUtils.isNotEmptyObject(sKeyParam)) {
                const sKeyParamDefaultValues = Object.keys(sKeyParam)
                  .filter(item => item.startsWith("sParamDefault") && commonUtils.isNotEmptyObject(sKeyParam[item]))
                  .reduce((result, item) => {
                    const sParamsName = item.replace("Default", "");
                    result[sParamsName] = sKeyParam[item];
                    return result;
                  }, {});

                const sParams = commonUtils.convertStrToObj(tableDataRow.sParams, []);
                const sKeyJsonIndex = sParams.findIndex(item => item.sParamType === key);
                if (sKeyJsonIndex === -1) {
                  sParams.push({
                    sParamType: key,
                    data: sKeyParamDefaultValues,
                  });
                } else {
                  const { data: sWorkOrderData = {} } = sParams[sKeyJsonIndex];
                  sParams[sKeyJsonIndex].data = {
                    ...sWorkOrderData,
                    ...sKeyParamDefaultValues,
                  };
                }
                tableDataRow.sParams = JSON.stringify(sParams);
              }
            });

            // 配套工序
            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 =
                    dropDownDataProcessName[iIndex].sType === "3"
                      ? tableData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId)
                      : tableData.findIndex(
                          item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === controlData[iControlIndex].sId
                        );
                  if (iIndex > -1 && 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);
                        }
                      });
                    }
                  }
                }
              });
            }
            addState.processSelectedRowKeys = [tableDataRow.sId];
          }
          if (iControlIndex > -1 && tableDataRow.sType !== "3") {
            tableDataRow.sControlId = controlData[iControlIndex].sId;
            tableDataRow.sPartsName = controlData[iControlIndex].sPartsName;
            tableData.push(tableDataRow);
          } else if (tableDataRow.sType === "3") {
            tableData.push(tableDataRow);
          }
        }
      }
      const tableDataNew = props.sortData(controlData, tableData);
      props.onSaveState({
        [`${name}Data`]: tableDataNew,
        [`${name}ChooseVisible`]: false,
        materialsConfig,
        materialsSelectedRowKeys: [],
        ...addState,
      });
    }
  };
  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 = async bParts => {
    form.validateFields(err => {
      if (err) {
        // 验证失败
        for (const key of Object.keys(err)) {
          message.warning(err[key].errors[0].message);
        }
        props.onSaveState({
          loading: false,
        });
        return;
      }

      // 验证成功
      const {
        masterData,
        slaveConfig,
        slaveData,
        controlConfig,
        controlData,
        materials0Config,
        materials0Data: materialsData,
        processConfig,
        processData,
        colorConfig,
        colorData,
        dailyConfig,
        dailyData,
        addStateMap,
      } = props;

      if (commonUtils.isEmptyArr(slaveData)) {
        message.warning(`从表${commonFunc.showMessage(props.app.commonConst, "isNotNull")}`);
        props.onSaveState({
          loading: false,
        });
        return;
      }

      if (!bParts) {
        if (
          !commonBusiness.validateTable(slaveConfig, slaveData, props) ||
          !commonBusiness.validateTable(controlConfig, controlData, props) ||
          !commonBusiness.validateTable(materials0Config, materialsData, props) ||
          !commonBusiness.validateTable(processConfig, processData, props) ||
          !commonBusiness.validateTable(colorConfig, colorData, props) ||
          !commonBusiness.validateTable(dailyConfig, dailyData, props)
        ) {
          props.onSaveState({
            loading: false,
          });
          return;
        }
      }
      const data = [];
      if (masterData.sStatus === "4" && !bParts) {
        /* 点保存后 从草稿箱状态变成未审核状态 */
        masterData.sStatus = "0";
        masterData.handleType = commonUtils.isEmpty(masterData.handleType) ? "update" : masterData.handleType;
      }
      if (!bParts) {
        masterData.bIsUnCcg = true;
      }

      const tableList = ["master", "slave", "control", "process", "pack", "color", "daily"];

      tableList.forEach(tablename => {
        const tableConfig = props[`${tablename}Config`];
        const tableData = props[`${tablename}Data`];
        const tableDelData = props[`${tablename}DelData`];

        if (!tableConfig) return;

        data.push(commonBusiness.mergeData(tablename, tableConfig.sTbName, tablename === "master" ? [tableData] : tableData, tableDelData));
      });

      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 { slaveData, [`${name}Data`]: tableData } = props;
    const { [`${name}SelectedRowKeys`]: tableSelectedRowKeys, app } = 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 || tableData[iIndex].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, [`${name}Data`]: tableData, masterConfig, controlConfig, controlData: controlDataOld, masterData, 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 = {};
    /* 主表配置bProductQtyAdd 则代表产品数量不叠加备货数 赠送数 */
    const bProductQtySelf = masterConfig?.gdsconfigformslave.some(item => item.sControlName === "bProductQtySelf");
    if (["dProductQty", "dGiveQty", "dStockupQty"].includes(sFieldName)) {
      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 controlData = [];
      controlDataOld.forEach(item => {
        const itemNew = { ...item };
        itemNew.dPartsQty = dPartsQty;
        controlData.push(itemNew);
      });
      addState.controlData = controlData;
    }
    if (["sCustomerId", "sCustomerNo", "sCustomerName"].includes(sFieldName)) {
      tableDataRow.sProductId = "";
      tableDataRow.sProductNo = "";
      tableDataRow.sProductName = "";
      tableData[iIndex] = tableDataRow;
    } else if (["sProductId", "sProductNo", "sProductName"].includes(sFieldName)) {
      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对象转换为字符串存放到合版信息中 */
          // const controlDataNew =commonUtils.isNotEmptyArr(addState.controlData)? addState.controlData: controlDataOld;
          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 iPIndex = packData.findIndex(child => child.sId === itemPack.sId);

            packData[iPIndex] = { ...packData[iPIndex], ...packDataRow };
            if (iPIndex > -1 && commonUtils.isNotEmptyObject(packData[iPIndex])) {
              const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty, sCombinePartsName } = packData[iPIndex];
              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(controlItem => {
                  const sCombinedMemoArr = JSON.parse(controlItem.sCombinedMemo);
                  const sCombinedMemoFilterArr = sCombinedMemoArr.filter(item => item.dCombineQty > 0 && item.sProductNo === itemPack.sProductNo);
                  return commonUtils.isNotEmptyArr(sCombinedMemoFilterArr);
                });
                if (iControlIndex > -1) {
                  controlDataNew[iControlIndex].sCombinedMemo = sCombinedMemo;
                  controlDataNew[iControlIndex].sPartsName = tableDataRow.sProductName;
                }
              }
            }
          });
          addState.controlData = controlDataNew;
        }
      }
      addState.packData = packData;
    }

    props.onSaveState({ [`${name}Data`]: tableData, ...addState });
  };
  return returnProps;
};

// 控制表相关事件
const controlProps = props => {
  const returnProps = {};
  returnProps.onDataRowAdd = ({ name, bchild }) => {
    const { slaveData, controlData, controlSelectedRowKeys, slaveSelectedRowKeys, [`${name}Data`]: tableData } = props;
    let { packData } = props;

    const sTreeKey = "sNodeId";

    /* 增加子部件 */
    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[sTreeKey] === pId);
        if (sControlParentId > -1) {
          const sAllId = controlData[sControlParentId].sAllId;
          // if (commonUtils.isEmptyObject(sAllId)) {
          //   message.warn("部件数据生成错误！[sAllId为空]");
          //   return;
          // }
          tableDataRow.sAllId = `${controlData[sControlParentId].sAllId},${tableDataRow[sTreeKey]}`;
        } else {
          tableDataRow.sAllId = tableDataRow[sTreeKey];
        }
      }
    }
    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 iIndex = packData.findIndex(item => item.sControlId === tableDataRow.sId);
    if (iIndex === -1) {
      if (commonUtils.isEmptyObject(slaveSelectedRow.sProductId)) {
        message.error("请先选择产品！");
        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;
    if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) {
      /* 删除该节点及所有子节点 */
      const tableRow = controlData.find(item => item.sId === tableSelectedRowKeys[0]);
      let controlChildData = [];
      if(commonUtils.isNotEmptyObject(tableRow)) {
        // 递归查找所有子节点
        const findChildren = (parentId, allNodes) => {
          const children = allNodes.filter(node => node.sControlParentId === parentId);
          let result = [...children];
          children.forEach(child => {
            result = result.concat(findChildren(child.sNodeId, allNodes));
          });
          return result;
        };

        controlChildData = findChildren(tableRow.sNodeId, controlData);
      }
      if (commonUtils.isNotEmptyArr(controlData)) {
        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);
      props.onSaveState({
        treeData: [],
        ...materialsReturnData,
        ...materials0ReturnData,
        ...processReturnData,
        ...packReturnData,
        ...controlReturnData,
      });
      return true;
    } else {
      message.warn(commonFunc.showMessage(app.commonConst, "selectedRowKeysNo")); /* 请选择数据 */
      return false;
    }
  };
  returnProps.onDataChange = async ({ name, sFieldName, changeValue, sId, dropDownData }) => {
    const {
      [`${name}Data`]: tableData,
      materialsData: materialsDataOld,
      materials0Data: materials0DataOld,
      processData: processDataOld,
      sModelsId,
      sModelsType,
      slaveData,
      packData,
    } = props;
    let { masterData } = props;
    let tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (tableDataRow === undefined) return;
    if (
      sFieldName === "dSinglePQty" ||
      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);

          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;
              tableDataRow.iCombineNum = tableDataRow.dSinglePQty;
              if (iIndex > -1) {
                if(commonUtils.isEmptyObject(packData[iIndex].sProductNo)) {
                  const slaveRow = slaveData.find(row => row.sId === packData[iIndex].sSlaveId);

                  if(commonUtils.isNotEmptyObject(slaveRow)) {
                    packData[iIndex].sProductNo =  slaveRow.sProductNo;
                    packData[iIndex].sProductName =  slaveRow.sProductName;
                  }
                }
                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);
    }
    /* 膜内工艺卡算法逻辑  */
    if (sModelsType === "manufacture/workOrder3" && sModelsId === "101251240115016046551448370") {
      /* 排版数dSinglePQty=列数iCol*iRow个数 */
      const iCol = commonUtils.isNull(tableDataRow.iCol, 0);
      const iRow = commonUtils.isNull(tableDataRow.iRow, 0);
      const dMachineWidth = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMachineWidth, 0));
      const dMachineLength = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMachineLength, 0));
      const dCutEdge = commonUtils.isNull(tableDataRow.dCutEdge, 0);
      const dColGap = commonUtils.isNull(tableDataRow.dColGap, 0);
      const dRowGap = commonUtils.isNull(tableDataRow.dRowGap, 0);
      const dScraperGap = commonUtils.isNull(tableDataRow.dScraperGap, 0);
      const dMaterialsLength = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMaterialsLength, 0));
      const dMaterialsWidth = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMaterialsWidth, 0));
      const dSinglePQty = commonUtils.isNull(tableDataRow.dSinglePQty, 0);
      if (sFieldName === "iCol" || sFieldName === "iRow") {
        tableDataRow.dSinglePQty = iCol * iRow;
      }
      /* 膜宽dMaterialsWidth =图文尺寸dMachineWidth*列数iCol+图文到膜边尺寸 dCutEdge*2+图文到图文的尺寸dColGap*（列数iCol-1） */
      if (sFieldName === "dMachineWidth" || sFieldName === "iCol" || sFieldName === "dCutEdge" || sFieldName === "dColGap") {
        tableDataRow.dMaterialsWidth = dMachineWidth * iCol + dCutEdge * 2 + dColGap * (iCol - 1);
      }
      /* 版周长 dMaterialsLength=（版周长图文尺寸dMachineLength+图文到图文尺寸dRowGap）*版周长个数iRow+dScraperGap刮刀距离 */
      if (sFieldName === "dMachineLength" || sFieldName === "dRowGap" || sFieldName === "iRow" || sFieldName === "dScraperGap") {
        tableDataRow.dMaterialsLength = (dMachineLength + dRowGap) * iRow + dScraperGap;
      }
      if (
        sFieldName === "dMachineLength" ||
        sFieldName === "dRowGap" ||
        sFieldName === "iRow" ||
        sFieldName === "dScraperGap" ||
        sFieldName === "dMaterialsLength"
      ) {
        let dPlatediameter = dMaterialsLength / Math.PI;
        dPlatediameter = commonUtils.convertFixNum(dPlatediameter, 2);
        const addState = {};
        addState.dPlatediameter = dPlatediameter;
        addState.handleType = commonUtils.isEmpty(masterData.handleType) ? "update" : masterData.handleType;
        masterData = { ...masterData, ...addState };
      }
      /* 1款拼版 从表产品折算率=版周长*膜宽/1000000 */
      if (commonUtils.isNotEmptyArr(slaveData)) {
        if (slaveData.length === 1) {
          /* 只有一条从表数据  */
          const addState = {};
          addState.dConversionRate = (dMaterialsLength * dMaterialsWidth) / 1000000;
          addState.dCombineCoefficient = dSinglePQty;
          addState.handleType = commonUtils.isEmpty(slaveData[0].handleType) ? "update" : slaveData[0].handleType;
          slaveData[0] = { ...slaveData[0], ...addState };
        } else if (slaveData.length > 1) {
          /* 多款产品合拼的 折算率  */
          let sumTotal = 0;
          slaveData.forEach(itemNew => {
            const singleSum = itemNew.dProductLength * itemNew.dProductWidth * itemNew.dCombineCoefficient;
            sumTotal += singleSum;
          });
          slaveData.forEach((item, index) => {
            const addState = {};
            /* 多产品折算率 */
            const dConversionRate =
              (dMaterialsLength * dMaterialsWidth * (item.dProductLength * item.dProductWidth * item.dCombineCoefficient)) /
              sumTotal /
              item.dCombineCoefficient /
              1000000;
            addState.dConversionRate = commonUtils.convertFixNum(dConversionRate, 6);
            addState.handleType = commonUtils.isEmpty(item.handleType) ? "update" : item.handleType;
            slaveData[index] = { ...item, ...addState };
          });
        }
      }
    }
    const materialsData = [];
    const materials0Data = [];
    const processData = [];
    materialsDataOld?.forEach(item => {
      const itemNew = { ...item };
      if (itemNew.sControlId === sId) {
        itemNew.sPartsName = tableDataRow.sPartsName;
      }
      materialsData.push(itemNew);
    });
    materials0DataOld?.forEach(item => {
      const itemNew = { ...item };
      if (itemNew.sControlId === sId) {
        itemNew.sPartsName = tableDataRow.sPartsName;
      }
      materials0Data.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 materials0DataNew = props.sortData(tableData, materials0Data);
    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,
      materials0Data: materials0DataNew,
      processData: processDataNew,
      slaveData,
      masterData,
      packData,
    });
  };
  returnProps.onTableSelectRowChange = async ({ name, selectedRowKeys }) => {
    const addState = await props.onTableSelectRowChange(name, selectedRowKeys, true);
    props.onSaveState({ addState, processSelectedRowKeys: []});
  }
  returnProps.onViewChoose = ({ sName, record }) => {
    const { sId } = record; /* 控制表主键 */
    const { enabled, slaveData } = props;
    let { packData } = props;
    if (sName === "sCombinedMemo") {
      const packSelectedRowKeys = [];

      /* 合并从表相同客户、产品数据 */
      const slaveDataMerge = [];
      slaveData.forEach(item => {
        const iIndex = slaveDataMerge.findIndex(child => child.sCustomerId === item.sCustomerId && child.sProductId === item.sProductId);
        if (iIndex === -1) {
          const itemNew = JSON.parse(JSON.stringify(item));
          slaveDataMerge.push(itemNew);
        } else if (iIndex > -1) {
          const dProductQtyNew =
            commonUtils.isNull(slaveDataMerge[iIndex].dProductQty, 0) + commonUtils.isNull(item.dProductQty, 0); /* 生产数量叠加 */
          const dGiveQtyNew = commonUtils.isNull(slaveDataMerge[iIndex].dGiveQty, 0) + commonUtils.isNull(item.dGiveQty, 0); /* 赠送数量叠加 */
          const dStockupQtyNew =
            commonUtils.isNull(slaveDataMerge[iIndex].dStockupQty, 0) + commonUtils.isNull(item.dStockupQty, 0); /* 备货数量叠加 */
          slaveDataMerge[iIndex].dProductQty = dProductQtyNew;
          slaveDataMerge[iIndex].dGiveQty = dGiveQtyNew;
          slaveDataMerge[iIndex].dStockupQty = dStockupQtyNew;
        }
      });

      /* 合并合版表相同客户、产品数据 */
      const packDataMerge = [];
      if (commonUtils.isNotEmptyArr(packData)) {
        packData.forEach(item => {
          const iIndex = packDataMerge.findIndex(
            child =>
              commonUtils.isNotEmptyObject(item.sCombinePartsName) &&
              child.sCombinePartsName === item.sCombinePartsName &&
              commonUtils.isNotEmptyObject(item.sProductId) &&
              child.sProductId === item.sProductId
          );
          if (iIndex === -1) {
            const itemNew = JSON.parse(JSON.stringify(item));
            packDataMerge.push(itemNew);
          } else if (iIndex > -1) {
            const dProductQtyNew =
              commonUtils.isNull(packDataMerge[iIndex].dProductQty, 0) + commonUtils.isNull(item.dProductQty, 0); /* 生产数量叠加 */
            const dGiveQtyNew = commonUtils.isNull(packDataMerge[iIndex].dGiveQty, 0) + commonUtils.isNull(item.dGiveQty, 0); /* 赠送数量叠加 */
            const dStockupQtyNew =
              commonUtils.isNull(packDataMerge[iIndex].dStockupQty, 0) + commonUtils.isNull(item.dStockupQty, 0); /* 备货数量叠加 */
            packDataMerge[iIndex].dProductQty = dProductQtyNew;
            packDataMerge[iIndex].dGiveQty = dGiveQtyNew;
            packDataMerge[iIndex].dStockupQty = dStockupQtyNew;
          }
        });
      }
      if (commonUtils.isNotEmptyArr(packDataMerge)) {
        packData = packDataMerge;
      }

      /* 填充合版信息数值 如果packData为空，则填充从表所有数据 */
      if (commonUtils.isNotEmptyArr(slaveDataMerge)) {
        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) {
                    packSelectedRowKeys.push(itemPack.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 if ( sName === 'sPositiveColor' || sName === 'sOppositeColor') {
      props.onViewChoose('control', sName, record);
    } else {
      props.onViewChoose(name, sName, record);
    }
  };
  return returnProps;
};

// 工序表相关事件
const processProps = props => {
  const returnProps = {};
  returnProps.onDataRowAdd = ({ name, bFinished, bModalAdd }) => {
    if (bModalAdd) {
      const { masterConfig } = props;
      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]);
        }
      }
    }

    const { 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 = async ({ name, tableSelectedRowKeys }) => {
    const { sModelsId, [`${name}Data`]: tableData, materialsConfig, token } = props;
    let { materialsDelData, materials0Data: materialsData } = props;
    if (commonUtils.isEmptyArr(materialsDelData)) {
      materialsDelData = [];
    }
    if (commonUtils.isEmptyArr(materialsData)) {
      materialsData = [];
    }
    const iIndex = tableData.findIndex(item => item.sId === tableSelectedRowKeys.toString());

    const dataUrl = `${commonConfig.server_host}salesorder/getProcessAssort?sModelsId=${sModelsId}`;
    const dataProcessAssort = (await commonServices.postValueService(token, {}, dataUrl)).data;
    const tableDelData = [];
    let returnProcessAssort = [];
    if (dataProcessAssort.code === 1) {
      returnProcessAssort = dataProcessAssort.dataset.rows[0].processassort;
    }

    let sProcessId = "";
    let processReturnData = [];
    if (iIndex > -1) {
      sProcessId = tableData[iIndex].sProcessId;
      const sControlId = tableData[iIndex].sControlId;
      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);
        }
      });
      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 (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,
      materialsData,
      materials0Data,
      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 sControlId = "";
    if (iIndex > -1) {
      tableDataRowOld = tableData[iIndex];
      tableData[iIndex] = tableDataRow;
      sControlId = tableData[iIndex].sControlId;
    }
    const addState = {};
    if (sFieldName === "sProcessId" || sFieldName.includes("sProcessName")) {
      const bProcessAssort = true;
      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;
        materials0Data.forEach(materialsItem => {
          if (materialsItem.sControlId === tableData[iIndex].sControlId && materialsItem.sProcessTbId === tableData[iIndex].sId) {
            materialsItem.sProcessId = tableData[iIndex].sProcessId;
            materialsItem.sProcessName = tableData[iIndex].sProcessName;
            materialsItem.sProcessNo = tableData[iIndex].sProcessNo;
            materialsItem.sMaterialsProcessNameOrder = tableData[iIndex].iRowNum + "-" + tableData[iIndex].sProcessName;
            materialsItem.handleType = commonUtils.isEmpty(materialsItem.handleType) ? "update" : materialsItem.handleType;
          }
        });
        addState.materials0Data = materials0Data;
      }
    }
    props.onSaveState({
      [`${name}Data`]: tableData,
      materialsSelectedRowKeys: [],
      ...addState,
    });
  };
  returnProps.onViewChoose = ({ name, sName, record }) => {
    const { sId } = record; /* 控制表主键 */
    const { slaveData } = props;
    let { packData } = props;
    if (name === "process" && sName === "sCombinePartsNameNew") {
      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((itemPack, 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 (name === "process" && sName === "sColorSerialMemo") {
      props.onViewChoose(name, sName, record);
    } else if (name === "process" && (sName === "sParams" || sName === "sQuoParams")) {
      const { processConfig } = props;
      const bSWorkOrderParams = processConfig.gdsconfigformslave.some(item => item.sName === sName && item.sControlName === "sWorkOrder");
      if (bSWorkOrderParams) {
        props.onSaveState({
          sWorkParamsModalVisible: true,
        });
      } else {
        props.onViewClick(name, sName, record);
      }
    }
  };
  return returnProps;
};

// 材料表相关事件
const materialsProps = props => {
  const returnProps = {};
  returnProps.onDataRowAdd = params => {
    const { bModalAdd, bFinished } = params;
    if (bModalAdd) {
      const { masterConfig } = props;
      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]);
        }
      }
    } else {
      processProps(props).onDataRowAdd(params);
    }
  };
  returnProps.onDataRowDel = ({ name, tableSelectedRowKeys }) => {
    if (name === "materials0") {
      /* 删除全部材料时 对应删除替代料 */
      const { [`${name}SelectedRowKeys`]: tableSelectedRowKeys, materials0Data } = props;
      if (commonUtils.isEmptyArr(tableSelectedRowKeys)) {
        message.error("请选择数据！");
        return;
      }
      if (commonUtils.isNotEmptyArr(materials0Data)) {
        const materials0ChildData = materials0Data.filter(item => tableSelectedRowKeys.includes(item.sParentMaterialsId));
        if (commonUtils.isNotEmptyArr(materials0ChildData)) {
          materials0ChildData.forEach(item => {
            tableSelectedRowKeys.push(item.sId);
          });
        }

        /* 删除子墨 */
        const materials0InkData = materials0Data.filter(item => tableSelectedRowKeys.includes(item.sInkFatherMaterialsTbId));
        if (commonUtils.isNotEmptyArr(materials0InkData)) {
          materials0InkData.forEach(item => {
            tableSelectedRowKeys.push(item.sId);
          });
        }

        const materials0ReturnData = props.otherTableDel("materials0", tableSelectedRowKeys, "sId"); /* 全部材料删除 */
        const materials0ChildReturnData = props.otherTableDel("materials0Child", tableSelectedRowKeys, "sId"); /* 替代料删除 */
        props.onSaveState({
          ...materials0ReturnData,
          ...materials0ChildReturnData,
        });
      }
    } else if (name === "materials1") {
      /* 删除油墨时 同时删除油墨子集 */
      /* 从全部材料里 找到对应数据 进行更改 */
      const { [`${name}SelectedRowKeys`]: tableSelectedRowKeys, materials0Data } = props;
      if (commonUtils.isEmptyArr(tableSelectedRowKeys)) {
        message.error("请选择数据！");
        return;
      }
      if (commonUtils.isNotEmptyArr(materials0Data)) {
        const iIndex = materials0Data.findIndex(item => tableSelectedRowKeys.includes(item.sId));
        let materials1Row = {};
        if (iIndex > -1) {
          materials1Row = materials0Data[iIndex];
        }

        const materials0ChildData = materials0Data.filter(
          item =>
            commonUtils.isNotEmptyObject(item.sInkBOMId) &&
            item.sInkBOMId === materials1Row.sInkBOMId &&
            commonUtils.isNotEmptyObject(item.sInkBOMsSlaveId) &&
            item.sInkBOMsSlaveId === materials1Row.sInkBOMsSlaveId &&
            commonUtils.isEmptyObject(item.sInkBOMsMaterialsId)
        );

        if (commonUtils.isNotEmptyArr(materials0ChildData)) {
          materials0ChildData.forEach((item, index) => {
            tableSelectedRowKeys.push(item.sId);
          });
        }
        const materials0ReturnData = props.otherTableDel("materials0", tableSelectedRowKeys, "sId");
        const tableReturnData = props.onDataRowDel(name, true, tableSelectedRowKeys);
        props.onSaveState({
          ...materials0ReturnData,
          ...tableReturnData,
        });
      }
    } else if (name === "materials2" || name === "materials3" || name === "materials1Child") {
      /* 删除电化铝、油墨子集 */
      /* 从全部材料里 找到对应数据 进行删除 */
      const { [`${name}SelectedRowKeys`]: tableSelectedRowKeys, materials0Data } = props;
      if (commonUtils.isEmptyArr(tableSelectedRowKeys)) {
        message.error("请选择数据！");
        return;
      }
      if (commonUtils.isNotEmptyArr(materials0Data)) {
        const materials0ReturnData = props.otherTableDel("materials0", tableSelectedRowKeys, "sId");
        const tableReturnData = props.onDataRowDel(name, true, tableSelectedRowKeys);
        props.onSaveState({
          ...materials0ReturnData,
          ...tableReturnData,
        });
      }
    } else if (name === "materials0Child") {
      // 删除替代料
      const result = props.onDataRowDel("materials0", true, tableSelectedRowKeys) || {};
      delete result.materials0SelectedRowKeys;
      props.onSaveState(result);
    }
  };
  returnProps.onDataChange = async ({ name, sFieldName, changeValue, sId, dropDownData }) => {
    if (name === "materials") {
      const { [`${name}Data`]: tableData, controlData, controlSelectedRowKeys } = props;
      const tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
      if (tableDataRow === undefined) return;
      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 });
    } else if (name === "materials0" || name === "materials1" || name === "materials2" || name === "materials3" || name === "materials1Child") {
      name = "materials0";
      const { [`${name}Data`]: tableData, controlData, controlSelectedRowKeys, masterData } = props;
      const tableDataRow = await props.onDataChange("materials0", sFieldName, changeValue, sId, dropDownData, true);
      if (sFieldName === "dPackageQty") {
        if (commonUtils.isNotEmptyArr(controlSelectedRowKeys)) {
          const iControlIndex = controlData.findIndex(item => item.sId === controlSelectedRowKeys[0]);
          if (iControlIndex > -1) {
            if (masterData?.sBusinessType === "MergeVersion") {
              tableDataRow.dAuxiThousheetQty = ((controlData[iControlIndex].iCombineNum * 1000.0) / tableDataRow.dPackageQty).toFixed(3);
            } else {
              tableDataRow.dAuxiThousheetQty = ((controlData[iControlIndex].dSinglePQty * 1000.0) / tableDataRow.dPackageQty).toFixed(3);
            }
          }
        }
      }
      if (tableDataRow === undefined) return;

      const iIndex = tableData.findIndex(item => item.sId === sId);
      if (iIndex > -1) {
        tableData[iIndex] = tableDataRow;
      }

      props.onSaveState({ [`${name}Data`]: tableData });
    } else if (name === "materials0Child") {
      /* 替代料 */
      name = "materials0";
      const { [`${name}Data`]: tableData, controlData, controlSelectedRowKeys } = props;
      const tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
      if (sFieldName === "dPackageQty") {
        if (commonUtils.isNotEmptyArr(controlSelectedRowKeys)) {
          const iControlIndex = controlData.findIndex(item => item.sId === controlSelectedRowKeys[0]);
          if (iControlIndex > -1) {
            tableDataRow.dAuxiThousheetQty = ((controlData[iControlIndex].dSinglePQty * 1000.0) / tableDataRow.dPackageQty).toFixed(3);
          }
        }
      }
      if (tableDataRow === undefined) return;
      const iIndex = tableData.findIndex(item => item.sId === sId);
      if (iIndex > -1) {
        tableData[iIndex] = tableDataRow;
      }
      props.onSaveState({ [`${name}Data`]: tableData });
    }
  };
  returnProps.onViewChoose = ({ name, sName, record }) => {
    const { sId } = record; /* 控制表主键 */
    const { slaveData } = props;
    if (name === "materials" && sName === "sCombinePartsNameNew") {
      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((itemPack, 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,
      });
    }
  };
  return returnProps;
};

// 合版信息相关事件
const packProps = props => {
  const returnProps = {};
  returnProps.onDataChange = async ({ name, sFieldName, changeValue, sId, dropDownData }) => {
    const { [`${name}Data`]: tableData, [`${name}SelectedRowKeys`]: tableSelectedRowKeys } = props;
    const tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (sFieldName === "dCombineQty") {
      if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) {
        const dCurrentSqure = commonUtils.convertFixNum(
          commonUtils.isNull(tableDataRow.dProductWidth, 0) *
            commonUtils.isNull(tableDataRow.dProductLength, 0) *
            commonUtils.isNull(tableDataRow.dCombineQty, 0),
          2
        );
        tableDataRow.dSReserve1 = commonUtils.convertFixNum(dCurrentSqure, 2);
        if (tableSelectedRowKeys.length === 1) {
          tableDataRow.dCoefficient = 100; /* 单拼 系数= 100% */
        } else {
          const filterData = tableData.filter(child => tableSelectedRowKeys.includes(child.sId) && child.sId !== tableDataRow.sId);
          let dSumSqure = dCurrentSqure;
          /* 算面积之和 */
          if (commonUtils.isNotEmptyArr(filterData)) {
            filterData.forEach(item => {
              const iFIndex = tableData.findIndex(key => key.sId === item.sId);
              const dSqure =
                commonUtils.isNull(tableData[iFIndex].dProductWidth, 0) *
                commonUtils.isNull(tableData[iFIndex].dProductLength, 0) *
                commonUtils.isNull(tableData[iFIndex].dCombineQty, 0);
              dSumSqure += dSqure;
            });
          }
          tableDataRow.dCoefficient = Math.round(commonUtils.convertFixNum(dCurrentSqure / dSumSqure, 2) * 100);
          console.log("当前系数", Math.round(tableDataRow.dCoefficient));
          /* 算其他系数 */
          if (commonUtils.isNotEmptyArr(filterData)) {
            filterData.forEach((row, index) => {
              const iFIndex = tableData.findIndex(key => key.sId === row.sId);
              const dSqure = tableData[iFIndex].dProductWidth * tableData[iFIndex].dProductLength * tableData[iFIndex].dCombineQty;
              const dCoefficient = commonUtils.convertFixNum(dSqure / dSumSqure, 2) * 100;
              const addState = {};
              addState.dCoefficient = Math.round(dCoefficient);
              console.log("其他系数", Math.round(dCoefficient));
              if (iFIndex > -1) {
                tableData[iFIndex] = { ...tableData[iFIndex], ...addState };
              }
            });
          }
        }
      }
    }
    if (tableDataRow === undefined) return;
    const iIndex = tableData.findIndex(item => item.sId === sId);
    if (iIndex > -1) {
      tableData[iIndex] = tableDataRow;
    }
    props.onSaveState({ [`${name}Data`]: tableData });
  };
  return returnProps;
};

// 入口
const ProcessCardPackTableTreeNew = 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 = ProcessCardPackTableTreeNewEvent({ ...commonPackProps, ...otherProps });
  const { masterData } = props;
  if (!masterData) return "";

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

// 包一层Form
const ProcessCardPackTableTreeNewComponent = 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);
  }

  return (
    <div className={`xly-workorder-list ${styles.ProcessCardPackTableTreeNew}`}>
      <ToolBarComponent {...props} />
      <div className={styles.content}>
        <AvatarComponent {...props} />
        <MasterComponent {...props} />
        <SlaveComponent {...props} />
        <ControlComponent {...props} />
        <OtherComponent {...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 = [] } = 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,
  };

  return (
    <div className={styles.controlTable}>
      <StaticEditTable {...controlPropsType} setOpterationColumn="Y" selfTableHeight={82} noVlist />
      {props.getCustomTabPaneExtra('control')}
    </div>
  );
};

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

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

  const { commonConst } = app;

  const [processTabValue, setProcessTabValue] = useState("processInfo");
  const processInfo = commonFunc.showMessage(commonConst, "processInfo"); // 工序信息
  const dailyInfo = commonFunc.showMessage(commonConst, "dailyInfo"); // 日志信息
  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 [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>;
            })}
          </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={3}>{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} />}
      </Panel>

      <Panel collapsible="header" header={getHeaderIcon("material")} showArrow={false} extra={panelExtra("material")} key="material">
        <MaterialsComponent {...props} materialsTabValue={materialsTabValue} />
      </Panel>
      {materialsChildInfoListFilter.map(tablename => {
        const { showName } = props[`${tablename}Config`];
        return (
          <Panel
            collapsible="header"
            header={getHeaderIcon(tablename)}
            showArrow={false}
            extra={panelExtra("", { selfName: showName, 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 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 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} />;
};

export default CommonBase(CommonSales(ProcessCardPackTableTreeNew));
