import React, { useEffect, useState } from "react";
import QuotationAllprogressDetail from "./detailNew";
import commonConfig from "@/utils/config";
import { Toast, Input, Tabs, Selector, Grid, Image, Button, Checkbox, Switch, Dialog } from "antd-mobile";
import * as commonServices from "@/services/services";
import * as commonFunc from "@/components/Common/commonFunc";
import * as commonBusiness from "@/components/Common/commonBusiness";
import * as commonUtils from "@/utils/utils";
import { cloneDeep } from "lodash";
import moment from "moment";

const masterEvent = props => {
  const { location, quotationData, app, sModelsId } = props;
  const selectedNode = quotationData;
  const { token } = app;
  const [state, setState] = useState(null);
  const [isInitialized, setIsInitialized] = useState(false);
  const [isDraftSaved, setIsDraftSaved] = useState(false);

  const getSqlDropDownData = async (formId, name, showConfig, record, sKeyUpFilterName, pageNum) => {
    const url = `${commonConfig.server_host}business/getSelectLimit/${showConfig.sId}?sModelsId=${sModelsId}`;
    const body = {
      sSqlCondition: {
        sSqlCondition: "",
      },
      sKeyUpFilterName: "",
      pageNum: 1,
      pageSize: 20,
    };
    const retrunData = await commonServices.postValueService(token, body, url);
    if (retrunData.data.code === 1) {
      const { rows, totalPageCount, currentPageNo, totalCount } = retrunData.data.dataset;
      return {
        dropDownData: rows,
        totalPageCount,
        currentPageNo,
        totalCount,
      };
    }
  };

  // 获取主表信息
  useEffect(() => {
    const configUrl = `${commonConfig.server_host}business/getModelBysId/${sModelsId}?sModelsId=${sModelsId}`;
    commonServices
      .getService(token, configUrl)
      .then(async ({ data: masterReturn }) => {
        if (masterReturn.code === 1) {
          const formData = masterReturn.dataset.rows[0].formData;
          const masterConfig = formData.find(x => x.sTbName === "QuoQuotationmaster");
          const processConfig = formData.find(x => x.sTbName === "QuoQuotationprocess");
          const materialsConfig = formData.find(x => x.sTbName === "QuoQuotationmaterials");
          const slaveConfig = formData.find(x => x.sTbName === "QuoQuotationslave");
          const controlConfig = formData.find(x => x.sTbName === "QuoQuotationcontrol");

          let colorConfig = {};
          // const colorConfigTrue = formData.find(item => item.sTbName === "quoquotationparam");
          // if (commonUtils.isNotEmptyObject(colorConfigTrue)) {
          //   colorConfig = { ...colorConfigTrue };
          // }

          const packConfig = formData.find(item => item.sTbName === "quoquotationcontrolcombine");

          let checkConfig = {};
          let checkColumn = {};
          if (commonUtils.isNotEmptyArr(formData.filter(item => item.bGrd && item.sTbName === "sysbillcheckresult"))) {
            checkConfig = formData.find(item => item.bGrd && item.sTbName === "sysbillcheckresult");
            checkColumn = commonFunc.getHeaderConfig(checkConfig);
          }
          setState(prevState => ({
            ...prevState,
            formData,
            masterConfig,
            processConfig,
            materialsConfig,
            slaveConfig,
            controlConfig,
            colorConfig,
            packConfig,
            checkConfig,
            selectedNode,
          }));
        }
      })
      .catch(error => {
        console.error("获取主表信息失败：", error);
      });
  }, []);

  const handleSaveState = (newValues, callback) => {
    setState(prevState => {
      const mergedState = { ...prevState, ...newValues };
      // 确保回调在状态更新后执行
      if (typeof callback === "function") {
        // 使用 setTimeout 确保回调在下一个事件循环中执行
        setTimeout(() => {
          callback(mergedState);
        }, 0);
      }
      return mergedState;
    });
  };

  const { slaveData = [], packData = [], colorData = [], controlData = [], processData = [], materialsData = [] } = props;

  // 初始化数据
  useEffect(() => {
    if (!isInitialized) {
      const slaveRow = {
        handleType: "add",
        sId: commonUtils.createSid(),
        key: commonUtils.createSid(),
        sParentId: commonUtils.createSid(),
        sNodeId: commonUtils.createSid(),
        bDefault: false,
        iOrder: 1,
      };
      slaveData.push(slaveRow);

      const packRow = {
        sId: commonUtils.createSid(),
        handleType: "add",
        sSlaveId: commonUtils.createSid(),
        iOrder: 1,
        sParentId: commonUtils.createSid(),
        sControlId: commonUtils.createSid(),
        dProductQty: 0,
        dCombineQty: 1,
      };
      packData.push(packRow);

      const controlRow = {
        dSumPQty: 2,
        iPrintMode: 0,
        iPositiveColor: 4,
        iOppositeColor: 4,
        sSlaveId: " ",
        iPrintModePo: 2,
        handleType: "add",
        sId: commonUtils.createSid(),
        sParentId: commonUtils.createSid(),
        key: commonUtils.createSid(),
        bDefault: false,
        iOrder: 1,
        sCombinedMemo: "合版信息",
        sAllId: commonUtils.createSid(),
        dPartsQty: 0,
      };
      controlData.push(controlRow);
      const masterData = {
        handleType: "add",
        iPositiveColor: 4,
        maxBillNo: "sBillNo",
        sFormId: sModelsId,
        sId: commonUtils.createSid(),
      };
      setState(prevState => ({
        ...prevState,
        slaveData,
        packData,
        controlData,
        colorData,
        processData,
        materialsData,
        masterData,
        mastersId: masterData.sId,
      }));

      setIsInitialized(true);
    }
  }, [isInitialized, slaveData, packData, controlData, colorData, processData, materialsData]);

  // 确保 state 数据已加载
  if (!state) {
    return null; // 或者加载状态组件
  }

  return {
    ...props,
    selectedNode: quotationData,
    manyDataCache: [],
    token,
    getSqlDropDownData,
    onMaterialsChange: handleMaterialsChange,
    sortData,
    handleCalculation,
    onSaveState: handleSaveState,
    onSaveData: handleSaveData,
    onSubmit: handleSave,
    isDraftSaved,
    setIsDraftSaved,
    // onButtonClick: handleButtonClick,
    ...state,
  };
};
// 遍历下所有配置sButtonEnabled的字段，生成配置

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

    const iIndex2 = tableData.findIndex(item => item.sId === g2.sControlId) === -1 ? 999 : tableData.findIndex(item => item.sId === g2.sControlId);
    let sPartOrder2 = `0000${iIndex2}`;
    sPartOrder2 = sPartOrder2.substring(sPartOrder2.length - 3);
    let sOrder2 = `000${g2.iOrder}`;
    sOrder2 = sOrder2.substring(sOrder2.length - 3);
    return parseInt(sPartOrder1 + g1.sType + sOrder1, 10) - parseInt(sPartOrder2 + g2.sType + sOrder2, 10);
  });
  return processData;
};
const handleMaterialsChange = async (tableDataRow, sModelsId, masterData, changeValue, sFieldName, app, token, models) => {
  const { sComputeId, sConversionComputeId, sReConversionComputeId } = tableDataRow;
  if (
    sFieldName === "sMaterialsNo" ||
    sFieldName === "sMaterialsName" ||
    sFieldName === "dAuxiliaryQty" ||
    sFieldName === "dReelAuxiliaryQty" ||
    sFieldName === "dConversionQty" ||
    sFieldName === "sMaterialsStyle" ||
    sFieldName === "dProductQty"
  ) {
    if (sFieldName === "dReelAuxiliaryQty") {
      if (tableDataRow.sMaterialsUnit === "吨" && tableDataRow.bReel && tableDataRow.dGramWeight > 0) {
        tableDataRow = commonBusiness.getMaterialsQty(
          app,
          { ...tableDataRow, sMaterialsStyle: tableDataRow.sReelMaterialsStyle },
          "dReelAuxiliaryQty",
          "dMaterialsQty"
        );
        tableDataRow.dAuxiliaryQty = tableDataRow.dMaterialsQty;
        tableDataRow.sMaterialsStyle =
          tableDataRow.sMaterialsStyle !== undefined && tableDataRow.sMaterialsStyle.split("*").length > 1
            ? tableDataRow.sMaterialsStyle.split("*")[0]
            : tableDataRow.sMaterialsStyle;
        tableDataRow.sAuxiliaryUnit = tableDataRow.sMaterialsUnit;
      } else if (tableDataRow.sMaterialsUnit.toUpper() === "M2" && tableDataRow.bReel) {
        tableDataRow = commonBusiness.getMaterialsQty(app, tableDataRow, "dReelAuxiliaryQty", "dMaterialsQty");
        tableDataRow.dAuxiliaryQty = tableDataRow.dReelAuxiliaryQty;
      } else {
        tableDataRow.dAuxiliaryQty = tableDataRow.dReelAuxiliaryQty;
      }
    }
    if (commonUtils.isEmpty(sComputeId) && sFieldName !== "dConversionQty") {
      if (sFieldName === "dProductQty") {
        tableDataRow = commonBusiness.getMaterialsQty(app, tableDataRow, "dProductQty", "dMaterialsQty");
      } else {
        tableDataRow = commonBusiness.getMaterialsQty(app, tableDataRow, "dAuxiliaryQty", "dMaterialsQty");
      }
    } else if (!commonUtils.isEmpty(sComputeId)) {
      tableDataRow.dMaterialsQty = await commonBusiness.getFormulaValue({
        token,
        sModelsId,
        masterData,
        tableDataRow,
        sComputeId,
      });
    }
    if (sFieldName !== "dConversionQty" && !commonUtils.isEmpty(sConversionComputeId)) {
      tableDataRow.dConversionQty = await commonBusiness.getFormulaValue({
        token,
        sModelsId,
        masterData,
        tableDataRow,
        sComputeId: sConversionComputeId,
      });
    }
  } else if (sFieldName === "dMaterialsQty") {
    const { sReComputeId } = tableDataRow;
    if (commonUtils.isEmpty(sReComputeId) && tableDataRow.bInverse) {
      tableDataRow = commonBusiness.getAuxiliaryQty(app, tableDataRow, sFieldName, "dAuxiliaryQty");
    } else if (tableDataRow.bInverse) {
      tableDataRow.dAuxiliaryQty = await commonBusiness.getFormulaValue({
        token,
        sModelsId,
        masterData,
        tableDataRow,
        sComputeId: sReComputeId,
      });
      if (commonUtils.isNotEmptyArr(tableDataRow.dAuxiliaryQty) && tableDataRow.dAuxiliaryQty !== 0) {
        tableDataRow.dProductQty = tableDataRow.dAuxiliaryQty;
      }
    }
    if (!commonUtils.isEmpty(sReConversionComputeId)) {
      tableDataRow.dConversionQty = await commonBusiness.getFormulaValue({
        token,
        sModelsId,
        masterData,
        tableDataRow,
        sComputeId: sReConversionComputeId,
      });
    }
  } else if (sFieldName === "dAuxiliaryLossQty") {
    if (commonUtils.isEmpty(sComputeId)) {
      tableDataRow = commonBusiness.getMaterialsQty(app, tableDataRow, sFieldName, "dLossQty");
    } else {
      tableDataRow.dLossQty = await commonBusiness.getFormulaValue({
        token,
        sModelsId,
        masterData,
        tableDataRow,
        sComputeId,
      });
    }
    if (!commonUtils.isEmpty(tableDataRow.dSrcSurplusAuxiliaryQty)) {
      tableDataRow.dAuxiliaryQty = tableDataRow.dSrcSurplusAuxiliaryQty - tableDataRow.dAuxiliaryLossQty;
      tableDataRow.dMaterialsQty = commonUtils.convertFixNum(tableDataRow.dSrcSurplusQty - tableDataRow.dLossQty, 6);
    }
  } else if (sFieldName === "dLossQty") {
    const { sReComputeId } = tableDataRow;
    if (commonUtils.isEmpty(sReComputeId)) {
      tableDataRow = commonBusiness.getAuxiliaryQty(app, tableDataRow, sFieldName, "dAuxiliaryLossQty");
    } else {
      tableDataRow.dAuxiliaryLossQty = await commonBusiness.getFormulaValue({
        token,
        sModelsId,
        masterData,
        tableDataRow,
        sComputeId: sReComputeId,
      });
    }
    if (!commonUtils.isEmpty(tableDataRow.dSrcSurplusAuxiliaryQty)) {
      tableDataRow.dAuxiliaryQty = tableDataRow.dSrcSurplusAuxiliaryQty - tableDataRow.dAuxiliaryLossQty;
      tableDataRow.dMaterialsQty = tableDataRow.dSrcSurplusQty - tableDataRow.dLossQty;
    }
  } else if (sFieldName === "sProcessId" || sFieldName === "sProcessNo" || sFieldName === "sProcessName") {
    const sProcessId = changeValue.sProcessId;
    const url = `${commonConfig.server_host}process/outsideprocess?sModelsId=${sModelsId}&sProcessId=${sProcessId}`;
    const dataReturn = (await commonServices.getService(token, url)).data;
    if (dataReturn.code === 1) {
      if (commonUtils.isNotEmptyArr(dataReturn.dataset.rows)) {
        tableDataRow.dMaterialsPrice = dataReturn.dataset.rows[0].dMaterialsPrice;
      }
      tableDataRow = commonBusiness.getCalculateAllMoney(app, models, "dMaterialsPrice", masterData, tableDataRow);
    }
  }
  return tableDataRow;
};
// 计算数量
const handleCalculation = async (bSave, nextProps, isWait, props) => {
  const dataUrl = `${commonConfig.server_host}business/addQuotationsheet?sModelsId=${nextProps.sModelsId}`;
  const {
    masterConfig,
    slaveConfig,
    slaveDelData,
    controlConfig,
    controlDelData,
    colorConfig,
    colorData,
    colorDelData,
    materialsConfig,
    materialsDelData,
    processConfig,
    processDelData,
    app,
    manyqtysConfig,
    manyqtysDelData,
    packConfig,
    packDelData,
    manyDataCache = [],
    dQuickQuoteProductQty,
  } = nextProps;
  let { slaveData, controlData, materialsData, processData, masterData, manyqtysData, packData } = nextProps;
  const sMakePerson = masterData.sMakePerson;
  const data = [];
  data.push(commonBusiness.mergeData("master", `${masterConfig.sTbName.toLowerCase()}_Tmp`, [masterData], [], true));
  data.push(commonBusiness.mergeData("slave", `${slaveConfig.sTbName.toLowerCase()}_tmp`, slaveData, [], true));
  data.push(commonBusiness.mergeData("control", `${controlConfig.sTbName.toLowerCase()}_tmp`, controlData, [], true));
  data.push(commonBusiness.mergeData("materials", `${materialsConfig.sTbName.toLowerCase()}_tmp`, materialsData, [], true));
  data.push(commonBusiness.mergeData("process", `${processConfig.sTbName.toLowerCase()}_tmp`, processData, [], true));
  if (commonUtils.isNotEmptyObject(manyqtysConfig)) {
    data.push(
      commonBusiness.mergeData(
        "manyqtys",
        `${manyqtysConfig.sTbName.toLowerCase()}_tmp`,
        manyqtysData?.map(item => {
          delete item.manyData;
          return item;
        }),
        [],
        true
      )
    );
  }

  data.push(commonBusiness.mergeData("pack", `${packConfig.sTbName.toLowerCase()}_tmp`, packData, [], true));
  const value = { data, sClientType: "1", sGuid: masterData.sId };

  const cacheIndex = dQuickQuoteProductQty === undefined ? -1 : manyDataCache.findIndex(item => item.dManyQty === dQuickQuoteProductQty);
  if (cacheIndex === -1) {
    // message.warning("自动计算中，请稍后再试。");
    Toast.show({
      content: "自动计算中，请稍后再试。",
    });
  }
  const dataReturn = cacheIndex === -1 ? (await commonServices.postValueService(props.app.token, value, dataUrl)).data : manyDataCache[cacheIndex];
  if (dataReturn.code === 1) {
    /*   成功   */
    const valueReturn = dataReturn.dataset.rows[0];
    const masterDataArr = valueReturn[`${masterConfig.sTbName.toLowerCase()}_tmp`];
    if (commonUtils.isNotEmptyArr(masterDataArr)) {
      masterData = masterDataArr[0];
    }
    if (cacheIndex !== -1) {
      // masterData.handleType = nextProps.masterData.handleType || "update";
      masterData.sQuoConfig = nextProps.masterData.sQuoConfig;
      masterData.sFormId = nextProps.masterData.sFormId;
      masterData.sBillNo = nextProps.masterData.sBillNo;
    }
    // masterData.handleType = nextProps.handleType && nextProps.handleType === "update" ? "update" : "add";
    if (masterData.handleType === "update" && !commonUtils.isEmpty(sMakePerson)) {
      masterData.sMakePerson = sMakePerson;
      if (masterData.sBillNo === "") {
        const slaveUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${"172129113112117410664746760"}?sModelsId=${
          props.sModelsId
        }`;
        const value = { sId: masterData.sId };
        const slaveReturnData = (await commonServices.postValueService(props.app.token, value, slaveUrl)).data;
        const data = slaveReturnData.dataset.rows[0].dataSet[0];
        masterData = { ...data };
      }
    }
    slaveData = valueReturn[`${slaveConfig.sTbName.toLowerCase()}_tmp`].map(item => {
      item.handleType = dQuickQuoteProductQty ? "update" : item.handleType;
      item.sId = commonUtils.createSid();
      return item;
    });

    controlData = valueReturn[`${controlConfig.sTbName.toLowerCase()}_tmp`].map(item => {
      item.handleType = dQuickQuoteProductQty ? "update" : item.handleType;
      item.sId = commonUtils.createSid();
      return item;
    });
    materialsData = valueReturn[`${materialsConfig.sTbName.toLowerCase()}_tmp`].map(item => {
      item.handleType = dQuickQuoteProductQty ? "add" : item.handleType;
      item.sId = commonUtils.createSid();
      return item;
    });
    processData = valueReturn[`${processConfig.sTbName.toLowerCase()}_tmp`].map(item => {
      item.handleType = dQuickQuoteProductQty ? "add" : item.handleType;
      item.sId = commonUtils.createSid();
      return item;
    });
    processData = props.sortData(controlData, processData);
    const addState = {};
    if (commonUtils.isNotEmptyObject(manyqtysConfig)) {
      manyqtysData = valueReturn[`${manyqtysConfig.sTbName.toLowerCase()}_tmp`]?.map((item, index) => {
        return {
          ...item,
          sId: manyqtysData[index] ? manyqtysData[index].sId : item.sId,
          handleType: dQuickQuoteProductQty ? "update" : item.handleType,
        };
      });
      manyqtysData.forEach((x, i) => {
        if (i !== 0) {
          x.sParentId = manyqtysData[0].sParentId;
        }
      });

      if (cacheIndex === -1 && manyqtysData?.some(item => item.manyData)) {
        addState.manyDataCache = manyqtysData.map((item, index) => {
          let result = {};
          if (index === 0) {
            result = Object.keys(valueReturn).reduce((pre, cur) => {
              if (cur !== `${manyqtysConfig.sTbName.toLowerCase()}_tmp`) {
                pre[cur] = valueReturn[cur];
              }
              return pre;
            }, {});
          } else {
            result = commonUtils.convertStrToObj(item.manyData);
          }

          result[`${manyqtysConfig.sTbName.toLowerCase()}_tmp`] = cloneDeep(manyqtysData).map(item => {
            delete item.manyData;
            return item;
          });

          const { sId, sBillNo, sFormId } = masterData;
          const row = Object.keys(result).reduce((pre, cur) => {
            if (cur === `${masterConfig.sTbName.toLowerCase()}_tmp`) {
              pre[cur] = result[cur].map(item => ({
                ...item,
                sId,
                sBillNo: sBillNo || item.sBillNo,
                sFormId,
              }));
            } else if (cur.includes("_tmp")) {
              pre[cur] = result[cur].map(item => ({
                ...item,
                sParentId: sId,
                handleType: "add",
              }));
            } else {
              pre[cur] = result[cur];
            }
            return pre;
          }, {});

          return {
            code: 1,
            dManyQty: item.dManyQty,
            dataset: {
              rows: [row],
            },
          };
        });
      }
    }

    packData = valueReturn[`${packConfig.sTbName.toLowerCase()}_tmp`];
    /* 计算成功后自动调用保存 */
    if (bSave) {
      const data = [];
      // masterData.handleType = "update";
      // masterData.sFormId = commonUtils.createSid()
      masterData.sId = commonUtils.createSid();
      data.push(commonBusiness.mergeData("master", masterConfig.sTbName, [masterData]));
      data.push(commonBusiness.mergeData("slave", slaveConfig.sTbName, slaveData, slaveDelData));
      data.push(commonBusiness.mergeData("control", controlConfig.sTbName, controlData, controlDelData));
      data.push(commonBusiness.mergeData("materials", materialsConfig.sTbName, materialsData, materialsDelData));
      data.push(commonBusiness.mergeData("process", processConfig.sTbName, processData, processDelData));

      if (commonUtils.isNotEmptyObject(manyqtysConfig)) {
        data.push(commonBusiness.mergeData("manyqtys", manyqtysConfig.sTbName, manyqtysData, manyqtysDelData));
      }

      data.push(commonBusiness.mergeData("color", colorConfig.sTbName, colorData, colorDelData));
      data.push(commonBusiness.mergeData("pack", packConfig.sTbName, packData, packDelData));

      props.onSaveData(
        {
          data,
          sClientType: "1",
          loading: false,
          sSysLogSrcId: masterData.sId,
        },
        props
      );
      props.onSaveState({
        slaveData,
        packData,
        controlData,
        materialsData,
        processData,
        masterData,
        manyqtysData,
        ...addState,
      });
    } else {
      // masterData.handleType = "update";
      if (isWait) {
        return {
          slaveData,
          controlData,
          materialsData,
          processData,
          masterData,
          manyqtysData,
          loading: false,
          packData,
          handleType: "update",
          ...addState,
        };
      } else {
        props.onSaveState({
          slaveData,
          controlData,
          materialsData,
          processData,
          masterData,
          manyqtysData,
          loading: false,
          packData,
          ...addState,
          handleType: "update",
        });
      }
      // message.success(commonFunc.getConfigShowName(masterConfig, "BtnCalculation") + commonFunc.showMessage(app.commonConst, "handleSuccess"));
    }
  } else {
    /*   失败   */
    props.onSaveState({
      loading: false,
    });
    // this.props.getServiceError(dataReturn);
  }
};
/** 按钮操作事件 */
const handleButtonClick = async (name, props) => {
  if (name === "BtnDraft") {
    const {
      masterConfig,
      masterData,
      slaveConfig,
      slaveData,
      slaveDelData,
      controlConfig,
      controlData, // 需要
      controlDelData,
      materialsConfig,
      materialsData,
      materialsDelData,
      processConfig,
      processData,
      processDelData,
      colorConfig,
      colorData,
      colorDelData,
      packConfig,
      packData, // 需要
      packDelData,
    } = props;
    const data = [];
    slaveConfig.gdsconfigformslave.forEach(itemConfig => {
      slaveData
        .filter(itemData => itemData.handleType === "add" || itemData.handleType === "update")
        .forEach(itemData => {
          itemData.NoVerify = "NoVerify";
          const firstDataIndex = itemConfig.sName.substring(0, 1);
          if (commonUtils.isEmpty(itemData[itemConfig.sName])) {
            itemData[itemConfig.sName] =
              firstDataIndex === "s"
                ? ""
                : firstDataIndex === "d" || firstDataIndex === "i"
                ? 0
                : firstDataIndex === "b"
                ? false
                : firstDataIndex === "t"
                ? moment(new Date()).format(props.app.dateFormat)
                : undefined;
          }
        });
    });
    controlConfig.gdsconfigformslave.forEach(itemConfig => {
      controlData
        .filter(itemData => itemData.handleType === "add" || itemData.handleType === "update")
        .forEach(itemData => {
          itemData.NoVerify = "NoVerify";
          const firstDataIndex = itemConfig.sName.substring(0, 1);
          if (commonUtils.isEmpty(itemData[itemConfig.sName])) {
            itemData[itemConfig.sName] =
              firstDataIndex === "s"
                ? ""
                : firstDataIndex === "d" || firstDataIndex === "i"
                ? 0
                : firstDataIndex === "b"
                ? false
                : firstDataIndex === "t"
                ? moment(new Date()).format(props.app.dateFormat)
                : undefined;
          }
        });
    });

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

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

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

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

    data.push(commonBusiness.mergeData("master", masterConfig.sTbName, [masterData]));
    data.push(commonBusiness.mergeData("slave", slaveConfig.sTbName, slaveData, slaveDelData));
    data.push(commonBusiness.mergeData("control", controlConfig.sTbName, controlData, controlDelData));
    data.push(commonBusiness.mergeData("materials", materialsConfig.sTbName, materialsData, materialsDelData));
    data.push(commonBusiness.mergeData("process", processConfig.sTbName, processData, processDelData));
    if (commonUtils.isNotEmptyObject(colorConfig)) {
      data.push(commonBusiness.mergeData("color", colorConfig.sTbName, colorData, colorDelData));
    }
    if (commonUtils.isNotEmptyObject(packConfig)) {
      data.push(commonBusiness.mergeData("pack", packConfig.sTbName, packData, packDelData));
    }
    // 核价后保存
    props.onSaveData(
      {
        data,
        sClientType: "1",
        loading: false,
        sSysLogSrcId: masterData.sId,
        bIsUnCcg: false,
      },
      props
    );
  }
};
const handleSaveData = async (params, props) => {
  const {
    token,
    sModelsId,
    currentId,
    masterData,
    masterConfig,
    slaveConfig,
    checkConfig,
    billnosetting,
    app,
    sModelsType,
    controlConfig,
    materialsConfig,
    processConfig,
    colorConfig,
    packConfig,
    orderDetailConfig,
    dispatch,
    slaveChildConfig,
  } = props;
  const { userinfo } = app;
  const { copyTo } = app.currentPane;
  // const onSendSocketMessage = props.handleSendSocketMessage;
  const BtnSave = commonFunc.showMessage(app.commonConst, "BtnSave"); /* 保存 */
  params.optName = BtnSave;
  const returnData = await commonBusiness.saveData({ token, value: params, sModelsId });
  if (commonUtils.isNotEmptyObject(returnData)) {
    if (commonUtils.isNotEmptyObject(copyTo)) {
      const { slaveData } = copyTo;
      const sIdArray = [];
      slaveData.forEach(item => {
        const redisKey = item.sSlaveId;
        sIdArray.push(redisKey);
      });
      const sId = sIdArray.toString();
      // onSendSocketMessage("copyfinish", "noAction", sId, userinfo.sId, null, null);
    }
    // onSendSocketMessage("release", "noAction", currentId, userinfo.sId, null, null);
    Toast.show({
      content: "保存成功",
    });
    // masterData.handleType = "update";
    props.setIsDraftSaved(true);
    props.onSaveState({
      enabled: false,
      currentId: masterData.sId,
      masterData,
    });
    // 保存后更新panes,currentPane的checkedId，防止浏览器刷新时重新又变成新增。
    const iPaneIndex = app.panes.findIndex(item => item.key === app.currentPane.key);
    app.panes[iPaneIndex].checkedId = masterData.sId;
    app.currentPane.checkedId = masterData.sId;
    // dispatch({ type: "app/savePanesAndCurrentPane", payload: { panes: app.panes, currentPane: app.currentPane } });

    // if (billnosetting.bAutoCheck) {
    //   await this.handleAudit(1);
    // } else {
    //   await this.handleGetData(masterConfig, slaveConfig, checkConfig);
    //   if ((sModelsType.includes("sales/salesOrder") || sModelsType.includes("manufacture/workOrder")) && !commonUtils.isEmpty(controlConfig)) {
    //     await this.handleGetMemoData(controlConfig, materialsConfig, processConfig, colorConfig, packConfig);
    //   } else if (sModelsType === "purchase/purchaseOrder") {
    //     await this.handleGetOneMemoData("orderDetail", orderDetailConfig);
    //   } else if (sModelsType === "sales/salesSgoods" && !commonUtils.isEmpty(slaveChildConfig)) {
    //     await this.handleGetOneMemoData("slaveChild", slaveChildConfig);
    //   }
    //   if (this.props.app.currentPane.refresh !== undefined) {
    //     this.props.app.currentPane.refresh();
    //   }
    // }
    props.onSaveState({
      loading: false,
    });
    return true;
  } else {
    props.onSaveState({
      loading: false,
    });
    return false;
  }
};
// 保存
const handleSave = async (skipCalculation, props) => {
  /*   验证成功   */
  const {
    masterConfig,
    masterData,
    slaveConfig,
    slaveData,
    slaveDelData,
    controlConfig,
    controlData,
    controlDelData,
    colorConfig,
    colorData,
    colorDelData,
    materialsConfig,
    materialsData,
    materialsDelData,
    processConfig,
    processData,
    processDelData,
    app,
    manyqtysConfig,
    manyqtysData,
    manyqtysDelData,
    packConfig,
    packData,
    packDelData,
  } = props;
  if (commonUtils.isEmptyArr(slaveData)) {
    // message.warning(`从表${commonFunc.showMessage(props.app.commonConst, "isNotNull")}`);
    props.onSaveState({
      loading: false,
    });
    return;
  }
  if (
    !commonBusiness.validateTable(slaveConfig, slaveData, props) ||
    !commonBusiness.validateTable(controlConfig, controlData, props) ||
    !commonBusiness.validateTable(materialsConfig, materialsData, props) ||
    !commonBusiness.validateTable(processConfig, processData, props) ||
    !commonBusiness.validateTable(colorConfig, colorData, props) ||
    !commonBusiness.validateTable(packConfig, packData, props)
  ) {
    props.onSaveState({
      loading: false,
    });
    return;
  }
  const data = [];
 
  data.push(commonBusiness.mergeData("master", masterConfig.sTbName, [masterData]));
  data.push(commonBusiness.mergeData("slave", slaveConfig.sTbName, slaveData, slaveDelData));
  data.push(commonBusiness.mergeData("control", controlConfig.sTbName, controlData, controlDelData));
  data.push(commonBusiness.mergeData("materials", materialsConfig.sTbName, materialsData, materialsDelData));
  data.push(commonBusiness.mergeData("process", processConfig.sTbName, processData, processDelData));

  if (commonUtils.isNotEmptyObject(manyqtysConfig)) {
    data.push(commonBusiness.mergeData("manyqtys", manyqtysConfig.sTbName, manyqtysData, manyqtysDelData));
  }

  data.push(commonBusiness.mergeData("color", colorConfig.sTbName, colorData, colorDelData));
  data.push(commonBusiness.mergeData("pack", packConfig.sTbName, packData, packDelData));
  let skipFlag = 1; /* 默认不调用自动计算 若column有值 代表数据有更改 为0则调用自动计算  */
  if (commonUtils.isNotEmptyArr(data)) {
    for (const table of data) {
      for (const key of Object.keys(table)) {
        if (key.includes("column")) {
          /* 只要一个column有值 代表有更改 要走自动计算 */
          if (commonUtils.isNotEmptyArr(table[key])) {
            skipFlag = 0;
            break;
          }
        }
      }
      if (skipFlag === 0) {
        /* skipFlag=0 代表不自动计算 */
        break;
      }
    }
  }
  if ((skipFlag === 0 || masterData.bNoVerify) && !skipCalculation) {
    handleCalculation(true, props.state.newNextProps, false, props);
  } else {
    props.onSaveData({
      data,
      sClientType: "1",
      loading: false,
      sSysLogSrcId: masterData.sId,
    });
  }
};
/** 表格数据更改 */
// name 不写完整的state名称作用为了要用到total // (name, changeValue, sId, dropDownData)
const handleTableChange = async (name, sFieldName, changeValue, sId, dropDownData, props) => {
  /*   从CommonBase获取默认参数   */
  if (name === "slave") {
    const { sModelsId, [`${name}Data`]: tableData, masterConfig, controlConfig, controlData: controlDataOld, masterData, app, packData } = props;
    const { dNetMoney } = app.decimals;
    let 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;

    let bCkxNoTaxProcessPrice = "0";
    const filterData = app.systemData.filter(item => item.sName === "CkxNoTaxProcessPrice");
    if (commonUtils.isNotEmptyArr(filterData) && filterData.length > 0) {
      bCkxNoTaxProcessPrice = filterData[0].sValue;
    }
    const dCurrencyRate = commonUtils.convertIsNotNumToNumber1(tableDataRow.dCurrencyRate); /* 汇率 */

    const addState = {};
    /* 主表配置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 (sFieldName === "dProductQty" || sFieldName === "dGiveQty" || sFieldName === "dStockupQty") {
      let dPartsQty = 0;
      tableData.forEach(item => {
        if (bProductQtySelf) {
          dPartsQty += commonUtils.isNull(item.dProductQty, 0);
        } else {
          dPartsQty += commonUtils.isNull(item.dProductQty, 0) + commonUtils.isNull(item.dGiveQty, 0) + commonUtils.isNull(item.dStockupQty, 0);
        }
      });
      /* 找到所有一级部件 */
      const controlRootData = commonUtils.isNotEmptyArr(controlDataOld)
        ? controlDataOld.filter(item => commonUtils.isEmpty(item.sControlParentId))
        : [];
      if (commonUtils.isNotEmptyArr(controlRootData)) {
        controlRootData.forEach(item => {
          let itemNew = { ...item };
          /* 父级的dPartsQty为dPartsQty */
          itemNew.dPartsQty = dPartsQty;
          itemNew = singlePQtyChange(itemNew);
          /* 找到子部件 */
          const controlChildData = controlDataOld.filter(
            itemOld => commonUtils.isNotEmptyObject(itemOld.sAllId) && itemOld.sAllId.indexOf(item.sId) > -1 && itemOld.sId !== item.sId
          );
          if (commonUtils.isNotEmptyArr(controlChildData)) {
            const { dMachineQty } = itemNew;
            controlChildData.forEach(child => {
              let tableDataRow = { ...child };
              const iIndex = controlDataOld.findIndex(item => item.sId === child.sId);
              if (iIndex > -1) {
                /* 子部件部件数量为父部件上机数量  */
                tableDataRow.dPartsQty = dMachineQty;
                tableDataRow = singlePQtyChange(tableDataRow);
                controlDataOld[iIndex] = tableDataRow;
              }
            });
          }
          const addStata = {};
          addStata.dPartsQty = dPartsQty;
          const iRootIndex = controlDataOld.findIndex(itemControl => itemControl.sId === item.sId);
          controlDataOld[iRootIndex] = { ...controlDataOld[iRootIndex], ...itemNew };
        });
      }
      addState.controlData = controlDataOld;
    } else if (sFieldName === "sCustomerId" || sFieldName === "sCustomerNo" || sFieldName === "sCustomerName") {
      // commonUtils.setStoreDropDownData(sModelsId, 'slave', 'sProductId', []);
      // commonUtils.setStoreDropDownData(sModelsId, 'slave', 'sProductNo', []);
      // commonUtils.setStoreDropDownData(sModelsId, 'slave', 'sProductName', []);
      tableDataRow.sProductId = "";
      tableDataRow.sProductNo = "";
      tableDataRow.sProductName = "";
      tableData[iIndex] = tableDataRow;
    } else if (
      (sFieldName === "dProductMoney" || sFieldName === "dProductPrice" || sFieldName === "dProductForeignMoney") &&
      !commonUtils.isEmpty(tableDataRow.dStandardMoney)
    ) {
      let dProductMoney = commonUtils.isNull(tableDataRow.dProductMoney, 0);

      if (sFieldName === "dProductForeignMoney") {
        const dProductForeignMoney = commonUtils.isNull(tableDataRow.dProductForeignMoney, 0);
        dProductMoney = commonUtils.convertFixNum(dCurrencyRate !== 0 ? dProductForeignMoney * dCurrencyRate : 0, dNetMoney); /* 本位币金额 */
      }
      /* 不启用工序价格不含税 则计算利润时 无需减掉含税金额 */
      if (bCkxNoTaxProcessPrice === "0") {
        tableDataRow.dProfitMoney = commonUtils.convertFixNum(
          commonUtils.isNull(dProductMoney, 0) -
            commonUtils.isNull(tableDataRow.dStandardMoney, 0) -
            commonUtils.isNull(masterData.dPackMoney, 0) -
            commonUtils.isNull(masterData.dTransportMoney, 0),
          dNetMoney
        );
      } else {
        tableDataRow.dProfitMoney = commonUtils.convertFixNum(
          commonUtils.isNull(dProductMoney, 0) -
            commonUtils.isNull(tableDataRow.dProductTaxMoney, 0) -
            commonUtils.isNull(tableDataRow.dStandardMoney, 0) -
            commonUtils.isNull(masterData.dPackMoney, 0) -
            commonUtils.isNull(masterData.dTransportMoney, 0),
          dNetMoney
        );
      }
      // eslint-disable-next-line no-mixed-operators
      tableDataRow.dProfitRate =
        commonUtils.isNull(tableDataRow.dStandardMoney, 0) !== 0
          ? commonUtils.convertFixNum(
              (commonUtils.isNull(tableDataRow.dProfitMoney, 0) / commonUtils.isNull(tableDataRow.dStandardMoney, 0)) * 100,
              2
            )
          : 0;
    } else if (sFieldName === "dProfitRate" && !commonUtils.isEmpty(tableDataRow.dStandardMoney)) {
      /* 利润 = 标准金额 dStandMoney  * 利润率 dProfitRate */
      tableDataRow.dProfitMoney = commonUtils.convertFixNum(
        commonUtils.isNull(tableDataRow.dStandardMoney, 0) * (commonUtils.isNull(tableDataRow.dProfitRate, 0) / 100),
        dNetMoney
      );
      if (bCkxNoTaxProcessPrice === "0") {
        /* 不启用 则计算利润时 无需减掉含税金额 */
        tableDataRow.dProductMoney = commonUtils.isNull(tableDataRow.dStandardMoney, 0) + commonUtils.isNull(tableDataRow.dProfitMoney, 0);
      } else {
        /* 启用工序价格含税 代表金额已含税 */
        // eslint-disable-next-line no-mixed-operators
        tableDataRow.dProductMoney = commonUtils.convertFixNum(
          (commonUtils.isNull(tableDataRow.dStandardMoney, 0) + commonUtils.isNull(tableDataRow.dProfitMoney, 0)) * (1 + tableDataRow.dTaxRate / 100),
          dNetMoney
        );
      }
      tableDataRow = commonBusiness.getCalculateAllMoney(app, "Product", "dProductMoney", masterData, tableDataRow);
    } else if (sFieldName === "dTaxRate" || sFieldName === "sTaxId" || sFieldName === "sTaxName") {
      // eslint-disable-next-line no-mixed-operators
      const iIndex = app.systemData.findIndex(item => item.sName === "CkxNoTaxProcessPrice");
      if (iIndex > -1 && app.systemData[iIndex] === "1") {
        if (
          !commonUtils.isEmpty(tableDataRow.dStandardMoney) &&
          !commonUtils.isEmpty(tableDataRow.dProfitMoney) &&
          !commonUtils.isEmpty(tableDataRow.dTaxRate)
        ) {
          // eslint-disable-next-line no-mixed-operators
          tableDataRow.dProductMoney = commonUtils.convertFixNum(
            (commonUtils.isNull(tableDataRow.dStandardMoney, 0) + commonUtils.isNull(tableDataRow.dProfitMoney, 0)) *
              (1 + tableDataRow.dTaxRate / 100),
            dNetMoney
          );
          tableDataRow = commonBusiness.getCalculateAllMoney(app, "Product", "dProductMoney", masterData, tableDataRow);
        }
      }
    } else if (sFieldName === "sProductId" || sFieldName === "sProductNo" || sFieldName === "sProductName") {
      // const productIdDropDown = commonUtils.getStoreDropDownData(sModelsId, 'slave', sFieldName);
      const iProductIdIndex = dropDownData.findIndex(item => item.sId === tableData[0].sProductId);
      if (tableDataRow.handleType === "add" && iProductIdIndex > -1 && tableDataRow.sProductId !== tableDataRow.sProductName) {
        if (!commonUtils.isEmpty(tableDataRow.sProductId) && 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;
                  tableDataRow.sAllId = tableDataRow.sId;
                  tableDataRow.sControlParentId = "";
                  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 = 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 = handlePackDataAdd(tableDataRow, 0, sControlId);
            // packDataRow.dCombineQty = 1;
            const pIndex = packData.findIndex(item => item.sId === itemPack.sId);
            if (pIndex > -1) {
              packData[pIndex] = { ...packData[pIndex], ...packDataRow }; /* 根据选中的从表 找到所有的合版数据，将合版数据中的产品换成切换后的产品 */
              let sCombinedMemoStr = ""; /* 将控制表合版信息中的产品换成新选择的产品 */
              if (commonUtils.isNotEmptyArr(controlDataNew)) {
                const iControlIndex = controlDataNew.findIndex(item => item.sId === sControlId);
                if (iControlIndex > -1) {
                  sCombinedMemoStr = controlDataNew[iControlIndex].sCombinedMemo;
                  if (sCombinedMemoStr) {
                    const sCombinedMemoArr = commonUtils.isNotEmptyObject(sCombinedMemoStr) ? JSON.parse(sCombinedMemoStr) : {};
                    if (commonUtils.isNotEmptyArr(sCombinedMemoArr)) {
                      const iIndex = sCombinedMemoArr.findIndex(item => item.sId === itemPack.sId);
                      if (iIndex > -1) {
                        const addState = {};
                        addState.sProductId = tableDataRow.sProductId; /* 产品id */
                        addState.sCustomerId = tableDataRow.sCustomerId; /* 客户id */
                        addState.sCustomerName = tableDataRow.sCustomerName; /* 客户名称 */
                        addState.sProductName = tableDataRow.sProductName; /* 产品名称 */
                        addState.sProductNo = tableDataRow.sProductNo; /* 产品编号 */
                        sCombinedMemoArr[iIndex] = { ...sCombinedMemoArr[iIndex], ...addState };
                        const sCombinedMemo = commonUtils.isNotEmptyArr(sCombinedMemoArr)
                          ? JSON.stringify(sCombinedMemoArr)
                          : ""; /* JSON对象转换为字符串存放到合版信息中 */
                        controlDataNew[iControlIndex].sCombinedMemo = sCombinedMemo;
                        controlDataNew[iControlIndex].sPartsName = tableDataRow.sProductName;
                      }
                    }
                  }
                }
              }
            }
          });
          addState.controlData = controlDataNew;
        }
      }
      addState.packData = packData;
    }
    props.onSaveState({ [`${name}Data`]: tableData, ...addState });
  } else if (name === "control") {
    const {
      [`${name}Data`]: tableData,
      materialsData: materialsDataOld,
      processData: processDataOld,
      sModelsType,
      packData,
      slaveSelectedRowKeys,
      slaveData,
    } = props;
    let tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (tableDataRow === undefined) return;
    if (
      sFieldName === "dSinglePQty" ||
      sFieldName === "dPartsQty" ||
      sFieldName === "dSumPQty" ||
      sFieldName === "iPrintModePo" ||
      sFieldName === "iPrintMode" ||
      sFieldName === "iPrintModePo" ||
      sFieldName === "iPositiveColor" ||
      sFieldName === "iPositiveSpecialColor" ||
      sFieldName === "iOppositeColor" ||
      sFieldName === "iOppositeSpecialColor"
    ) {
      if (sFieldName === "iPrintModePo") {
        if (tableDataRow.iPrintModePo === 0) {
          tableDataRow.iPrintMode = 3;
          if (tableDataRow.iPositiveColor === 0) {
            tableDataRow.iPositiveColor = tableDataRow.iPositiveColor === 0 ? 4 : tableDataRow.iPositiveColor;
            tableDataRow.iOppositeColor = 0;
            tableDataRow.iOppositeSpecialColor = 0;
          } else {
            tableDataRow.iOppositeColor = 0;
            tableDataRow.iOppositeSpecialColor = 0;
          }
        } else if (tableDataRow.iPrintModePo === 1) {
          tableDataRow.iPrintMode = 3;
          if (tableDataRow.iPositiveColor === 0) {
            tableDataRow.iPositiveColor = 0;
            tableDataRow.iPositiveSpecialColor = 0;
            tableDataRow.iOppositeColor = tableDataRow.iOppositeColor === 0 ? 4 : tableDataRow.iOppositeColor;
          } else {
            tableDataRow.iPositiveColor = 0;
            tableDataRow.iPositiveSpecialColor = 0;
          }
        } else {
          tableDataRow.iPositiveColor = tableDataRow.iPositiveColor === 0 ? 4 : tableDataRow.iPositiveColor;
          tableDataRow.iOppositeColor = tableDataRow.iOppositeColor === 0 ? tableDataRow.iPositiveColor : tableDataRow.iOppositeColor;
        }
      } else if (sFieldName === "iPrintMode") {
        if (tableDataRow.iPrintMode === 0 || tableDataRow.iPrintMode === 1) {
          tableDataRow.iPositiveColor =
            commonUtils.isEmpty(tableDataRow.iPositiveColor) || tableDataRow.iPositiveColor === 0 ? 4 : tableDataRow.iPositiveColor;
          tableDataRow.iOppositeColor = tableDataRow.iPositiveColor;
          tableDataRow.iOppositeSpecialColor = tableDataRow.iPositiveSpecialColor;
        } else if (tableDataRow.iPrintMode === 2) {
          tableDataRow.iPositiveColor = tableDataRow.iPositiveColor === 0 ? 4 : tableDataRow.iPositiveColor;
          tableDataRow.iOppositeColor = tableDataRow.iOppositeColor === 0 ? tableDataRow.iPositiveColor : tableDataRow.iOppositeColor;
        } else if (tableDataRow.iPrintMode === 3) {
          tableDataRow.iPositiveColor = tableDataRow.iPositiveColor === 0 ? 4 : tableDataRow.iPositiveColor;
          tableDataRow.iOppositeColor = 0;
          tableDataRow.iOppositeSpecialColor = 0;
        } else if (tableDataRow.iPrintMode === 4) {
          tableDataRow.iPositiveColor = 0;
          tableDataRow.iPositiveSpecialColor = 0;
          tableDataRow.iOppositeColor = 0;
          tableDataRow.iOppositeSpecialColor = 0;
        }
      } else if (sFieldName === "iPositiveColor" || sFieldName === "iPositiveSpecialColor") {
        if (tableDataRow.iPrintMode === 0 || tableDataRow.iPrintMode === 1) {
          tableDataRow.iOppositeColor = tableDataRow.iPositiveColor;
          tableDataRow.iOppositeSpecialColor = tableDataRow.iPositiveSpecialColor;
        }
      } else if (sFieldName === "dSinglePQty") {
        /* 排版数改变时 如果该控制表合版数据只有一条 则改变packData该条的拼版数 改变备注 */
        if (commonUtils.isNotEmptyArr(packData)) {
          const packFilterData = packData.filter(item => item.sControlId === tableDataRow.sId);
          if (commonUtils.isNotEmptyArr(packFilterData) && packFilterData.length === 1) {
            const iIndex = packData.findIndex(itemPack => itemPack.sId === packFilterData[0].sId);
            const addState = {};
            if (tableDataRow.dSinglePQty > 0) {
              addState.dCombineQty = tableDataRow.dSinglePQty;
              addState.handleType = commonUtils.isEmpty(tableDataRow.handleType) ? "update" : tableDataRow.handleType;
              if (iIndex > -1) {
                packData[iIndex] = { ...packData[iIndex], ...addState };
                const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty, sCombinePartsName } = packData[iIndex];
                const tableCombineSelectedData = [];
                const jsonObj = {};
                jsonObj.sId = sId;
                jsonObj.sProductNo = sProductNo; /* 产品编号 */
                jsonObj.dCombineQty = commonUtils.isNotEmptyNumber(dCombineQty) ? dCombineQty : 0; /* 排版数 */
                jsonObj.dProductQty = commonUtils.isNotEmptyNumber(dProductQty) ? dProductQty : 0; /* 生产数 */
                jsonObj.dFactProductQty = commonUtils.isNotEmptyNumber(dFactProductQty) ? dFactProductQty : 0; /* 实际生产数 */
                jsonObj.sCombinePartsName = sCombinePartsName; /* 合版部件名称 */
                tableCombineSelectedData.push(jsonObj);
                const sCombinedMemo = commonUtils.isNotEmptyArr(tableCombineSelectedData)
                  ? JSON.stringify(tableCombineSelectedData)
                  : ""; /* JSON对象转换为字符串存放到合版信息中 */
                tableDataRow.sCombinedMemo = commonUtils.isNotEmptyObject(sCombinedMemo) ? sCombinedMemo : "合版信息";
              }
            }
          }
        }
      }
      tableDataRow = singlePQtyChange(tableDataRow);
      /* 上机数量改变时,子级部件数量同步改变 */
      const { dMachineQty } = tableDataRow;
      /* 查找该节的所有子节点，将上机数量改为部件数量 */
      tableData.forEach((item, index) => {
        if (commonUtils.isNotEmptyObject(item.sAllId) && item.sAllId.indexOf(tableDataRow.sId) > -1 && item.sId !== tableDataRow.sId) {
          const addstate = {};
          addstate.dPartsQty = dMachineQty;
          tableData[index] = { ...tableData[index], ...addstate };
        }
      });
    }
    if (
      sFieldName === "dPartsLength" ||
      sFieldName === "dPartsWidth" ||
      sFieldName === "dMachineLength" ||
      sFieldName === "dMachineWidth" ||
      sFieldName === "sPrintingPlate" ||
      sFieldName === "sCutMethod" ||
      sFieldName === "sSpineDirection" ||
      sFieldName === "iPrintMode" ||
      sFieldName === "dBite" ||
      sFieldName === "dBlood"
    ) {
      /* 计算材料开数 */
      if (true) {
        // if (commonUtils.isNotEmptyArr(slaveData)) {
        //   dProductLength = !commonUtils.isEmpty(slaveData[0].sProductStyle) && slaveData[0].sProductStyle.split('*').length === 2 ? slaveData[0].sProductStyle.split('*')[0] : 0;
        //   dProductLength = commonUtils.convertStrToNumber(commonUtils.isNull(dProductLength, 0)); /* 产品长 */
        //   dProductLength = (typeof dProductLength === 'number' && !isNaN(dProductLength)) ? dProductLength : 0; /* 产品长 */
        //   dProductWidth = !commonUtils.isEmpty(slaveData[0].sProductStyle) && slaveData[0].sProductStyle.split('*').length === 2 ? slaveData[0].sProductStyle.split('*')[1] : 0;
        //   dProductWidth = commonUtils.convertStrToNumber(commonUtils.isNull(dProductWidth, 0)); /* 产品宽 */
        //   dProductWidth = (typeof dProductLength === 'number' && !isNaN(dProductLength)) ? dProductWidth : 0; /* 产品宽 */
        // }

        let slaveDataRow = {};
        if (commonUtils.isNotEmptyArr(slaveData)) {
          if (commonUtils.isEmptyArr(slaveSelectedRowKeys)) {
            slaveDataRow = slaveData[0];
          } else if (commonUtils.isEmptyObject(tableDataRow.sCombinedMemo) || tableDataRow.sCombinedMemo === "合版信息") {
            const iIndex = slaveData.findIndex(item => slaveSelectedRowKeys.includes(item.sId));
            if (iIndex > -1) {
              slaveDataRow = slaveData[iIndex];
            }
          } else {
            const iIndex = slaveData.findIndex(item => tableDataRow.sCombinedMemo.includes(item.sProductNo));
            if (iIndex > -1) {
              slaveDataRow = slaveData[iIndex];
            }
          }
        }
        if (commonUtils.isNotEmptyObject(slaveDataRow)) {
          /* 如果有展开尺寸 则取展开尺寸 否则取产品规格 */
          let sProductStyle = "";
          if (slaveDataRow.sPartsStyle) {
            sProductStyle = slaveDataRow.sPartsStyle;
          } else if (slaveDataRow.sProductStyle) {
            sProductStyle = slaveDataRow.sProductStyle;
          }
          if (sProductStyle) {
            let dProductLength = !commonUtils.isEmpty(sProductStyle) && sProductStyle.split("*").length > 1 ? sProductStyle.split("*")[0] : 0;
            dProductLength = commonUtils.convertStrToNumber(commonUtils.isNull(dProductLength, 0)); /* 产品长 */
            dProductLength = typeof dProductLength === "number" && !isNaN(dProductLength) ? dProductLength : 0; /* 产品长 */
            let dProductWidth = !commonUtils.isEmpty(sProductStyle) && sProductStyle.split("*").length > 1 ? sProductStyle.split("*")[1] : 0;
            dProductWidth = commonUtils.convertStrToNumber(commonUtils.isNull(dProductWidth, 0)); /* 产品宽 */
            dProductWidth = typeof dProductLength === "number" && !isNaN(dProductLength) ? dProductWidth : 0; /* 产品宽 */
            tableDataRow.dPartsWidth = dProductLength;
            tableDataRow.dPartsLength = dProductWidth;
            /* 控制表增加 如果 产品长>产品宽 sSpineDirection 默认1 否则 2 */
            if (dProductLength > dProductWidth) {
              tableDataRow.sSpineDirection = "2"; /* 短书脊 */
            } else {
              tableDataRow.sSpineDirection = "1"; /* 长书脊 */
            }
            tableDataRow.sCutMethod = "2"; /* 默认四边裁 */
            tableDataRow.sPrintingPlate = "1"; /* 默认四边裁 */
          }
        }

        const dProductLength = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dPartsWidth, 0)); /* 产品长 */
        const dProductWidth = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dPartsLength, 0)); /* 产品宽 */
        const dMachineLength = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMachineLength, 0)); /* 上机长 */
        const dMachineWidth = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMachineWidth, 0)); /* 上机宽 */
        // const dMaterialsLength = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMaterialsLength, 0)); /* 材料长 */
        // const dMaterialsWidth = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMaterialsWidth, 0)); /* 材料宽 */

        /* 算材料开数 */
        // const mapMaterialsKQty = this.props.onResolveMachineComposing(dMachineLength, dMachineWidth, dMaterialsLength, dMaterialsWidth);
        // if (commonUtils.isNotEmptyObject(mapMaterialsKQty)) {
        //   const dMaterialsKQty = mapMaterialsKQty.totalNum;
        //   tableDataRow.dMaterialsKQty = dMaterialsKQty;
        // }

        /* 根据裁切方式、脊背方向、版式方向进行计算排版数 */
        if (dProductLength !== 0 && dProductWidth !== 0) {
          const dSinglePQty = props.onResolveSinglePQty(tableDataRow);
          if (commonUtils.isNotEmptyNumber(dSinglePQty)) {
            tableDataRow.dSinglePQty = dSinglePQty;
          }
        }
        /* 算拼版数 */
        // if (dProductLength !== 0 && dProductWidth !== 0) {
        //   const mapSinglePQty = this.props.onResolveMachineComposing(dProductLength, dProductWidth, dMachineLength, dMachineWidth);
        //   if (commonUtils.isNotEmptyObject(mapSinglePQty)) {
        //     const dSinglePQty = mapSinglePQty.totalNum;
        //     tableDataRow.dSinglePQty = dSinglePQty;
        //   }
        // }

        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;
              if (iIndex > -1) {
                packData[iIndex] = { ...packData[iIndex], ...addState };
                const { sId, sProductNo, dProductQty, dCombineQty, dFactProductQty, sCombinePartsName } = packData[iIndex];
                const tableCombineSelectedData = [];
                const jsonObj = {};
                jsonObj.sId = sId;
                jsonObj.sProductNo = sProductNo; /* 产品编号 */
                jsonObj.dCombineQty = commonUtils.isNotEmptyNumber(dCombineQty) ? dCombineQty : 0; /* 排版数 */
                jsonObj.dProductQty = commonUtils.isNotEmptyNumber(dProductQty) ? dProductQty : 0; /* 生产数 */
                jsonObj.dFactProductQty = commonUtils.isNotEmptyNumber(dFactProductQty) ? dFactProductQty : 0; /* 实际生产数 */
                jsonObj.sCombinePartsName = sCombinePartsName; /* 合版部件名称 */
                tableCombineSelectedData.push(jsonObj);
                const sCombinedMemo = commonUtils.isNotEmptyArr(tableCombineSelectedData)
                  ? JSON.stringify(tableCombineSelectedData)
                  : ""; /* JSON对象转换为字符串存放到合版信息中 */
                tableDataRow.sCombinedMemo = commonUtils.isNotEmptyObject(sCombinedMemo) ? sCombinedMemo : "合版信息";
              }
            }
          }
        } else {
          /* packData没数据时 */
          const packDataRow = handlePackDataAdd(slaveItem, 0, tableDataRow.sId, "add");
          packDataRow.dCombineQty = tableDataRow.dSinglePQty;
          packDataRow.dFactProductQty = commonUtils.isNull(slaveItem.dProductQty, 0); /* 排版数为1时，实际生产数 = 产品数 */
          if (tableDataRow.dSinglePQty > 0) {
            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);
          }
        }
      }
    } else if (sModelsType.includes("quotation/quotation")) {
      /* 计算材料开数 */
      // if (sFieldName === 'dMachineLength' || sFieldName === 'dMachineWidth' || sFieldName === 'dMaterialsLength' || sFieldName === 'dMaterialsWidth') {
      //   let dProductLength = 0; /* 产品长 */
      //   let dProductWidth = 0; /* 产品宽 */
      //   if (commonUtils.isNotEmptyArr(slaveData)) {
      //     dProductLength = !commonUtils.isEmpty(slaveData[0].sProductStyle) && slaveData[0].sProductStyle.split('*').length === 2 ? slaveData[0].sProductStyle.split('*')[0] : 0;
      //     dProductLength = commonUtils.convertStrToNumber(commonUtils.isNull(dProductLength, 0)); /* 产品长 */
      //     dProductLength = (typeof dProductLength === 'number' && !isNaN(dProductLength)) ? dProductLength : 0; /* 产品长 */
      //     dProductWidth = !commonUtils.isEmpty(slaveData[0].sProductStyle) && slaveData[0].sProductStyle.split('*').length === 2 ? slaveData[0].sProductStyle.split('*')[1] : 0;
      //     dProductWidth = commonUtils.convertStrToNumber(commonUtils.isNull(dProductWidth, 0)); /* 产品宽 */
      //     dProductWidth = (typeof dProductLength === 'number' && !isNaN(dProductLength)) ? dProductWidth : 0; /* 产品宽 */
      //   }
      //   const dMachineLength = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMachineLength, 0)); /* 上机长 */
      //   const dMachineWidth = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMachineWidth, 0)); /* 上机宽 */
      //   const dMaterialsLength = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMaterialsLength, 0)); /* 材料长 */
      //   const dMaterialsWidth = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMaterialsWidth, 0)); /* 材料宽 */
      //
      //   /* 算材料开数 */
      //   const mapMaterialsKQty = this.props.onResolveMachineComposing(dMachineLength, dMachineWidth, dMaterialsLength, dMaterialsWidth);
      //   if (commonUtils.isNotEmptyObject(mapMaterialsKQty)) {
      //     const dMaterialsKQty = mapMaterialsKQty.totalNum;
      //     tableDataRow.dMaterialsKQty = dMaterialsKQty;
      //   }
      //
      //   /* 算拼版数 */
      //   if (dProductLength !== 0 && dProductWidth !== 0) {
      //     const mapSinglePQty = this.props.onResolveMachineComposing(dProductLength, dProductWidth, dMachineLength, dMachineWidth);
      //     if (commonUtils.isNotEmptyObject(mapSinglePQty)) {
      //       const dSinglePQty = mapSinglePQty.totalNum;
      //       tableDataRow.dSinglePQty = dSinglePQty;
      //     }
      //   }
      // }
    }
    const materialsData = [];
    const processData = [];
    materialsDataOld.forEach(item => {
      const itemNew = { ...item };
      if (itemNew.sControlId === sId) {
        itemNew.sPartsName = tableDataRow.sPartsName;
      }
      materialsData.push(itemNew);
    });
    processDataOld.forEach(item => {
      const itemNew = { ...item };
      if (itemNew.sControlId === sId) {
        itemNew.sPartsName = tableDataRow.sPartsName;
      }
      processData.push(itemNew);
    });
    const materialsDataNew = sortData(tableData, materialsData);
    const processDataNew = sortData(tableData, processData);
    if (sFieldName === "sPartsName") {
      /* 部件名称与子部件同步 */
      const { sPartsName } = tableDataRow;
      const { treeSelectedKeys, treeData } = props;
      if (commonUtils.isNotEmptyArr(treeSelectedKeys)) {
        handleSearchNodes(treeSelectedKeys[0], treeData, sPartsName);
      }
    }
    const iIndex = tableData.findIndex(item => item.sId === sId);
    tableData[iIndex] = tableDataRow;
    props.onSaveState({ [`${name}Data`]: tableData, materialsData: materialsDataNew, processData: processDataNew, packData });
  } else if (name === "materials") {
    const { [`${name}Data`]: tableData, controlData, controlSelectedRowKeys, app, sModelsId } = props;
    const tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (tableDataRow === undefined) return;
    if (Object.keys(changeValue).length > 0 && Object.keys(changeValue).findIndex(item => item === "dMaterialsStockAuxiliaryQty") > -1) {
      const urlMaterialsStock = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
      const valueMaterialsStock = {
        sProName: "Sp_Inventory_MaterialsInventoryV56",
        paramsMap: {
          sMaterialsGuid: tableDataRow.sMaterialsId,
          sMaterialsStyle: tableDataRow.sMaterialsStyle,
          sWarehouseGuid: tableDataRow.sWarehouseId,
          sLocationalGuid: tableDataRow.sLocationId,
          sWarehouseLocationGuid: tableDataRow.sWarehouseLocationId,
          sDefine_no: tableDataRow.sDefineNo,
          sDefine_no2: tableDataRow.sDefineNo2,
          iGetQty: 1,
          iHasZero: 1,
        },
      };
      const returnDataMaterialsStock = (await commonServices.postValueService(app.token, valueMaterialsStock, urlMaterialsStock)).data;
      if (returnDataMaterialsStock.code === 1) {
        tableDataRow.dMaterialsStockAuxiliaryQty = returnDataMaterialsStock.dataset.rows[0].dataSet.outData[0].dAuxiliaryQty;
      }
    }
    if (Object.keys(changeValue).length > 0 && Object.keys(changeValue).findIndex(item => item === "dMaterialsStockAvailableQty") > -1) {
      const urlMaterialsAvailableQty = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
      const valueMaterialsAvailableQty = {
        sProName: "Sp_Inventory_MaterialsInventoryV56",
        paramsMap: {
          sMaterialsGuid: tableDataRow.sMaterialsId,
          sMaterialsStyle: tableDataRow.sMaterialsStyle,
          sWarehouseGuid: tableDataRow.sWarehouseId,
          sLocationalGuid: tableDataRow.sLocationId,
          sWarehouseLocationGuid: tableDataRow.sWarehouseLocationId,
          sDefine_no: tableDataRow.sDefineNo,
          sDefine_no2: tableDataRow.sDefineNo2,
          iGetQty: 2,
          iHasZero: 1,
        },
      };
      const returnDataMaterialsAvailableQty = (await commonServices.postValueService(app.token, valueMaterialsAvailableQty, urlMaterialsAvailableQty))
        .data;
      if (returnDataMaterialsAvailableQty.code === 1) {
        tableDataRow.dMaterialsStockAvailableQty = returnDataMaterialsAvailableQty.dataset.rows[0].dataSet.outData[0].dAuxiliaryQty;
      }
    }
    const iIndex = tableData.findIndex(item => item.sId === sId);
    if (iIndex > -1) {
      tableData[iIndex] = tableDataRow;
    }
    if (sFieldName === "sType") {
      if (tableData[iIndex].sType === "2") {
        tableData[iIndex].sControlId = "";
        tableData[iIndex].sPartsName = "";
      } else {
        const iControlIndex = commonUtils.isEmptyArr(controlSelectedRowKeys)
          ? -1
          : controlData.findIndex(item => item.sId === controlSelectedRowKeys[0]);
        if (iControlIndex > -1) {
          tableData[iIndex].sControlId = controlData[iControlIndex].sId;
          tableData[iIndex].sPartsName = controlData[iControlIndex].sPartsName;
        }
      }
    }
    props.onSaveState({ [`${name}Data`]: tableData });
  } else if (name === "materials0" || name === "materials1" || name === "materials2" || name === "materials0Child") {
    name = "materials";
    const { [`${name}Data`]: tableData, controlData, controlSelectedRowKeys, materials0Data, materials0SelectedRowKeys } = props;
    let oldRowMap = {};
    if (sFieldName === "sInkBOM") {
      const iOldIndex = tableData.findIndex(item => item.sId === sId);
      if (iOldIndex > -1) {
        const tableDataOldRow = JSON.parse(JSON.stringify(tableData[iOldIndex]));
        oldRowMap = {
          sInkBOMId: tableDataOldRow.sInkBOMId,
          sInkBOMsSlaveId: tableDataOldRow.sInkBOMsSlaveId,
          sInkBOMsMaterialsId: tableDataOldRow.sInkBOMsMaterialsId,
        };
      }
    }
    const tableDataRow = await props.onDataChange("materials", sFieldName, changeValue, sId, dropDownData, true);

    if (tableDataRow === undefined) return;
    tableDataRow.oldRowMap = oldRowMap;

    const iIndex = tableData.findIndex(item => item.sId === sId);
    if (iIndex > -1) {
      tableData[iIndex] = tableDataRow;
    }
    props.onSaveState({ [`${name}Data`]: tableData });
  } else if (name === "materialsChild") {
    /* 替代料 */
    name = "materials";
    const { [`${name}Data`]: tableData, controlData, controlSelectedRowKeys, materials0Data, materials0SelectedRowKeys } = 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 });
  } else if (name === "process") {
    const {
      [`${name}Data`]: tableData,
      sModelsId,
      masterData,
      slaveData,
      controlData,
      controlSelectedRowKeys,
      materialsData,
      processConfig,
      token,
    } = props;
    let { processDelData, materialsDelData } = props;
    const tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (tableDataRow === undefined) return;
    let iIndex = tableData.findIndex(item => item.sId === sId);
    let tableDataRowOld = {};
    let iMaterialsIndex = -1;
    let sControlId = "";
    if (iIndex > -1) {
      iMaterialsIndex = materialsData.findIndex(
        item => item.sControlId === tableData[iIndex].sControlId && item.sProcessId === tableData[iIndex].sProcessId
      );
      tableDataRowOld = tableData[iIndex];
      tableData[iIndex] = tableDataRow;
      sControlId = tableData[iIndex].sControlId;
    }
    const addState = {};
    if (sFieldName === "sProcessId" || sFieldName.includes("sProcessName")) {
      const bProcessAssort = 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].sProcessParam)) {
        tableData[iIndex].sProcessParamStr = "工艺参数";
      } else if (sProcessParamStriIndex > -1) {
        tableData[iIndex].sProcessParamStr = "";
      }
      /* 设置工艺参数下拉 */
      if (commonUtils.isNotEmptyObject(tableData[iIndex].sProcessParam)) {
        tableData[iIndex] = { ...tableData[iIndex], ...commonUtils.convertStrToObj(tableData[iIndex].sProcessParam) };
      }

      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 (iIndex > -1 && 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;
                }
                // const iSlaveIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys[0]);
                // if (iSlaveIndex > -1) {
                //   processRow.sSlaveId = slaveData[iSlaveIndex].sId;
                // }
                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;
                        }
                        // const iSlaveIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys[0]);
                        // if (iSlaveIndex > -1) {
                        //   processRow.sSlaveId = slaveData[iSlaveIndex].sId;
                        // }
                        tableData.push(processRow);
                      }
                    });
                }
              }
            }
          });
      }
      if (tableData[iIndex].sType === "3") {
        tableData[iIndex].sControlId = "";
        tableData[iIndex].sPartsName = "";
      } else if (iControlIndex > -1) {
        tableData[iIndex].sControlId = controlData[iControlIndex].sId;
        tableData[iIndex].sPartsName = controlData[iControlIndex].sPartsName;
        if (iMaterialsIndex > -1) {
          materialsData[iMaterialsIndex].sProcessId = tableData[iIndex].sProcessId;
          materialsData[iMaterialsIndex].sProcessTbId = tableData[iIndex].sId;
          materialsData[iMaterialsIndex].sMaterialsProcessName = tableData[iIndex].sProcessName;
        }
      }
    }
    props.onSaveState({ [`${name}Data`]: tableData, materialsSelectedRowKeys: [], ...addState });
  } else if (name === "pack") {
    const { packData, packSelectedRowKeys } = props;
    const tableDataRow = await props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
    if (tableDataRow === undefined) return;
    const iIndex = packData.findIndex(item => item.sId === sId);
    packData[iIndex] = tableDataRow;
    if (sFieldName === "dCombineQty" || sFieldName === "dProductQty") {
      handleGetdFactProductQty(packSelectedRowKeys, packData);
      props.onSaveState({ packData });
    }
  } else {
    props.onDataChange(name, sFieldName, changeValue, sId, dropDownData);
  }
};
const singlePQtyChange = tableDataRow => {
  const bZfZf = tableDataRow.iPrintMode === 2; // 正反版
  const bSample = tableDataRow.dSumPQty >= 4; // 样本
  tableDataRow.iPrintModePo = tableDataRow.iPrintMode <= 2 ? 2 : tableDataRow.iPrintMode === 3 ? 0 : -1;

  if (bSample) {
    if (tableDataRow.dSinglePQty > 0) {
      tableDataRow.dPlateQty = Math.ceil(tableDataRow.dSumPQty / tableDataRow.dSinglePQty);
    }

    if (bZfZf && tableDataRow.iPrintModePo === 2) {
      // 双面样本，正反
      if (tableDataRow.dPlateQty < 2) {
        // 不管建议放正自翻版了，点方式什么是什么
        tableDataRow.dPlateQty = 2;
        tableDataRow.iStick = Math.ceil(commonUtils.isNull(tableDataRow.dPlateQty, 0) / 2);
        tableDataRow.dSumPlateQty =
          tableDataRow.iStick *
          (commonUtils.isNull(tableDataRow.iPositiveColor, 0) +
            commonUtils.isNull(tableDataRow.iPositiveSpecialColor, 0) +
            commonUtils.isNull(tableDataRow.iOppositeColor, 0) +
            commonUtils.isNull(tableDataRow.iOppositeSpecialColor, 0));
      } else {
        if (tableDataRow.iPrintModePo !== 2) {
          // 单面样本
          tableDataRow.dPlateQty = Math.ceil((commonUtils.isNull(tableDataRow.dSumPQty, 0) * 0.5) / tableDataRow.dSinglePQty);
          tableDataRow.iStick = Math.ceil(tableDataRow.dPlateQty);
          tableDataRow.dSumPlateQty =
            tableDataRow.iStick * (commonUtils.isNull(tableDataRow.iPositiveColor, 0) + commonUtils.isNull(tableDataRow.iPositiveSpecialColor, 0));
        } else {
          tableDataRow.dPlateQty = Math.ceil(
            commonUtils.isNull(tableDataRow.dSumPQty, 0) / commonUtils.isNull(commonUtils.nullIf(tableDataRow.dSinglePQty, 0), 1)
          );
          tableDataRow.iStick = Math.ceil(tableDataRow.dPlateQty / 2);
        }
        tableDataRow.dSumPlateQty =
          tableDataRow.iStick *
          (commonUtils.isNull(tableDataRow.iPositiveColor, 0) +
            commonUtils.isNull(tableDataRow.iPositiveSpecialColor, 0) +
            commonUtils.isNull(tableDataRow.iOppositeColor, 0) +
            commonUtils.isNull(tableDataRow.iOppositeSpecialColor, 0));
      }
    } else {
      if (tableDataRow.iPrintModePo !== 2) {
        // 单面样本
        tableDataRow.dPlateQty = Math.ceil((commonUtils.isNull(tableDataRow.dSumPQty, 0) * 0.5) / tableDataRow.dSinglePQty);
      } else {
        tableDataRow.dPlateQty = Math.ceil(
          commonUtils.isNull(tableDataRow.dSumPQty, 0) / commonUtils.isNull(commonUtils.nullIf(tableDataRow.dSinglePQty, 0), 1)
        );
      }
      tableDataRow.iStick = Math.ceil(tableDataRow.dPlateQty);
      tableDataRow.dSumPlateQty =
        tableDataRow.iStick * (commonUtils.isNull(tableDataRow.iPositiveColor, 0) + commonUtils.isNull(tableDataRow.iPositiveSpecialColor, 0));
    }
    if (tableDataRow.iStick > 0 && tableDataRow.dSinglePQty > 0) {
      tableDataRow.dMachineQty = commonUtils.convertFixNum(
        (commonUtils.isNull(tableDataRow.dPartsQty, 0) * commonUtils.isNull(tableDataRow.dSumPQty, 0) * 0.5) /
          tableDataRow.dSinglePQty /
          tableDataRow.iStick,
        0
      );
      tableDataRow.dSumMachineQty = tableDataRow.dMachineQty * tableDataRow.iStick;
    }
  } else {
    tableDataRow.iStick = 1;
    tableDataRow.dSumPlateQty =
      tableDataRow.iStick *
      (commonUtils.isNull(tableDataRow.iPositiveColor, 0) +
        commonUtils.isNull(tableDataRow.iPositiveSpecialColor, 0) +
        commonUtils.isNull(tableDataRow.iOppositeColor, 0) +
        commonUtils.isNull(tableDataRow.iOppositeSpecialColor, 0));
    if (bZfZf && tableDataRow.iPrintModePo === 2) {
      tableDataRow.dPlateQty = 2;
      tableDataRow.dSumPlateQty =
        tableDataRow.iStick *
        (commonUtils.isNull(tableDataRow.iPositiveColor, 0) +
          commonUtils.isNull(tableDataRow.iPositiveSpecialColor, 0) +
          commonUtils.isNull(tableDataRow.iOppositeColor, 0) +
          commonUtils.isNull(tableDataRow.iOppositeSpecialColor, 0));
    } else {
      tableDataRow.dPlateQty = 1;
      tableDataRow.dSumPlateQty =
        tableDataRow.iStick * (commonUtils.isNull(tableDataRow.iPositiveColor, 0) + commonUtils.isNull(tableDataRow.iPositiveSpecialColor, 0));
    }

    if (tableDataRow.dSinglePQty > 0) {
      if (tableDataRow.iPage > 1) {
        // 笔记本  用 非样本 来做， 倍率是每页都一样才可以用      原先 /2 是指页数， 现在直接按张数
        tableDataRow.dMachineQty = commonUtils.convertFixNum((tableDataRow.dPartsQty * tableDataRow.iPage) / tableDataRow.dSinglePQty, 0);
      } else {
        tableDataRow.dMachineQty = commonUtils.convertFixNum(commonUtils.isNull(tableDataRow.dPartsQty, 0) / tableDataRow.dSinglePQty, 0);
        tableDataRow.dSumMachineQty = tableDataRow.dMachineQty * tableDataRow.iStick;
      }
    }
  }

  /* 计算材料开数 */
  // const dMachineLength = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMachineLength, 0)); /* 上机长 */
  // const dMachineWidth = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMachineWidth, 0)); /* 上机宽 */
  // const dMaterialsLength = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMaterialsLength, 0)); /* 材料长 */
  // const dMaterialsWidth = commonUtils.convertStrToNumber(commonUtils.isNull(tableDataRow.dMaterialsWidth, 0)); /* 材料宽 */
  // const sResult = this.props.onResolveMachineComposing(dMachineLength, dMachineWidth, dMaterialsLength, dMaterialsWidth);
  // if (commonUtils.isNotEmptyObject(sResult)) {
  //   const dMaterialsKQty = sResult.totalNum;
  //   tableDataRow.dMaterialsKQty = dMaterialsKQty;
  // }

  return tableDataRow;
};
const handlePackDataAdd = (item, index, sControlId, handleType) => {
  const tableDataRow = {};
  if (handleType === "add") {
    tableDataRow.sId = commonUtils.createSid();
    tableDataRow.handleType = "add";
    tableDataRow.sSlaveId = item.sId;
    tableDataRow.iOrder = item.iOrder;
  }
  tableDataRow.sParentId = item.sParentId;
  if (commonUtils.isNotEmptyObject(sControlId)) {
    tableDataRow.sControlId = sControlId;
  }
  // if (commonUtils.isNotEmptyObject(index)) {
  //   tableDataRow.iOrder = index + 1;
  // }
  tableDataRow.sProductId = item.sProductId; /* 产品id */
  tableDataRow.sCustomerId = item.sCustomerId; /* 客户id */
  tableDataRow.sCustomerName = item.sCustomerName; /* 客户名称 */
  tableDataRow.sProductName = item.sProductName; /* 产品名称 */
  tableDataRow.sProductNo = item.sProductNo; /* 产品编号 */
  /* 主表配置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 (bProductQtySelf) {
    tableDataRow.dProductQty = commonUtils.isNull(item.dProductQty, 0);
  } else {
    tableDataRow.dProductQty =
      commonUtils.isNull(item.dProductQty, 0) + commonUtils.isNull(item.dGiveQty, 0) + commonUtils.isNull(item.dStockupQty, 0); /* 生产数量 */
  }
  tableDataRow.sProductUnit = item.sProductUnit; /* 单位 */
  tableDataRow.sProductStyle = item.sProductStyle; /* 产品规格 */
  return tableDataRow;
};
const QuotationAllMaster = baseProps => {
  const props = masterEvent(baseProps);
  if (!props) {
    return null; // 或者加载状态组件
  }
  if (props && !props.masterConfig) {
    return null;
  }

  return <QuotationAllprogressDetail {...props} onDataChange={handleTableChange} onButtonClick={handleButtonClick} />;
};
export default QuotationAllMaster;
