/* eslint-disable */
import { useRef, useEffect, useState, useCallback, useMemo } from "react";
import { Toast, Input, Tabs, Selector, Grid, Image, Button, Checkbox, Switch, Dialog, Radio, Space, CenterPopup, ImageViewer, Collapse, CapsuleTabs } from "antd-mobile";
import { AddOutline, MinusOutline, EditFill, CloseOutline } from "antd-mobile-icons";
import commonConfig from "@/utils/config";
import * as commonServices from "@/services/services";
import * as commonFunc from "@/components/Common/commonFunc";
import * as commonBusiness from "@/components/Common/commonBusiness";
import styles from "./quotationDetail.less";
import SelectInput from "../components/SelectInput";
import * as commonUtils from "@/utils/utils";
import Typesetting from "@/components/Common/Typesetting/typesetting";
import DynamicSVG from "@/components/Common/BoxDesignCompontent/svg";
import ShowImgM from "@/components/Common/BoxShowImgMaterial/indexNew";
import CommonBase from "@/components/Common/CommonBase";
import { cloneDeep, isEqual } from "lodash";
import moment from "moment";
import { transform } from "@antv/g2/lib/util/transform";
const QuickQuoteEvent = props => {
  const { location, selectedNode, sModelsId } = props;
  // const selectedNode = JSON.parse(location.state).quotationData;
  const addState = {};

  addState.onGetFilterState = (state, bInit) => {
    const result = Object.keys(state).reduce((pre, cur) => {
      if (cur.endsWith("Column") || cur.endsWith("Config") || ["formData", "treeData", "downAbleConfigs", "finishedConfigs"].includes(cur)) {
        return pre;
      }

      pre[cur] = state[cur];
      return pre;
    }, {});

    const { slaveData = [], manyData = [], masterData = {} } = result;
    const materialInfoFields = [
      "sMaterialsName",
      "sMaterialsNo",
      "sMaterialsId",
      "sAuxiliaryUnit",
      "sMaterialsUnit",
      "bReel",
      "dCoefficient",
      "bInverse",
      "sMaterialsStyle",
      "sComputeId",
      "sReComputeId",
      "dGramWeight",
      "sReConversionComputeId",
      "sConversionComputeId",
      "sMaterialsType",
      "bComMaterials",
      "dWlcd",
      "dWlkd",
    ];
    const slaveDataNew = bInit
      ? slaveData.map(item => {
        const { materialsInfo = [], sMaterialsName } = item;
        if (!materialsInfo.length && sMaterialsName) {
          return {
            ...item,
            materialsInfo: [
              materialInfoFields.reduce((pre, cur) => {
                pre[cur] = item[cur];
                return pre;
              }, {}),
            ],
          };
        } else {
          return item;
        }
      })
      : slaveData;

    const manyDataNew = manyData.map(item => {
      delete item.manyData;
      return item;
    });

    const { sType, sCustomerId, sCustomerName } = props.app.userinfo;
    const bCustomer = sType === "Customer";
    if (bCustomer && !masterData.sCustomerId) {
      masterData.sCustomerName = sCustomerName;
      masterData.sCustomerId = sCustomerId;
    }
    return { ...result, masterData, slaveData: slaveDataNew, manyData: manyDataNew };
  };

  const sQuoConfig = commonUtils.convertStrToObj(props.masterData?.sQuoConfig, {});

  const [state, setState] = useState(addState.onGetFilterState(sQuoConfig, true));

  const { formData = [], masterConfig } = state;
  const { bLinkFieledClick } = props;
  const [hideBackBtn, setHideBackBtn] = useState(false);
  const [enabled, setEnabled] = useState(props.enabled);

  useEffect(() => {
    setHideBackBtn(!bLinkFieledClick);
    setEnabled(!bLinkFieledClick || props.enabled);
  }, [bLinkFieledClick, props.enabled]);
  useEffect(() => {
    // 获取 masterConfig
    const { masterConfig, token } = props;
    const quickQuoteConfig = masterConfig?.gdsconfigformslave.find(item => item.sControlName === "BtnQuickQuote") || {};
    const { sActiveId } = quickQuoteConfig;
    const configUrls = `${commonConfig.server_host}business/getModelBysId/${sActiveId}?sModelsId=${sActiveId}`;
    commonServices.getService(props.app.token, configUrls).then(async ({ data: configReturn }) => {
      if (configReturn.code === 1) {
        const formData = configReturn.dataset.rows[0].formData;
        setState(pre => ({ ...pre, formData, selectedNode, masterConfig: formData[0] }));
      }
    });
  }, []);
  // 获取盒型定义配置
  useEffect(() => {
    if (!formData.length) return '';
    const sBoxActiveId = formData.find(item => item.sGrd === "slave")?.gdsconfigformslave?.find(item => item.sName === "sName")?.sActiveId;
    if (!sBoxActiveId) return '';
    const { token } = props;
    const configUrl = `${commonConfig.server_host}business/getModelBysId/${sBoxActiveId}?sModelsId=${sBoxActiveId}`;
    commonServices.getService(token, configUrl).then(({ data: configReturn }) => {
      if (configReturn.code === 1) {
        const formData = configReturn.dataset.rows[0].formData;
        setState(pre => ({ ...pre, boxConfig: formData[0] }));
      }
    });
  }, [formData.length]);

  // 获取column
  useEffect(() => {
    if (!formData.length) return '';

    let result = {};
    for (let i = 0; i < formData.length; i++) {
      const tableConfig = formData[i];
      const { sGrd } = tableConfig;
      if (!sGrd) continue;
      const column = commonFunc.getHeaderConfig(tableConfig);
      result = {
        ...result,
        [`${sGrd}Column`]: column,
        [`${sGrd}Config`]: tableConfig,
      };
    }
    setState(pre => ({ ...pre, ...result }));
  }, [formData.length]);
  const { slaveData = [], masterData = {} } = state;
  useEffect(() => {
    if (!slaveData.length) return;
    const bNotInit = slaveData.some(item => item.sBackProcessData);
    if (!bNotInit) {
      const { downAbleConfigs = [] } = state;
      const downAbleConfigsNew = downAbleConfigs.filter(item => item.sDefaultProcessId);
      if (downAbleConfigsNew.length) {
        const slaveDataNew = slaveData.map(item => {
          let sBackProcessData = [];
          downAbleConfigsNew.forEach(({ sChineseDropDown: sChineseDropDownStr, sDefaultProcessId, sName, sId }) => {
            const sChineseDropDown = commonUtils.convertStrToObj(sChineseDropDownStr, []);
            const defaultProcess = sChineseDropDown.find(item => item.sId === sDefaultProcessId);
            const name = `slaveDown${item.sBoxModel}`;
            const sFieldName = sName;
            const changeValue = { [sFieldName]: defaultProcess.sId };
            const dropDownData = sChineseDropDown.map(item => ({
              ...item,
              sProductClassifyId: sId,
            }));
            const slaveDataReturn = onDataChange(name, sFieldName, changeValue, item.sId, dropDownData, true);
            sBackProcessData = [...sBackProcessData, ...(slaveDataReturn?.sBackProcessData?.filter(item => item.sProductClassifyId === sId) || [])];
          });
          return {
            ...item,
            sBackProcessData,
          };
        });
        setState(pre => {
          return { ...pre, slaveData: slaveDataNew };
        });
      }
    }

    const bNotInit1 = !!masterData.cpProcessName;
    if (!bNotInit1) {
      const { finishedConfigs = [] } = state;
      const finishedConfigsNew = finishedConfigs.filter(item => item.sDefaultProcessId);
      if (finishedConfigsNew.length) {
        let [cpProcessNameList, productProcessInfo] = [[], []];
        finishedConfigsNew.forEach(({ sChineseDropDown: sChineseDropDownStr, sDefaultProcessId, sName, sId }) => {
          const sChineseDropDown = commonUtils.convertStrToObj(sChineseDropDownStr, []);
          const defaultProcess = sChineseDropDown.find(item => item.sId === sDefaultProcessId);
          const name = "finished";
          const sFieldName = sName;
          const changeValue = { [sFieldName]: defaultProcess.sId };
          const dropDownData = sChineseDropDown.map(item => ({
            ...item,
            sProductClassifyId: sId,
          }));
          const { cpProcessName: cpProcessNameNew, productProcessInfo: productProcessInfoNew } = onDataChange(
            name,
            sFieldName,
            changeValue,
            masterData.sId,
            dropDownData,
            true
          );
          cpProcessNameNew.split(",").forEach((item, index) => {
            if (!cpProcessNameList.includes(item)) {
              cpProcessNameList.push(item);
              productProcessInfo.push(productProcessInfoNew[index]);
            }
          });
        });
        setState(pre => ({
          ...pre,
          masterData: {
            ...masterData,
            cpProcessName: cpProcessNameList.join(","),
            productProcessInfo,
          },
        }));
      }
    }
  }, [slaveData.map(item => item.sId).toString()]);
  addState.onBackClick = () => {
    props.onSaveState({ masterData: { ...props.masterData, sQuoConfig: JSON.stringify(addState.onGetFilterState(state)) }, quickQuoteModel: false });
  };

  const onDataChange = (name, sFieldName, changeValue, sId, dropDownData, isWait) => {
    const { masterData = {}, slaveData = [], selectedNode = {}, manyData = [] } = state;
    const extraState = {
      calcPriceFinished: false,
    };

    if (name === "master") {

      const { showName: sTreeNodeName } = selectedNode || {};
      const masterDataNew = { ...masterData, ...changeValue };
      masterDataNew.handleType = masterDataNew.handleType || "update";
      masterDataNew.sId = masterDataNew.sId || commonUtils.createSid();

      if (sFieldName === "dProductQty") {
        setState(pre => ({
          ...pre,
          dProductQty: changeValue.dProductQty,
        }));
      }
      if (sFieldName === "dLength" || sFieldName === "dWidth" || sFieldName === "dHeight") {
        if (sTreeNodeName) {
          if (props.currentBoxModel) {
            const boxModel = props.currentBoxModel.replace("slaveUp", "").replace("slaveDown", "");
            const iIndex = slaveData.findIndex(item => item.sTreeNodeName === sTreeNodeName && item.sBoxModel === boxModel);
            const sColumnNameConfig = commonUtils.convertStrToObj(slaveData[iIndex].sColumnNameConfig, []).map(item => ({
              ...item,
              iColValue: item.iColValue || 6,
            }));
            slaveData[iIndex] = {
              ...slaveData[iIndex],
              upAbleConfigsExtra: sColumnNameConfig,
            };
          } else {
            if (!slaveData[0]) return;
            const sColumnNameConfig = commonUtils.convertStrToObj(slaveData[0].sColumnNameConfig, []).map(item => ({
              ...item,
              iColValue: item.iColValue || 6,
            }));
            slaveData[0] = {
              ...slaveData[0],
              upAbleConfigsExtra: sColumnNameConfig,
            };
          }
        } else {
          masterDataNew[sFieldName] = changeValue[sFieldName];
        }
        if (masterData?.sMReserve3) {
          const result1 = masterData?.sMReserve3.split('(')[0];
          masterDataNew.sMReserve3 = `${result1}(${masterDataNew.dLength}*${masterDataNew.dWidth}*${masterDataNew.dHeight})`;
        }
        const num = Number(changeValue[sFieldName])
        if (Number.isNaN(num)) {
          masterDataNew[sFieldName] = null
        }
      }

      setState(pre => ({ ...pre, masterData: masterDataNew, ...extraState }));
    } else if (name.includes("slave")) {

      const boxModel = name.replace("slaveUp", "").replace("slaveDown", "");

      if (sFieldName === "sName") {
        let upAbleConfigsList = []

        if (!changeValue.sName) return;
        const dropDownDataSelected = dropDownData.find(item => item.sName === changeValue.sName);
        const { sColumnNameConfig, sColumnNameConfigExclusion, sColumnNameConfigPic } = dropDownDataSelected;
        const upAbleConfigsExtra = commonUtils.convertStrToObj(sColumnNameConfig, []).map(item => ({
          ...item,
          iColValue: item.iColValue || 6,
        }));
        const defaultData = commonFunc.getDefaultData({ gdsconfigformslave: upAbleConfigsExtra });
        delete defaultData.sId;
        delete dropDownDataSelected.sId;
        upAbleConfigsExtra?.forEach(item => {
          if (item.sTypes && item.sTypes.includes('09')) {
            const list = ['iSLength', 'iSWidth', 'iCLength', 'iCWidth']
            const nameList = ['层1长', '层1宽', '层2长', '层2宽']
            for (let index = 0; index < 4; index++) {
              upAbleConfigsList.push({
                ...item,
                sName: item.sName + list[index],
                sDefault: item[list[index]],
                showName: item.showName + nameList[index]
              })
            }
          } else {
            upAbleConfigsList.push(item)
          }
        })
        changeValue = {
          ...changeValue,
          ...defaultData,
          ...dropDownDataSelected,
          upAbleConfigsExtra,
          ...upAbleConfigsList.reduce((acc, item) => {
            acc[item.sName] = item.sDefault;
            return acc;
          }, {}),
          calcMethodData: commonUtils.convertStrToObj(sColumnNameConfigExclusion, []),
          boxPicData: commonUtils.convertStrToObj(sColumnNameConfigPic, []),
        };
      }

      const { selectedNode = {}, slaveConfig } = state;
      const { showName: sTreeNodeName } = selectedNode;


      if (sFieldName === "dSumPQty" && (sTreeNodeName.includes("骑马") || sTreeNodeName.includes("锁线"))) {
        changeValue.dSumPQty = Number(changeValue.dSumPQty);
        if (changeValue.dSumPQty !== 0) {
          if (!changeValue.dSumPQty || changeValue.dSumPQty % 4 !== 0) {
            Toast.show({
              content: "P数要为4的倍数",
            });
            changeValue.dSumPQty = 4;
            extraState.slaveUpKey = `key_${commonUtils.createSid()}`;
          }
        }

      }
      const iIndex = slaveData.findIndex(item => item.sTreeNodeName === sTreeNodeName && item.sBoxModel === boxModel);
      if (name.includes("slaveDown")) {

        let dropDownDataSelected = dropDownData.find(item => item.sId === changeValue[sFieldName] || item.sId === changeValue.value);
        // dropDownDataSelected.sProductClassifyId = dropDownDataSelected.sProductClassifyId ? dropDownDataSelected.sProductClassifyId : dropDownDataSelected.sId
        const extraRowData = {};
        if (dropDownDataSelected !== undefined) {
          dropDownDataSelected[sFieldName] = dropDownDataSelected.sProcessName;
          // 后道参数额外配置
          const { sParamConfig: sParamConfigStr } = dropDownDataSelected || {};
          const sParamConfig = commonUtils.convertStrToObj(sParamConfigStr, []);
          extraState.backendParamsConfig = sParamConfig;
          extraState.backendConfig = { sParentFieldsName: sFieldName, sBoxModel: boxModel, typeName: 'slave', dropDownDataSelected };
          const sBackendParams = sParamConfig
            .map(item => {
              const { sParamDefault, sParam, sFieldName, iOrder } = item;
              return !sParamDefault
                ? ""
                : {
                  sId: commonUtils.createSid(),
                  value: sParamDefault,
                  sParam: sParam,
                  [`sParam${iOrder}`]: sParamDefault,
                  ...(sFieldName ? { [sFieldName]: sParamDefault } : {}),
                  sParamKey: sFieldName || `sParam${iOrder}`,
                };
            })
            .filter(item => item !== "");
          dropDownDataSelected.sBackendParams = sBackendParams;
        }
        if (iIndex === -1) {
          slaveData.push({
            sId: commonUtils.createSid(),
            handleType: "add",
            sBoxModel: boxModel,
            sTreeNodeName,
            sBackProcessData: dropDownDataSelected === undefined ? [] : [dropDownDataSelected],
            ...extraRowData,
          });
        } else {

          const sBackProcessData = slaveData[iIndex].sBackProcessData || [];
          const iIndex1 = sBackProcessData.findIndex(item => item.sProductClassifyId === changeValue.sProductClassifyId);
          if (iIndex1 === -1) {
            dropDownDataSelected !== undefined && sBackProcessData.push(dropDownDataSelected);
          } else {
            if (dropDownDataSelected === undefined) {
              sBackProcessData.splice(iIndex1, 1);
            } else {
              sBackProcessData[iIndex1] = dropDownDataSelected;
            }
          }
          slaveData[iIndex].sBackProcessData = sBackProcessData;

          slaveData[iIndex] = {
            ...slaveData[iIndex],
            ...extraRowData,
            handleType: slaveData[iIndex].handleType || "update",
          };
        }
      } else {
        if (iIndex === -1) {
          slaveData.push({
            ...commonFunc.getDefaultData(slaveConfig, { tree: selectedNode }),
            ...changeValue,
            sId: commonUtils.createSid(),
            handleType: "add",
            sBoxModel: boxModel,
            sTreeNodeName,
          });
        } else {
          slaveData[iIndex] = {
            ...(sFieldName === "sName"
              ? {
                sId: slaveData[iIndex].sId,
                sBoxModel: boxModel,
                sTreeNodeName,
                ...commonFunc.getDefaultData(slaveConfig, { tree: selectedNode }),
                sBackProcessData: slaveData[iIndex].sBackProcessData,
              }
              : slaveData[iIndex]),
            ...changeValue,
            handleType: slaveData[iIndex].handleType || "update",
          };

        }
      }
      const saveIndex = slaveData.findIndex(item => item.sTreeNodeName === selectedNode.showName && item.sBoxModel === boxModel);
      const materialStyleLength = slaveData[saveIndex].materialLength || 0;
      const materialStyleWidth = slaveData[saveIndex].materialWidth || 0;


      slaveData[saveIndex] = {
        ...slaveData[saveIndex],
        sMachineStyle: materialStyleLength + "*" + materialStyleWidth,
        dMachineQty: masterData.sBillNo && slaveData[saveIndex].dMachineQty ? slaveData[saveIndex].dMachineQty : slaveData[saveIndex].dProductQty ? slaveData[saveIndex].dProductQty : masterData.dProductQty,
      };

      if (sFieldName === "dWlcd" || sFieldName === "dWlkd") {
        const horizontalBoxes = Math.floor(slaveData[saveIndex]?.dWlkd / Number(slaveData[saveIndex]?.dMachineWidth));
        const verticalBoxes = Math.floor(slaveData[saveIndex]?.dWlcd / Number(slaveData[saveIndex]?.dMachineLength));
        const newDMaterialsKQty = horizontalBoxes * verticalBoxes;
        slaveData[saveIndex] = {
          ...slaveData[saveIndex],
          dMachineQty: masterData.sBillNo && slaveData[saveIndex].dMachineQty ? slaveData[saveIndex].dMachineQty : Math.floor(slaveData[saveIndex].dMachineQty / slaveData[saveIndex].dSinglePQty),
          dMaterialsKQty: newDMaterialsKQty,
          newMaterialLength: sFieldName === "dWlcd" ? changeValue[sFieldName] : slaveData[saveIndex]?.dWlcd,
          newMaterialWidth: sFieldName === "dWlkd" ? changeValue[sFieldName] : slaveData[saveIndex]?.dWlkd,
          materialLength: sFieldName === "dWlcd" ? changeValue[sFieldName] : slaveData[saveIndex]?.dWlcd,
          materialWidth: sFieldName === "dWlkd" ? changeValue[sFieldName] : slaveData[saveIndex]?.dWlkd,
          sMaterialsStyle: `${sFieldName === "dWlcd" ? changeValue[sFieldName] : slaveData[saveIndex]?.dWlcd || 0}*${sFieldName === "dWlkd" ? changeValue[sFieldName] : slaveData[saveIndex]?.dWlkd || 0}`,
        };
      }

      if (sFieldName === "sName") {
        slaveData[saveIndex] = {
          ...slaveData[saveIndex],
          dMaxLength: Number(selectedNode.sMachineStyle.split("*")[0]),
          dMaxWidth: Number(selectedNode.sMachineStyle.split("*")[1]),
        };
      }

      if (sFieldName === "bFlap") {
        slaveData[saveIndex] = {
          ...slaveData[saveIndex],
          bFold: false,
          sFold: "",
          dFold: "",
          dAdhesive: "",
        };
      }
      if (sFieldName === "bFold") {
        slaveData[saveIndex] = {
          ...slaveData[saveIndex],
          bFlap: false,
          dFlap: "",
        };
      }
      if (sFieldName === "iPrintModePo") {
        slaveData[saveIndex] = {
          ...slaveData[saveIndex],
          iPrintModePo: Number(changeValue.value),
        };
      }

      const { upAbleConfigsExtra = [] } = slaveData[saveIndex] || {};

      upAbleConfigsExtra.forEach(item => {
        if (item.sName === sFieldName) {
          item.sAssignFormula = null;
        }
      });

      if (isWait) {
        return slaveData.find(item => item.sBoxModel === boxModel);
      }

      setState(pre => ({ ...pre, slaveData, ...extraState }));
    } else if (name === "finished") {
      const { productProcessInfo = [] } = masterData;
      const dropDownDataSelected = dropDownData.find(item => item.sId === changeValue[sFieldName] || item.sId === changeValue.value);
      if (dropDownDataSelected !== undefined) {
        dropDownDataSelected[sFieldName] = dropDownDataSelected.sProcessName;
        // 后道参数额外配置
        const { sParamConfig: sParamConfigStr } = dropDownDataSelected || {};
        const sParamConfig = commonUtils.convertStrToObj(sParamConfigStr, []);
        extraState.backendParamsConfig = sParamConfig;
        extraState.backendConfig = { sParentFieldsName: sFieldName, typeName: 'finished', dropDownDataSelected };
        const sBackendParams = sParamConfig
          .map(item => {
            const { sParamDefault, sParam, sFieldName, iOrder } = item;
            return !sParamDefault
              ? ""
              : {
                sId: commonUtils.createSid(),
                value: sParamDefault,
                sParam: sParam,
                [`sParam${iOrder}`]: sParamDefault,
                ...(sFieldName ? { [sFieldName]: sParamDefault } : {}),
                sParamKey: sFieldName || `sParam${iOrder}`,
              };
          })
          .filter(item => item !== "");
        dropDownDataSelected.sBackendParams = sBackendParams;
      }

      const iIndex = productProcessInfo.findIndex(item => item.sProductClassifyId === dropDownData[0].sProductClassifyId);
      if (iIndex === -1) {
        dropDownDataSelected !== undefined && productProcessInfo.push(dropDownDataSelected);
      } else {
        if (dropDownDataSelected === undefined) {
          productProcessInfo.splice(iIndex, 1);
        } else {
          productProcessInfo[iIndex] = dropDownDataSelected;
        }
      }
      const cpProcessName = productProcessInfo.map(item => item.sProcessName).join(",");
      const masterDataNew = { ...masterData, cpProcessName, productProcessInfo };
      masterDataNew.handleType = masterDataNew.handleType || "update";
      masterDataNew.sId = masterDataNew.sId || commonUtils.createSid();
      if (isWait) {
        return masterDataNew;
      }
      setState(pre => ({ ...pre, masterData: masterDataNew, ...extraState }));
    }

  };
  addState.onDataChange = onDataChange;
  addState.onGetAllDelData = () => {
    const {
      slaveData = [],
      slaveDelData: slaveDelDataOld = [],
      controlData = [],
      controlDelData: controlDelDataOld = [],
      materialsData = [],
      materialsDelData: materialsDelDataOld = [],
      processData = [],
      processDelData: processDelDataOld = [],
      manyqtysData = [],
      manyqtysDelData: manyqtysDelDataOld = [],
      colorData = [],
      colorDelData: colorDelDataOld = [],
      packData = [],
      packDelData: packDelDataOld = [],
    } = props;

    const addState = {
      slaveDelData: [
        ...slaveDelDataOld,
        ...slaveData.filter(item => !slaveDelDataOld.map(item1 => item1.sId).includes(item.sId)).map(item => ({ ...item, handleType: "del" })),
      ],
      controlDelData: [
        ...controlDelDataOld,
        ...controlData.filter(item => !controlDelDataOld.map(item1 => item1.sId).includes(item.sId)).map(item => ({ ...item, handleType: "del" })),
      ],
      materialsDelData: [
        ...materialsDelDataOld,
        ...materialsData
          .filter(item => !materialsDelDataOld.map(item1 => item1.sId).includes(item.sId))
          .map(item => ({ ...item, handleType: "del" })),
      ],
      processDelData: [
        ...processDelDataOld,
        ...processData.filter(item => !processDelDataOld.map(item1 => item1.sId).includes(item.sId)).map(item => ({ ...item, handleType: "del" })),
      ],
      manyqtysDelData: [
        ...manyqtysDelDataOld,
        ...manyqtysData.filter(item => !manyqtysDelDataOld.map(item1 => item1.sId).includes(item.sId)).map(item => ({ ...item, handleType: "del" })),
      ],
      colorDelData: [
        ...colorDelDataOld,
        ...colorData.filter(item => !colorDelDataOld.map(item1 => item1.sId).includes(item.sId)).map(item => ({ ...item, handleType: "del" })),
      ],
      packDelData: [
        ...packDelDataOld,
        ...packData.filter(item => !packDelDataOld.map(item1 => item1.sId).includes(item.sId)).map(item => ({ ...item, handleType: "del" })),
      ],
    };

    return addState;
  };
  // 判断单据是否被删除
  const bDataDeleted = async () => {
    const { masterConfig, currentId, masterData = {}, slaveConfig } = props;
    if (!masterData.sBillNo) return false;
    const sId = currentId || masterData.sId || "";
    const returnData = await props.handleGetDataOne({
      name: "master",
      configData: masterConfig,
      condition: { sId, pageSize: "", pageNum: "" },
      bEditClick: false,
      slaveConfig,
      isWait: true,
    });

    if (returnData) return false;
    Toast.show({
      content: "当前报价单已被删除！请重新核价以生成新的报价单！"
    });
    props.onAdd();
    setState(pre => ({
      ...pre,
      // manyData: [],
      calcPriceFinished: false,
    }));
    return true;
  };
  addState.bDataDeleted = bDataDeleted;

  // 存草稿
  const onSaveDraft = (nextState = state, nextProps = props) => {
    const { masterData = {} } = nextState;
    const { sProductName, sProductNo, sCustomerName, sCustomerId, sCustomerNo } = masterData;
    if (!sProductName || !sCustomerName) {
      // message.info("请先填写客户名称和产品名称");
      Toast.show({
        content: "请先填写客户名称和产品名称",
      });
      return;
    }
    props.onSaveState(
      {
        ...addState.onGetAllDelData(),
        masterData: { ...nextProps.masterData, sQuoConfig: JSON.stringify(addState.onGetFilterState(nextState)) },
        slaveData: nextProps.slaveData.map(item => {
          return {
            ...item,
            sProductName: sProductName,
            sProductNo: sProductNo,
            sCustomerName: sCustomerName,
            sCustomerId: sCustomerId,
            sCustomerNo: sCustomerNo,
            handleType: "add",
          };
        }),
        isDraftSaved: true,
        controlData: nextProps.controlData.map(item => {
          return {
            ...item,
            // sPartsName: sProductName,
            handleType: "add",
          };
        }),
        materialsData: nextProps.materialsData?.map(item => {
          return {
            ...item,
            handleType: "add",
          };
        }),
        processData: nextProps.processData?.map(item => {
          return {
            ...item,
            handleType: "add",
          };
        }),
        manyqtysData: nextProps.manyqtysData?.map(item => {
          return {
            ...item,
            handleType: "add",
          };
        }),
        colorData: nextProps.colorData?.map(item => {
          return {
            ...item,
            handleType: "add",
          };
        }),
        packData: nextProps.packData?.map(item => {
          return {
            ...item,
            handleType: "add",
          };
        }),
        loading: true,
        isSaveDraft: true,
      },
      newState => {
        if (newState) {
          props.onButtonClick("BtnDraft", { ...props, ...newState });

          // setTimeout(() => {
          //   setIsDraftSaved(true);
          // }, 500);
        }
      }
    );
  };

  addState.onSaveDraft = onSaveDraft;
  // 获取国际化名称
  const getI18nName = (sFieldName, sDefault) => {
    return commonFunc.showMessage(props.app?.commonConst, sFieldName) || sDefault;
  };
  // 核价按钮
  addState.handleCalcPrice = async () => {
    if (props.app.webSocket === null || props.app.webSocket?.readyState !== WebSocket.OPEN) {
      console.log("================webSocket连接======================");
      props.dispatch({
        type: "app/createWebSocket",
        payload: { reStart: true, dispatch: props.dispatch },
      });

      // 暂停2秒
      await new Promise(resolve => setTimeout(resolve, 2000));
    }

    // const { masterData = {}, slaveData = [], selectedNode = {}, extraParts = {} } = state;
    // const selectProduct = commonFunc.showLocalMessage(props, "selectProduct", "请先选择产品");
    // const selectCustomer = commonFunc.showLocalMessage(props, "selectCustomer", "请先选择客户名称");
    // const selectProductUnit = commonFunc.showLocalMessage(props, "selectProductUnit", "请先输入产品单位");
    // const inputLength = commonFunc.showLocalMessage(props, "inputLength", "请先输入长度");
    // const inputWidth = commonFunc.showLocalMessage(props, "inputWidth", "请先输入宽度");
    // const inputQty = commonFunc.showLocalMessage(props, "inputQty", "请先输入数量");
    // if (commonUtils.isEmptyObject(selectedNode)) {
    //   // message.error("请先选择产品");
    //   Toast.show({
    //     icon: "fail",
    //     content: selectProduct,
    //   });
    //   return;
    // }
    const {
      masterConfig,
      masterData = {},
      slaveConfig,
      slaveData = [],
      selectedNode = {},
      extraParts = {},
      downAbleConfigs = [],
      downAbleExtraConfigs = [],
      finishedConfigs = [],
    } = state;
    const selectProduct = commonFunc.showLocalMessage(props, "selectProduct", "请先选择产品");
    if (commonUtils.isEmptyObject(selectedNode)) {
      Toast.show({
        icon: "fail",
        content: selectProduct,
      });
      return;
    }

    const errMsgList = [];
    const masterConfigMust = masterConfig?.gdsconfigformslave.filter(item => item.bVisible && item.bNotEmpty);
    if (!masterConfigMust) return;
    const checkResult = masterConfigMust.filter(item => !masterData[item.sName]);
    if (checkResult.length) {
      errMsgList.push(
        checkResult.map(item => <span>【{item.showName}】</span>),
        <span>{getI18nName("isNotNull")}</span>,
        <br />
      );
    }
    // const mustFieldsMap = {
    //   sCustomerName: selectCustomer,
    //   sProductName: selectCustomer,
    //   sProductUnit: selectProductUnit,
    //   dLength: inputLength,
    //   dWidth: inputWidth,
    //   dProductQty: inputQty,
    // };

    // const checkResult = Object.keys(mustFieldsMap).find(item => masterData[item] === undefined);
    // if (checkResult) {
    //   Toast.show({
    //     icon: "fail",
    //     content: mustFieldsMap[checkResult],
    //   });
    //   return;
    // }

    const { bBox, showName, sId } = selectedNode;
    let { sAllPartsName } = selectedNode;
    if (!sAllPartsName) {
      sAllPartsName = showName;
    }
    const slaveConfigMust = slaveConfig.gdsconfigformslave
      .filter(item => item.bVisible && item.iTag && item.bNotEmpty && item.sName !== "sMaterialsName")
      .filter(item => (bBox ? true : item.sName !== "sName"));

    const sMaterialsNameConfig = slaveConfig.gdsconfigformslave.find(item => item.sName === "sMaterialsName");
    const downAbleConfigMust = [...downAbleConfigs, ...downAbleExtraConfigs].filter(item => item.bNotEmpty);

    const errorList = [];
    const partsList = [];
    slaveData.forEach(slaveRowData => {
      const list = slaveConfigMust.filter(item => !slaveRowData[item.sName]);
      if (!slaveRowData.materialsInfo || slaveRowData.materialsInfo.some(item => !item.sMaterialsName)) {
        list.push(sMaterialsNameConfig);
      }
      const { sBackProcessData = [] } = slaveRowData;
      downAbleConfigMust.forEach(item => {
        if (!sBackProcessData.some(x => x.sProductClassifyId === item.sId)) {
          list.push(item);
        }
      });
      errorList.push(list);
      partsList.push(slaveRowData.sBoxModel);
    });

    if (!errorList.some(item => !item.length)) {
      errMsgList.push(
        errorList.map((item, index0) => [
          <span>{partsList[index0]}:</span>,
          ...item.map(config => <span>【{config.showName}】</span>),
          <span>{getI18nName("isNotNull")}</span>,
          <br />,
        ])
      );
    }

    const finishedConfigMust = finishedConfigs.filter(item => item.bNotEmpty);
    const { productProcessInfo = [] } = masterData;

    const checkResult1 = finishedConfigMust.filter(item => !productProcessInfo.some(x => x.sProductClassifyId === item.sId));
    if (checkResult1.length) {
      errMsgList.push(
        checkResult1.map(item => <span>【{item.showName}】</span>),
        <span>{getI18nName("isNotNull")}</span>,
        <br />
      );
    }

    if (errMsgList.length) {
      // message.error(errMsgList, 3);
      Toast.show({
        icon: "fail",
        content: errMsgList,
      });
      return;
    }

    setState(pre => ({ ...pre, calcPriceLoading: true, calcPriceFinished: false }));
    const { sModelsId, token, sBoxModel } = props;
    const extraPartsList = extraParts?.[showName] || [];

    const sAllPartsNameList = [...sAllPartsName.split(","), ...extraPartsList];

    const masterDataNew = {
      ...masterData,
      cpProcessName: masterData.cpProcessName || "",
      productProcessInfo: masterData.productProcessInfo?.map(item => ({ ...item, sProcessId: item.sId })) || [],
      sProductClassifyId: sId,
      sProductName1: masterData.sProductName,
      dProductWidth: masterData.dWidth,
      dProductLength: masterData.dLength,
      dProductHeight: masterData.dHeight,
      sProductStyle:
        masterData.dHeight !== undefined
          ? `${masterData.dLength}*${masterData.dWidth}*${masterData.dHeight}`
          : `${masterData.dLength}*${masterData.dWidth}`,
    };

    const paramMap = {
      bQuotation: true,
      ...masterDataNew,
      product: masterDataNew,
      sPartsStyle: "",
      partsInfo: sAllPartsNameList
        .map(partName => {
          const temp = {
            ...slaveData.find(item => item.sTreeNodeName === showName && item.sBoxModel === partName),
          };
          return temp;
        })
        .filter(item => commonUtils.isNotEmptyObject(item) && item.materialsInfo && item.materialsInfo.length)
        .map(item => {
          return {
            ...Object.keys(item).reduce((pre, cur) => {
              if (typeof item[cur] !== "object") {
                pre[cur] = item[cur];
              }
              return pre;
            }, {}),
            iOrder: 1,
            dPartsQty: masterData.dProductQty,
            // iPositiveColor: Number(item.sColor),
            iOppositeColor: item.sBackProcessData?.find(item => item.bPrintParams)?.iPositiveColor || 0,
            iOppositeSpecialColor: item.sBackProcessData?.find(item => item.bPrintParams)?.iPositiveSpecialColor || 0,
            sPartsName: item.sBoxModel,
            materialsInfo: item.materialsInfo?.filter(x => commonUtils.isNotEmptyObject(x)),
            processInfo:
              item.sBackProcessData?.map(item => ({
                ...item,
                sProcessId: item.sProcessId || item.sId,
              })) || [],
          };
        }),
    };

    const firstPart = paramMap.partsInfo && paramMap.partsInfo[0];
    paramMap.sPartsStyle =
      ((firstPart && firstPart.dPartsLength) || 0) + "*" + ((firstPart && firstPart.dPartsWidth) || 0);
    if (paramMap.sPartsStyle === "0*0") {
      delete paramMap.sPartsStyle;
    }
    // 先用好的数据模拟后面在调整
    // const newParamMap = JsonData;
    const url = `${commonConfig.server_host}calculationStd/countMoney?sModelsId=${sModelsId}`;
    const dataReturn = (await commonServices.postValueService(token, paramMap, url)).data;

    if (dataReturn.code === 1) {
      // const { app, sModelsId } = props;
      // const { slaveConfig, masterData: masterData1, processConfig, materialsConfig } = state;

      const { slaveConfig, masterData: masterData1, materialsConfig, processConfig, sModelsId, app } = props;
      const { productClassify, partsNewInfo = [], productProcessInfo, partsInfo: partsOldInfo } = dataReturn.dataset.rows[0];

      const slaveData = [];
      const controlData = [];
      const materialsData = [];
      let processData = [];
      let tableDataRow = {};
      for (const item of slaveConfig.gdsconfigformslave) {
        tableDataRow[item.sName] = masterData[item.sName];
      }
      tableDataRow.sId = commonUtils.createSid();
      tableDataRow.handleType = "add";
      tableDataRow.iOrder = 1;
      tableDataRow.sParentId = masterData.sId;
      // const productIdDropDown = commonUtils.getStoreDropDownData(sModelsId, 'slave', 'sProductName');
      let productIdDropDown;
      const slaveIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === "sProductName");
      if (slaveIndex > -1) {
        const sqlDropDownData = await props.getSqlDropDownData(sModelsId, "slave", slaveConfig.gdsconfigformslave[slaveIndex], tableDataRow);
        productIdDropDown = sqlDropDownData.dropDownData;
      }
      const iProductIdIndex = commonUtils.isEmptyArr(productIdDropDown)
        ? -1
        : productIdDropDown.findIndex(item => item.sId === tableDataRow.sProductId);
      if (iProductIdIndex === -1) {
        tableDataRow.sProductId = tableDataRow.sProductName;
        const tableDataRowNew = { ...tableDataRow, ...masterDataNew };
        const extraProps = {
          sProductId: tableDataRowNew.sProductName,
          sProductName: tableDataRowNew.sProductName,
          sProductStyle: tableDataRowNew.sProductStyle,
          sProductUnit: tableDataRowNew.sProductUnit,
          sProductNo: tableDataRowNew.sProductNo,
          sCustomerProductNo: tableDataRowNew.sCustomerProductNo,
          sProductClassifyId: tableDataRowNew.sProductClassifyId,
          sProductClassifyName: tableDataRowNew.sProductClassifyName,
        };
        tableDataRow = { ...tableDataRow, ...extraProps };
        tableDataRow.sProductInfo = JSON.stringify(extraProps);
      } else {
        tableDataRow.sProductInfo = "";
      }
      slaveData.push(tableDataRow);
      const sInfoArr = [];
      let errorFlag = false;
      if (!commonUtils.isEmptyArr(partsOldInfo)) {
        partsOldInfo.forEach(item => {
          if (commonUtils.isNotEmptyObject(item) && !commonUtils.isEmpty(item.errorFlag)) {
            errorFlag = true;
            // props.getServiceError({ msg: `${item.sPartsName}  ${item.errorFlag}` });
            Toast.show({
              content: `${item.sPartsName}  ${item.errorFlag}`,
            });
          }
        });
      }
      if (errorFlag) {
        setState(pre => ({ ...pre, calcPriceLoading: false }));
        return;
      }

      // 返回数据赋值
      const { slaveData: stateSlaveData = [] } = state;
      const { bCalculatingArea } = selectedNode;
      partsNewInfo.forEach(item => {
        const slaveRowData = stateSlaveData.find(row => item.sTreeNodeName === row.sTreeNodeName && item.sBoxModel === row.sBoxModel);
        slaveRowData.dMachineQty = item.dMachineQty;
        slaveRowData.dAuxiliaryQty = item.materialsInfo?.[0]?.dAuxiliaryQty;
        slaveRowData.sPrint = item.sProcessName;
        if (bCalculatingArea) {
          // todo 核价成功后 判断bSpecialRules 为false 就要给材料长材料款赋值
          slaveRowData.dWlcd = item.dMaterialsLength;
          slaveRowData.dWlkd = item.dMaterialsWidth;
        }
        setState(pre => ({ ...pre, slaveData: stateSlaveData }));
      });

      if (props.app.userinfo.sType === "sysadmin") {
        /* 超级管理员，弹窗显示接口返回的sInfo  */
        partsNewInfo.forEach(item => {
          const { sPartsName, sInfo } = item;
          const sInfoObj = {};
          sInfoObj.sPartsName = sPartsName;
          sInfoObj.sInfo = sInfo;
          sInfoArr.push(sInfoObj);
        });
      }

      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 = 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 newCopyTo = {};
      newCopyTo.master = masterData;
      newCopyTo.slave = commonUtils.isEmptyArr(slaveData) ? {} : slaveData[0];
      for (let i = 0; i < partsNewInfo.length; i++) {
        const partInfo = partsNewInfo[i];
        const iIndex = i;
        const partsDataRow = {};
        for (const child of Object.keys(partInfo)) {
          partsDataRow[child] = partInfo[child];
        }
        partsDataRow.handleType = "add";
        partsDataRow.iOrder = iIndex + 1; /* 快速下单编号从1开始 */
        partsDataRow.sId = commonUtils.createSid();
        partsDataRow.sParentId = masterData.sId;
        // partsDataRow.sSlaveId = ' ';
        if (partsDataRow.iPrintMode !== 3) {
          partsDataRow.iOppositeColor = partsDataRow.iPositiveColor;
        }
        delete partsDataRow.dMaterialsKQty;
        // delete partsDataRow.dMaterialsLength;
        // delete partsDataRow.dMaterialsWidth;
        // if (productClassify.bSpecialRules) {
        //   partsDataRow.dMachineLength = partsDataRow.dMaxMachineLength;
        //   partsDataRow.dMachineWidth = partsDataRow.dMaxMachineWidth;
        // }

        controlData.push(partsDataRow);
        // 材料信息
        for (let i = 0; i < partInfo.materialsInfo.length; i++) {
          const materialInfo = partInfo.materialsInfo[i];
          const iOrder = i;
          let materialDataRow = {};
          for (const item of materialsConfig.gdsconfigformslave) {
            materialDataRow[item.sName] = materialInfo[item.sName];
          }
          materialDataRow.handleType = "add";
          materialDataRow.sType = "0";
          materialDataRow.iPartOrder = iIndex;
          materialDataRow.iOrder = iOrder + 1;
          materialDataRow.sPartsName = partsDataRow.sPartsName;
          materialDataRow.sId = commonUtils.createSid();
          materialDataRow.sParentId = masterData.sId;
          materialDataRow.sControlId = partsDataRow.sId;
          // materialDataRow.sSlaveId = ' ';
          materialDataRow.dMaterialsKQty = partsDataRow.iNumberofMaterial;
          const models = "Materials";
          materialDataRow = await props.onMaterialsChange(materialDataRow, sModelsId, masterData, [], "dAuxiliaryQty", app, token, models);
          materialDataRow = commonBusiness.getCalculateAllMoney(app, models, "dAuxiliaryQty", masterData, materialDataRow);
          materialsData.push(materialDataRow);
        }

        // 工序信息
        let processPrintDataRow = {};
        processPrintDataRow.handleType = "add";
        processPrintDataRow.sProcessId = partInfo.sProcessId;
        const iProcessPrintIndex = dropDownDataProcessName.findIndex(item => item.sId === processPrintDataRow.sProcessId);
        if (iProcessPrintIndex > -1) {
          processPrintDataRow = {
            ...processPrintDataRow,
            ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iProcessPrintIndex], newCopyTo),
          }; // 取赋值字段
        }
        processPrintDataRow.sType = partInfo.sType;
        processPrintDataRow.iPartOrder = iIndex;
        processPrintDataRow.iOrder = 1;
        processPrintDataRow.sProcessName = partInfo.sProcessName;
        processPrintDataRow.sPartsName = partsDataRow.sPartsName;
        processPrintDataRow.dProcessInQty = partInfo.dProcessInQty;
        processPrintDataRow.dLossQty = partInfo.dLossQty;
        processPrintDataRow.dProcessOutQty = partInfo.dProcessOutQty;
        processPrintDataRow.sId = commonUtils.createSid();
        processPrintDataRow.sParentId = masterData.sId;
        processPrintDataRow.sControlId = partsDataRow.sId;
        const iSpecialColor = partInfo.iSpecialColor !== undefined ? partInfo.iSpecialColor : partInfo.partInfoiSpecialColor;
        processPrintDataRow.sColorSerialMemo = JSON.stringify([{ sId: partInfo.sColorId, sName: partInfo.sColor, dColor: partInfo.iColor, iSpecialColor }]);

        // processPrintDataRow.sSlaveId = ' ';
        processData.push(processPrintDataRow);
        // 配套工序
        if (bProcessAssort) {
          returnProcessAssort
            .filter(item => item.sParentId === processPrintDataRow.sProcessId)
            .forEach(itemProcessAssort => {
              const iIndex = dropDownDataProcessName.findIndex(item => item.sId === itemProcessAssort.sProcessId);
              const iProcessIndex = -1;
              const iNewProcessIndex = processData.findIndex(
                item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === partsDataRow.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.sControlId = partsDataRow.sId;
                processRow.sPartsName = partsDataRow.sPartsName;
                processRow.sType = dropDownDataProcessName[iIndex].sType;
                // processRow.sSlaveId = ' ';
                processData.push(processRow);
              }
            });
        }

        partInfo.processInfo.forEach((process, iOrder) => {
          let processAfterDataRow = {};
          for (const item of processConfig.gdsconfigformslave) {
            processAfterDataRow[item.sName] = process[item.sName];
          }
          for (const child of Object.keys(process)) {
            processAfterDataRow[child] = process[child];
          }
          processAfterDataRow.handleType = "add";
          processAfterDataRow.sProcessId = process.sProcessId;
          const iProcessAfterIndex = dropDownDataProcessName.findIndex(item => item.sId === processAfterDataRow.sProcessId);
          if (iProcessAfterIndex > -1) {
            processAfterDataRow = {
              ...processAfterDataRow,
              ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iProcessAfterIndex], newCopyTo),
            }; // 取赋值字段
          }
          processAfterDataRow.sType = process.sType;
          processAfterDataRow.iPartOrder = iIndex;
          processAfterDataRow.iOrder = iOrder + 1;
          processAfterDataRow.sPartsName = partsDataRow.sPartsName;
          processAfterDataRow.sId = commonUtils.createSid();
          processAfterDataRow.sParentId = masterData.sId;
          processAfterDataRow.sControlId = partsDataRow.sId;

          const sBackendParams = process.sBackendParams || [];
          if (sBackendParams.length) {
            const sQuoParams = sBackendParams.map(item => ({
              sParamKey: item.sParamKey,
              sParamName: item.sParam,
              sParamValue: item.value !== undefined ? item.value : "",
              bSelfCbx: !(item.value === "" || item.value === undefined),
            }));
            processAfterDataRow.sQuoParams = JSON.stringify(sQuoParams);
          }
          if (process.sColor) {
            processAfterDataRow.sColorSerialMemo = JSON.stringify([{ sId: process.sColorId, sName: process.sColor, dColor: process.iColor }]);
          }
          // processAfterDataRow.sSlaveId = ' ';
          processData.push(processAfterDataRow);
          // 配套工序
          if (bProcessAssort) {
            returnProcessAssort
              .filter(item => item.sParentId === processPrintDataRow.sProcessId)
              .forEach(itemProcessAssort => {
                const iIndex = dropDownDataProcessName.findIndex(item => item.sId === itemProcessAssort.sProcessId);
                const iProcessIndex = -1;
                const iNewProcessIndex = processData.findIndex(
                  item => item.sProcessId === itemProcessAssort.sProcessId && item.sControlId === partsDataRow.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.sControlId = partsDataRow.sId;
                  processRow.sPartsName = partsDataRow.sPartsName;
                  processRow.sType = dropDownDataProcessName[iIndex].sType;
                  // processRow.sSlaveId = ' ';
                  processData.push(processRow);
                }
              });
          }
        });
      }
      productProcessInfo.forEach((process, iOrder) => {
        let processProductDataRow = {};
        for (const item of processConfig.gdsconfigformslave) {
          processProductDataRow[item.sName] = process[item.sName];
        }
        for (const child of Object.keys(process)) {
          processProductDataRow[child] = process[child];
        }
        const iProductProcessIndex = dropDownDataProcessName.findIndex(item => item.sId === processProductDataRow.sProcessId);
        if (iProductProcessIndex > -1) {
          processProductDataRow = {
            ...processProductDataRow,
            ...commonFunc.getAssignFieldValue(processAssignAssort, dropDownDataProcessName[iProductProcessIndex], newCopyTo),
          }; // 取赋值字段
        }
        processProductDataRow.handleType = "add";
        processProductDataRow.sType = "3";
        processProductDataRow.sPartsName = "";
        processProductDataRow.iPartOrder = 999;
        processProductDataRow.iOrder = iOrder + 1;
        processProductDataRow.sId = commonUtils.createSid();
        processProductDataRow.sParentId = masterData.sId;

        const sBackendParams = process.sBackendParams || [];
        if (sBackendParams.length) {
          const sQuoParams = sBackendParams.map(item => ({
            sParamKey: item.sParamKey,
            sParamName: item.sParam,
            sParamValue: item.value !== undefined ? item.value : "",
            bSelfCbx: !(item.value === "" || item.value === undefined),
          }));
          processProductDataRow.sQuoParams = JSON.stringify(sQuoParams);
        }

        // processProductDataRow.sSlaveId = ' ';
        processData.push(processProductDataRow);
        // 配套工序
        if (bProcessAssort) {
          returnProcessAssort
            .filter(item => item.sParentId === processProductDataRow.sProcessId)
            .forEach(itemProcessAssort => {
              const iIndex = dropDownDataProcessName.findIndex(item => item.sId === itemProcessAssort.sProcessId);
              const iProcessIndex = -1;
              const iNewProcessIndex = processData.findIndex(item => item.sProcessId === itemProcessAssort.sProcessId);
              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;
                // processRow.sSlaveId = ' ';
                processData.push(processRow);
              }
            });
        }
      });
      processData = props.sortData(controlData, processData);
      const addState = { controlSelectedRowKeys: ["0000000"] };
      if (!commonUtils.isEmptyArr(slaveData)) {
        addState.slaveSelectedRowKeys = [slaveData[0].sId];
      }
      const { sPrintConfig = {}, downAbleConfigs = [], finishedConfigs = [] } = state;
      const processConfigs = [sPrintConfig, ...downAbleConfigs, ...finishedConfigs];

      const configOrderMap = {};
      processConfigs.forEach((config, index) => {
        configOrderMap[config.sId] = index;
      });

      processData.sort((a, b) => {
        return configOrderMap[a.sProcessClassifyId] - configOrderMap[b.sProcessClassifyId];
      });
      processData = processData.map((item, index) => ({ ...item, iOrder: index + 1 }));

      const newState = {
        materialsConfig,
        masterData: { ...masterData1, ...masterData },
        slaveData,
        controlData,
        materialsData,
        processData,
        fastOrderModalVisible: false,
        quotationAllprogress: 0,
        materialsSelectedRowKeys: [],
        ...addState,
        sInfoArr,
        // bVisiblesInfo: !!commonUtils.isNotEmptyArr(sInfoArr),
        Loading: false,
        dQuickQuoteProductQty: state?.dQuickQuoteProductQty
        // quickQuoteModel: false,
      };

      delete newState.masterData.sQuoConfig;

      setState(pre => ({
        ...pre,
        newNextProps: {
          dQuickQuoteProductQty: state.dQuickQuoteProductQty,
          ...props,
          ...newState,
          // manyqtysConfig: state.manyConfig,
          // manyqtysData: state.manyData,
        },
      }));

      const result = await props.handleCalculation(
        false,
        { ...props, ...newState, manyqtysConfig: state.manyConfig, manyqtysData: state.manyData, manyqtysDelData: state.manyData, state },
        true,
        { ...props, state }
      );
      if (commonUtils.isEmptyObject(result)) {
        setState(pre => ({ ...pre, calcPriceLoading: false }));
        return;
      }
      let hasCalled = false;
      const { manyqtysData = [] } = result;
      result.manyqtysData = manyqtysData.map(item => ({
        ...item,
        sParentId: newState.masterData.sId,
      }));
      setState(pre => {
        const preNew = {
          ...pre,
          manyData: result.manyqtysData,
          calcPriceLoading: false,
          calcPriceFinished: true,
        };

        const stateNew = { ...newState, ...result };

        if (hasCalled) return preNew; // 防止重复执行
        hasCalled = true;

        props.onSaveState(stateNew, () => {
          onSaveDraft(preNew, stateNew);
        });

        return preNew;
      });
    } else {
      // message.error(dataReturn.erroMsg || dataReturn.msg);
      Toast.show({
        icon: "fail",
        content: dataReturn.erroMsg || dataReturn.msg,
      });
      setState(pre => ({ ...pre, calcPriceLoading: false }));
    }
  };

  // 新报价
  addState.onAdd = () => {
    const restList = ["formData", "manyColumn", "manyConfig", "masterConfig", "slaveConfig", "slaveColumn", "treeData"];
    const stateNew = {
      ...restList.reduce((pre, cur) => {
        pre[cur] = state[cur];
        return pre;
      }, {}),
      masterData: {},
      slaveData: [],
      manyData: [],
    };
    setState(stateNew);
    props.onAdd();
  };

  // 选择盒型弹窗
  addState.onFieldPopupModal = (showConfig, name) => {
    if (showConfig.sName === "sName") {
      props.onSaveState({ boxModelSelectedModalVisible: true, currentBoxModel: name });
    }
  };


  return {
    ...props,
    onDataChange0: props.onDataChange,
    ...addState,
    hideBackBtn,
    enabled,
    state,
    setState,
  };
};
// 入口
const QuotationAllprogressDetail = baseProps => {
  const props = QuickQuoteEvent(baseProps);
  const { selectedNode, quotationData, app, sModelsId, masterData, state } = props;
  const { slaveConfig, slaveData = [] } = state
  const { showName, sUnit } = quotationData;
  const timeRef = useRef(0);
  useEffect(() => {

    if (!selectedNode.sId || commonUtils.isEmptyObject(slaveConfig)) return '';
    timeRef.current += 1;
    const getDropDownData = async props => {
      const showDownConfig = slaveConfig?.gdsconfigformslave.find(item => item.sControlName === "BtnDownConfig");
      const downAbleConfigs = await getSqlDropDownData({ ...showDownConfig });
      props.setState(pre => {
        const { slaveData = [], slaveConfig } = pre;
        const addState = {};
        const defaultData = commonFunc.getDefaultData(slaveConfig, { tree: selectedNode });
        const slaveDataNew = slaveData.filter(item => item.sTreeNodeName === selectedNode.showName);
        if (!slaveDataNew.length) {
          const sAllPartsName = selectedNode.sAllPartsName || selectedNode.showName;
          sAllPartsName?.split(",").forEach((item, index) => {
            const tempData = {
              sId: commonUtils.createSid(),
              handleType: "add",
              ...defaultData,
              sBoxModel: item,
              sTreeNodeName: selectedNode.showName,
            };
            if (selectedNode.sTypeKey === "huace") {
              if (index !== 0) {
                delete tempData.dSumPQty;
              } else {
                tempData.dSumPQty = 4;
              }
            }
            slaveDataNew.push(tempData);
          });
          addState.slaveData = slaveDataNew;
        }
        if (timeRef.current > 1) {
          addState.slaveData = slaveDataNew;
          addState.extraParts = {};
        }
        let sQuoConfigData = {}
        if (props?.sQuoData) {
          const sQuoConfig = commonUtils.convertStrToObj(props.masterData?.sQuoConfig, {});
          sQuoConfigData = props.onGetFilterState(sQuoConfig, true)
          sQuoConfigData = {
            ...sQuoConfigData,
            masterData: { ...sQuoConfigData?.masterData, handleType: masterData?.handleType, sBillNo: masterData?.sBillNo },
            slaveData: sQuoConfigData?.slaveData?.map((item, i) => {
              return {
                ...item,
                sId: props?.slaveData[i] ? sQuoConfigData?.slaveData[i]?.sId : item.sId
              }
            })
          }
        } else {
          sQuoConfigData = {
            masterData: {
              ...masterData,
              sProductName: showName, sProductUnit: sUnit,
            }
          }
        }

        return {
          ...pre,
          ...addState,
          downAbleConfigs: downAbleConfigs
            .filter(item => item.sType === "2")
            .map((item, index) => ({
              ...item,
              sName: `sParams${index}`,
              iColValue: item.iColValue || 4,
              sVisColumnName: "sProcessName",
            })),
          finishedConfigs: downAbleConfigs
            .filter(item => item.sType === "3")
            .map((item, index) => ({
              ...item,
              sName: `sParams${index}`,
              iColValue: item.iColValue || 4,
              sVisColumnName: "sProcessName",
            })),
          ...sQuoConfigData,
          // masterData: { sProductName: showName, sProductUnit: sUnit, handleType: masterData?.handleType, sBillNo: masterData?.sBillNo },

        };
      });

    };
    if (selectedNode.sTypeKey === "juantong") {
      props.onSaveState({
        masterData: { ...props.masterData, sFormId: "101251240115016002356125200" },
      });
    } else {
      props.onSaveState({
        masterData: { ...props.masterData, sFormId: "101251240115016076506222050" },
      });
    }
    getDropDownData(props);
  }, [selectedNode.sId, commonUtils.isEmptyObject(slaveConfig)]);

  const getSqlDropDownData = async ({ sId }) => {
    const url = `${commonConfig.server_host}business/getSelectLimit/${sId}`;
    const body = {
      sSqlCondition: {
        sProductClassifyId: selectedNode.sId,
      },
      sKeyUpFilterName: "",
      pageNum: 1,
      pageSize: 20,
    };
    const retrunData = await commonServices.postValueService(props.app.token, body, url);
    const sColumnNameConfigStr = retrunData.data?.dataset?.rows?.[0]?.sColumnNameConfig;
    // 取上机尺寸
    return commonUtils.convertStrToObj(sColumnNameConfigStr, []);
  };

  return (
    <div className={styles.quotationDetailBox}>
      <QuotationDetail {...props} />
    </div>
  );
};

const QuotationDetail = props => {
  const { masterConfig, masterData = {}, selectedNode = {} } = props.state;
  const { app } = props;
  if (!masterConfig) return "";
  const ableConfigs = masterConfig.gdsconfigformslave.filter(item => item.sName && item.bVisible);
  // 处理长宽样式
  const { sStripType = 0 } = selectedNode;
  const viewConfigs = Number(sStripType) === 0 ? ableConfigs : ableConfigs.filter(x => x.sName !== "dHeight");
  const lengthData = viewConfigs.find(x => x.sName === "dLength");
  if (Number(sStripType) === 0) {
    viewConfigs.forEach(item => {
      if (item.sName === "dLength" || item.sName === "dWidth") {
        item.iColValue = 4;
      }
    });
  } else {
    viewConfigs.forEach(item => {
      item.iColValue = viewConfigs[0].iColValue;
    });
  }
  if (selectedNode && selectedNode.sTypeKey && selectedNode.sTypeKey !== "danye") {
    if (lengthData) {
      lengthData.showName = "高(D)";
      lengthData.sChinese = "高(D)";
      lengthData.sEnglish = "Height (D)";
      if (app.userinfo?.sLanguage === "sEnglish") {
        lengthData.showName = lengthData.sEnglish;
      }
    }
  } else {
    if (lengthData) {
      lengthData.showName = "长(L)";
      lengthData.sChinese = "长(L)";
      lengthData.sEnglish = "Length (L)";
      if (app.userinfo?.sLanguage === "sEnglish") {
        lengthData.showName = lengthData.sEnglish;
      }
    }
  }
  const viewProps = {
    ...props,
    viewConfigs: viewConfigs,
    tableConfig: masterConfig,
    iColValueView: 24,
    viewRow: { ...masterData, sProductClassifyId: selectedNode.sId },
    tableName: "master",
  };


  return (
    <div className={styles.quotationBody}>
      <div className={styles.boxTitle}>
        {selectedNode?.showName || selectedNode?.sProductName}
        <EditFill color="#BFBFBF" style={{ marginLeft: "16px" }} />
      </div>
      <div>
        <MasterComponent {...viewProps} />
      </div>
      <div>
        <QuotationTabs {...props} quotationData={selectedNode} />
      </div>
    </div>
  );
};
const MasterComponent = props => {
  const { viewConfigs, masterData } = props;
  const customer = viewConfigs?.find(x => x.sName === "sCustomerName") || {};
  const customerProps = {
    ...props,
    itemDetail: customer,
  };
  const product = viewConfigs?.find(x => x.sName === "sProductName") || {};
  const productProps = {
    ...props,
    itemDetail: product,
  };
  const dLength = viewConfigs?.find(x => x.sName === "dLength") || {};

  const dLengthProps = {
    ...props,
    itemDetail: dLength,
  };
  const dWidth = viewConfigs?.find(x => x.sName === "dWidth") || {};
  const dWidthProps = {
    ...props,
    itemDetail: dWidth,
  };
  const dHeight = viewConfigs?.find(x => x.sName === "dHeight") || {};
  const dHeightProps = {
    ...props,
    itemDetail: dHeight,
  };
  const dProductQty = viewConfigs?.find(x => x.sName === "dProductQty") || {};
  const dProductQtyProps = {
    ...props,
    itemDetail: dProductQty,
  };
  const sProductUnit = viewConfigs?.find(x => x.sName === "sProductUnit") || {};
  const sProductUnitProps = {
    ...props,
    itemDetail: sProductUnit,
  };
  const sDeliverName = viewConfigs?.find(x => x.sName === "sDeliverName") || {};
  const sDeliverNameProps = {
    ...props,
    itemDetail: sDeliverName,
  };
  const viewConfigsList = viewConfigs.filter(
    x => x.sName !== "sCustomerName" && x.sName !== "sProductName" && x.sName !== "dLength" && x.sName !== "dWidth" && x.sName !== "dHeight"
  );
  return (
    <div>
      <div className={styles.customer}>
        <div>{customerProps.itemDetail?.showName}</div>
        <SelectInput {...customerProps} />
      </div>
      <div className={styles.customer}>
        <div>{productProps.itemDetail?.showName}</div>
        <SelectInput {...productProps} />
      </div>
      <div className={styles.customer}>
        <div>
          尺寸 {dLength?.showName} * {dWidth?.showName} {dHeight?.showName ? "*" : ""} {dHeight?.showName}{" "}
        </div>
        <div className={styles.sizeBox}>
          <div className={styles.sizeItem}>
            <div style={{ width: "70%" }}>
              <SelectInput {...dLengthProps} bCanInput={true} />
            </div>
            <div style={{ width: "30%", textAlign: "center" }}>X</div>
          </div>
          <div className={styles.sizeItem}>
            <div style={{ width: "70%" }}>
              <SelectInput {...dWidthProps} bCanInput={true} />
            </div>{" "}
            {Object.keys(dHeight).length > 0 ? (
              <div style={{ width: "30%", textAlign: "center" }}>X</div>
            ) : (
              <div style={{ width: "30%", textAlign: "center" }}>mm</div>
            )}
          </div>
          {Object.keys(dHeight).length > 0 ? (
            <div className={styles.sizeItem}>
              <div style={{ width: "70%" }}>
                <SelectInput {...dHeightProps} bCanInput={true} />
              </div>
              <div style={{ width: "30%", textAlign: "center" }}>mm</div>
            </div>
          ) : (
            ""
          )}
        </div>
      </div>
      <div >
        <Grid columns={3} gap={8}>
          {viewConfigsList.map(item => {
            return (
              <Grid.Item>
                <div className={styles.customer}>
                  <div>{item.showName}</div>
                  <SelectInput {...props} itemDetail={item} />
                </div>
              </Grid.Item>
            );
          })}
        </Grid>
      </div>
    </div>
  );
};
const QuotationTabs = props => {
  const { state } = props;
  const { selectedNode, extraParts = {}, slaveData } = state;
  const [sAllPartsNameList, setSAllPartsNameList] = useState([]);
  const [activeKey, setActiveKey] = useState(sAllPartsNameList?.length ? sAllPartsNameList[0] : null);
  const [visible, setVisible] = useState(false);
  const [value, setValue] = useState("");
  const partsList = selectedNode?.sAllPartsName ? selectedNode?.sAllPartsName?.split(",") : [selectedNode?.showName];
  const { showName, sAllPartsNameDefault } = selectedNode;
  const extraPartsList = extraParts[showName] || [];
  useEffect(() => {
    let nameList = selectedNode?.sAllPartsName || ''
    if (nameList === '') {
      nameList = selectedNode?.showName
    }
    const list = nameList?.split(",")
    if (list && list.length) {
      const lists = [...list, ...extraPartsList];
      setSAllPartsNameList(lists)
      setTimeout(() => {
        setActiveKey(list[0])

      }, 200);
    }
  }, [selectedNode])
  useEffect(() => {
    // 更新父组件的状态
    props.setState(pre => ({ ...pre, boxModel: activeKey }));
  }, [activeKey]);

  const tabsProps = {
    ...props,
    boxModel: activeKey,
  };

  // 处理添加新标签的逻辑
  const handleAdd = () => {
    // 弹窗
    setVisible(true);
  };
  const manyqtysInfo = commonFunc.showLocalMessage(props, "manyqtysInfo", "多数量报价");

  return (
    <div>
      <div className={styles.tabsBox}>

        <div className={styles.tabsContainer}>
          <CapsuleTabs
            activeKey={activeKey}
            onChange={key => {
              setActiveKey(key);
            }}
          >
            {sAllPartsNameList?.length
              ? sAllPartsNameList.map((pane, index) => (
                <CapsuleTabs.Tab
                  key={pane}
                  title={
                    <div className={styles.tabTitle}>
                      <div className={styles.tabText}>{pane}</div>
                      {partsList.includes(pane) ? (
                        ""
                      ) : (
                        <CloseOutline
                          className={styles.closeIcon}
                          onClick={(e) => {
                            e.stopPropagation();
                            const newTabs = sAllPartsNameList.filter(panes => panes !== pane);
                            setSAllPartsNameList(newTabs);
                            const index1 = slaveData.findIndex(item => item.sBoxModel === pane && item.sTreeNodeName === selectedNode.showName);
                            if (index1 > -1) {
                              props.setState(pre => {
                                const newSlaveData = [...pre.slaveData];
                                newSlaveData.splice(index1, 1);
                                return {
                                  ...pre,
                                  slaveData: newSlaveData,
                                };
                              });
                            }
                            if (activeKey === pane) {
                              setActiveKey(newTabs[0] || null);
                            }
                          }}
                        />
                      )}
                    </div>
                  }
                  style={{
                    maxWidth: '150px',
                    minWidth: '150px',
                    flexShrink: 0,
                  }}
                >
                  {activeKey === pane && <BoxComponent {...tabsProps} paneKey={pane} />}
                </CapsuleTabs.Tab>
              ))
              : ""}
          </CapsuleTabs>
        </div>
        <FinishedProcessComponent  {...tabsProps}></FinishedProcessComponent>
        <div>
          <div className={styles.projectBtn}>
            <div className={styles.boxTitle} style={{ marginTop: "32px" }}>
              {manyqtysInfo}
              <EditFill color="#BFBFBF" style={{ marginLeft: "16px" }} />
            </div>
          </div>
          <ManyComponent {...props}></ManyComponent>
        </div>
        <Button
          className={styles.tabAddBtn}
          color="primary"
          fill="solid"
          size="small"
          style={{ width: "30px", height: "30px", display: "flex", justifyContent: "center", alignItems: "center", textAlign: "center" }}
          onClick={handleAdd} // 调用 handleAdd 方法
        >
          <AddOutline />
        </Button>
        <CenterPopup
          visible={visible}
        // onMaskClick={() => {
        //   setVisible(false);
        // }}
        >
          <div className={styles.addTabs}>
            <div>请输入新标签名称：</div>
            <Input
              placeholder="请输入内容"
              clearable
              value={value}
              onChange={val => {
                setValue(val);
              }}
            />
            <div className={styles.addTabsBtn}>
              <Button
                color="primary"
                fill="outline"
                size="small"
                style={{ marginRight: "16px" }}
                onClick={() => {
                  setValue("");
                  setVisible(false);
                }}
              >
                取消
              </Button>
              <Button
                color="primary"
                fill="solid"
                size="small"
                onClick={() => {
                  if (value === '') {
                    Toast.show({
                      content: "标签名称不能为空",
                    });
                    return
                  }
                  if ([...sAllPartsNameList, ...extraPartsList].includes(value)) {
                    Toast.show({
                      content: "标签名称已存在!",
                    });
                    return;
                  }
                  const newSAllPartsNameList = [...sAllPartsNameList, value]; // 创建一个新的数组，包含新增的元素
                  setSAllPartsNameList(newSAllPartsNameList); // 更新状态，触发组件重新渲染
                  setVisible(false);
                  setValue("");
                  extraPartsList.push(value);
                  props.setState(pre => ({
                    ...pre,
                    extraParts: {
                      ...pre.extraParts,
                      [showName]: extraPartsList,
                    },
                  }));
                  // props.setState(pre => {})
                }}
              >
                确认
              </Button>
            </div>
          </div>
        </CenterPopup>
      </div>
    </div>
  );
};

// 内容
const BoxComponent = props => {
  const { state, boxModel } = props;
  const {
    activeKey,
    slaveConfig,
    masterData,
    selectedNode,
    boxConfig,
    downAbleConfigs = [],
    downAbleExtraConfigs = [],
    finishedConfigs = [],
    slaveData,
  } = state || {};
  const slaveRowData = slaveData.find(item => item.sTreeNodeName === selectedNode.showName && item.sBoxModel === boxModel) || {};
  const { sBillNo } = slaveRowData;
  const { sModelsId } = props;
  const [selectList, setSelectList] = useState([]);
  const [boxTypeList, setBoxTypeList] = useState([]);
  const [searchValue, setSearchValue] = useState("");
  const [boxPopup, setBoxPopup] = useState(false);
  const [boxsList, setBoxsList] = useState([]);
  const [selected, setSelected] = useState(slaveRowData?.sBoxType);
  // 获取盒型信息
  useEffect(() => {
    const sId = "17428091410008594700322758474000";
    const { selectedNode } = props;
    const url = `${commonConfig.server_host}business/getSelectLimit/${sId}`;
    const body = {
      sSqlCondition: {
        sProductClassifyId: selectedNode.sId,
      },
      sKeyUpFilterName: "",
      pageNum: 1,
      pageSize: 1000,
    };

    commonServices.postValueService(props.app.token, body, url).then(res => {
      if (res.data.code === 1) {
        const list = res.data.dataset.rows.map(x => {
          return {
            ...x,
            label: x.sName,
            value: x.sId,
          };
        });
        const boxTypeLists = Array.from(
          new Set(
            list.map(item => {
              return {
                ...item,
                label: item.sBoxType,
                value: item.sBoxType,
              };
            })
          )
        );

        // 去重
        const uniqueArray = boxTypeLists.filter((item, index, self) => index === self.findIndex(i => i.sBoxType === item.sBoxType));
        setBoxTypeList(uniqueArray);
        setSelectList(list);
      }
    });
    // 获取盒型
  }, [sModelsId]);

  useEffect(() => {
    if (selectedNode.sTypeKey === "kapai" || selectedNode.sTypeKey === "juantong") {
      const { sBillNo } = slaveRowData;
      if (sBillNo) return;
      const getSqlDropDownData = async ({ sId, sSqlCondition = {} }, cb) => {
        const url = `${commonConfig.server_host}business/getSelectLimit/${sId}`;
        const body = {
          sKeyUpFilterName: "",
          pageNum: 1,
          pageSize: 1000,
          sSqlCondition,
        };
        const retrunData = await commonServices.postValueService(props.app.token, body, url);
        const dropDownData = retrunData.data?.dataset?.rows;
        if (dropDownData) {
          const box = dropDownData.find(box => box.sId === '17551384620004172929247856556500'); // Define 'box' here
          const boxData = dropDownData.map((itemBox, indexBox) => ({
            ...itemBox,
            iOrder: indexBox + 1,
          }));
          if (box) { // Check if 'box' exists before using it
            props.onDataChange("slaveUp" + boxModel, "sName", { sName: box.sName }, box.sId, boxData);
          }
        }

      };

      getSqlDropDownData({
        sId: '17428091410008594700322758474000',
        sSqlCondition: { sProductClassifyId: selectedNode.sId },
      });

    }
  }, [boxModel]);

  const { sColumnNameConfig } = slaveRowData || {};
  const upAbleConfigsExtra = commonUtils.convertStrToObj(sColumnNameConfig, []).map(item => ({
    ...item,
    sValue: item.sDefault,
    iColValue: item.iColValue || 6,
  }));
  const showUpAbleConfigsExtra = upAbleConfigsExtra.filter(x => x.bVisible === 1);
  let boxList = [];
  const { sStripType = 0 } = selectedNode;
  // if(!masterData) return
  if (
    (slaveRowData.sColumnNameConfig && masterData.dLength && masterData.dWidth && masterData.dHeight) ||
    (Number(sStripType) === 1 && slaveRowData.sColumnNameConfig && masterData.dLength && masterData.dWidth) ||
    slaveRowData.sName === "卡牌"
  ) {
    const slaveNewData = slaveRowData.upAbleConfigsExtra || JSON.parse(slaveRowData.sColumnNameConfig);
    const tables = [
      { name: "盒型类别", value: slaveRowData.sBoxType, type: null },
      { name: "盒身", value: slaveRowData.sBoxBody, type: slaveRowData.sTypes },
      { name: "盒长", value: slaveRowData.dL ? slaveRowData.dL : masterData.dLength ? Number(masterData.dLength) : 0, type: null },
      { name: "盒宽", value: slaveRowData.dW ? slaveRowData.dW : masterData.dWidth ? Number(masterData.dWidth) : 0, type: null },
      { name: "盒高", value: masterData.dHeight ? Number(masterData.dHeight) : 0, type: null },
    ];
    const titleList1 = [
      { name: "上方盒舌", value: "dSFHS" },
      { name: "盒底组件", value: "dHDC" },
      { name: "下方盒舌", value: "dXFHS" },
      { name: "左(上)插位组件", value: "dZSCW" },
      { name: "左贴边位", value: "dZTBW" },
      { name: "左(下)插位组件", value: "dZXCW" },
      { name: "右(上)插位组件", value: "dYSCW" },
      { name: "右贴边位", value: "dYTBW" },
      { name: "右(下)插位组件", value: "dYXCW" },
    ];
    const evaluateFormula = (formula, variables) => {
      if (!formula) return 0; // 如果公式为空，返回0
      try {
        // 提取公式中的变量名
        const variableNames = formula.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g) || [];
        // 构建函数参数
        const params = variableNames.join(",") + ",Math";
        // 替换公式中的变量为实际值
        const func = new Function(params, `return ${formula}`);
        // 提取变量值
        const args = variableNames.map(name => Number(variables[name]) || 0);
        // 执行函数并返回结果
        return func(...args, Math);
      } catch (error) {
        console.error("公式执行错误:", error);
        return 0;
      }
    };

    // 确认是竖向排列还是横向排列
    const L = masterData?.dLength || 0;
    const W = masterData?.dWidth || 0;
    const H = masterData?.dWidth || 0;
    const D = masterData?.dHeight || 0;
    const variables = {
      L,
      W,
      H,
      D,
      ...slaveRowData,
    };
    slaveNewData.forEach(x => {
      let key = 0;
      if (x.sAssignFormula) {
        key = evaluateFormula(x.sAssignFormula, variables);
        slaveRowData[x.sName] = key;
      } else {
        key = slaveRowData[x.sName];
      }

      boxList.push({
        value: key,
        sName: titleList1.find(item => item.value === x.sName)?.name || "",
        isEditable: true,
        isSelect: false,
        selectValue: null,
        selectLabel: "",
        selectImage: null,
        type: x.sTypes || null,
        show: true,
        showName: x.showName, // 参数名称
      });
    });
    tables.forEach(x => {
      boxList.push({
        value: x.value,
        sName: x.name,
        isEditable: true,
        isSelect: false,
        selectValue: null,
        selectLabel: "",
        selectImage: null,
        type: x.type || null,
        show: true,
        showName: x.name, // 参数名称
      });
    });
  }

  const svgProps = {
    ...props,
    boxList,
    dSvgBoxWidth: 125,
    dSvgBoxHeight: 125,
    showNew: 1,
    isMobile: true,
  };
  // 印刷参数
  const getUpViewPropsByITag = iTag => {
    if (!slaveConfig) return;

    const config = slaveConfig.gdsconfigformslave
      .filter(item => !["sPrint", "sColor", "iPrintModePo"].includes(item.sName))
      .filter(item => {
        if (item.sName === "dSumPQty" && selectedNode.sTypeKey !== "huace") {
          return false;
        }
        const { bAdvancedSetting, bFlap, bFold } = slaveRowData;
        const shouldExcludeItem = (condition, itemNameList) => !condition && itemNameList.includes(item.sName);
        if (selectedNode.showName === "封套") {
          slaveRowData.bFold = true;
        }
        if (
          shouldExcludeItem(bAdvancedSetting, ["dPortrait", "dHorizontal"]) ||
          shouldExcludeItem(bFlap, ["dFlap"]) ||
          shouldExcludeItem(bFold, ["sFold", "dAdhesive", "dFold"])
        ) {
          return false;
        }
        if (Number(selectedNode.iRateType) === 0 && item.sName === "iPage") {
          return false;
        } else {
          if (item.sName === "iPage") {
            const rateList = JSON.parse(slaveConfig.gdsconfigformslave.find(x => x.sName === "iRateType")?.showDropDown) || [];
            item.showName = rateList[Number(selectedNode.iRateType)] || "倍率";
          }
        }

        if (item.sName === "dWlcd" && selectedNode.sTypeKey === "juantong") {
          return false;
        }
        if (item.sName === "dAuxiliaryQty" && selectedNode.sTypeKey !== "juantong") {
          return false;
        }
        if (item.sName === "dWlkd") {
          if (selectedNode.sTypeKey === "juantong") {
            const FabricWidth = commonFunc.showLocalMessage(props, "FabricWidth", "门幅");
            item.showName = FabricWidth;
          } else {
            const MaterialWidth = commonFunc.showLocalMessage(props, "MaterialWidth", "材料宽");
            item.showName = MaterialWidth;
          }
        }
        if (item.sName === "sPaperDirection" && selectedNode.sTypeKey === "huace") {
          return false;
        }

        // 判断bPartsDimension 是否显示展长展宽，0不显示，1显示

        if (selectedNode.bPartsDimension === false && (item.sName === "dPartsLength" || item.sName === "dPartsWidth")) {
          return false;
        }

        if (!selectedNode.bBleed && item.sName === "dBleed") {
          return false;
        }
        if (selectedNode.sTypeKey !== "juantong" && item.sName === "sPaperDirection") {
          return false;
        }
        if ((selectedNode.showName === "封套" && item.sName === "dSpine") || (selectedNode.showName === "封套" && item.sName === "bFlap")) {
          return false;
        }

        return item.iTag === iTag;
      });

    let boxConfigList = [];
    if (iTag === 20) {
      let showNameKeyList = ["dZBLB", "dSBLB", "dYBLB", "dXBLB", "dZBJJ", "dYBJJ", "dSBJJ", "dXBJJ"];
      if (selectedNode.sTypeKey === "juantong") {
        showNameKeyList = ["dSBLB", "dZBJJ", "dYBJJ", "dSBJJ", "dXBJJ"];
      }
      const UlToolPosition = commonFunc.showLocalMessage(props, "UlToolPosition", "上下刀位");
      const RLToolPosition = commonFunc.showLocalMessage(props, "RLToolPosition", "左右刀位");
      const LeftMargin = commonFunc.showLocalMessage(props, "LeftMargin", "左右留白");
      const StayOnTheEdge = commonFunc.showLocalMessage(props, "StayOnTheEdge", "留边");
      const Spacing = commonFunc.showLocalMessage(props, "Spacing", "间距");
      const HopDistance = commonFunc.showLocalMessage(props, "HopDistance", "跳距");
      boxConfigList = boxConfig?.gdsconfigformslave?.filter(item => item.bVisible && showNameKeyList.includes(item.sName)) || [];
      if (selectedNode.sTypeKey === "juantong") {
        const mappings = {
          dZBLB: StayOnTheEdge,
          dXBJJ: Spacing,
          dYBJJ: HopDistance,
        };

        boxConfigList.forEach(item => {
          if (mappings[item.sName]) {
            item.showName = mappings[item.sName];
          }
        });
      } else {
        const mappings = {
          dZBLB: LeftMargin,
          dXBJJ: UlToolPosition,
          dYBJJ: RLToolPosition,
        };

        boxConfigList.forEach(item => {
          if (mappings[item.sName]) {
            item.showName = mappings[item.sName];
          }
        });
      }
    }
    const newConfig = [...boxConfigList, ...config];

    return {
      ...props,
      viewConfigs: newConfig,
      tableConfig: { ...slaveConfig, gdsconfigformslave: newConfig },
      iColValueView: 24,
      viewRow: { ...slaveRowData, sProductClassifyId: selectedNode.sId },
      tableName: `slaveUp${boxModel}`,
    };
  };

  // 印刷参数表单
  let upViewProps12 = getUpViewPropsByITag(12);

  const filterConditions = {
    juantong: x =>
      x.sName === "sMagnification" ||
      x.sName === "dPartsLength" ||
      x.sName === "dPartsWidth" ||
      x.sName === "dRowGap" ||
      x.sName === "dColGap" ||
      x.sName === "dBleed" ||
      x.sName === "sPaperDirection",
    default: x =>
      x.sName === "sPaperDirection" ||
      x.sName === "dBleed" ||
      x.sName === "sMagnification" ||
      x.sName === "dPartsLength" ||
      x.sName === "dPartsWidth" ||
      x.sName === "dSumPQty",
  };
  if (upViewProps12 && selectedNode.sTypeKey === "juantong") {
    upViewProps12.viewConfigs = upViewProps12?.viewConfigs.filter(filterConditions.juantong);
  }
  if (upViewProps12 && !(selectedNode.sTypeKey === "huace" && slaveRowData.sBoxModel === "封面")) {
    upViewProps12.viewConfigs = upViewProps12.viewConfigs.filter(filterConditions.default);
  }
  // 拼板信息表单
  const upViewProps20 = getUpViewPropsByITag(20);
  const { bBox } = selectedNode;

  const upAbleConfig =
    slaveConfig?.gdsconfigformslave?.filter(item => item.iTag === 10)?.filter(item => (bBox ? true : item.sName !== "sName")) || [];
  const upViewProps = {
    ...props,
    viewConfigs: [...(Array.isArray(showUpAbleConfigsExtra) ? showUpAbleConfigsExtra : [])],
    tableConfig: {
      ...slaveConfig,
      gdsconfigformslave: [...(Array.isArray(showUpAbleConfigsExtra) ? showUpAbleConfigsExtra : [])],
    },
    iColValueView: 24,
    viewRow: slaveRowData,
    tableName: `slaveUp${boxModel}`,
  };

  // 后道参数
  const { sBackProcessData } = slaveRowData || [];
  const [downAbleConfigsNew, setDownAbleConfigsNew] = useState([]);

  const computedDownAbleConfigsNew = useMemo(() => {
    const arr = downAbleConfigs.reduce((pre, cur) => {
      const childConfigs = downAbleExtraConfigs.filter(item => item.sParentName === cur.showName);
      return [...pre, cur, ...childConfigs];
    }, [])
    const sortBySName = (arr) => {
      return arr.slice().sort((a, b) => {
        // 分割前缀和后缀
        const aParts = a.sName.split('_');
        const bParts = b.sName.split('_');
        const aParamsNum = parseInt(aParts[0].replace('sParams', '')) || 0;
        const bParamsNum = parseInt(bParts[0].replace('sParams', '')) || 0;

        if (aParamsNum !== bParamsNum) {
          return aParamsNum - bParamsNum;
        }
        const aHasSuffix = aParts.length > 1;
        const bHasSuffix = bParts.length > 1;
        if (!aHasSuffix && bHasSuffix) return -1;
        if (aHasSuffix && !bHasSuffix) return 1;
        if (aHasSuffix && bHasSuffix) {
          return aParts[1].localeCompare(bParts[1], undefined, { numeric: true });
        }
        return 0;
      });
    }
    const sortedData = arr.reduce((prev, cur) => {
      const exists = prev.find(item => item.sName === cur.sName);
      if (!exists) {
        prev.push(cur);
      }
      return prev;
    }, [])
    return sortBySName(sortedData);
  }, [downAbleConfigs, downAbleExtraConfigs]);

  // 使用 useEffect 设置 downAbleConfigsNew 状态
  useEffect(() => {
    if (!isEqual(downAbleConfigsNew, computedDownAbleConfigsNew)) {
      setDownAbleConfigsNew(computedDownAbleConfigsNew);
    }
  }, [computedDownAbleConfigsNew, downAbleConfigsNew]);

  // 初始化状态，存储每个 Switch 的状态
  const [switchStates, setSwitchStates] = useState(null);
  // 初始化成品工序 
  const [finishedStates, setFinishedStates] = useState(null);
  // 处理 Switch 变化的函数
  const handleSwitchChange = (item, val) => {
    setSwitchStates({
      ...switchStates,
      [item.sName]: val,
    });
    const iIndex = downAbleExtraConfigs.findIndex(x => x.sId === item.sId);
    const slaveRowIndex = slaveData.findIndex(x => x.sId === slaveRowData.sId);
    const { sBackProcessData = [] } = slaveData[slaveRowIndex] || {};
    const iIndex1 = sBackProcessData.findIndex(x => x.sProductClassifyId === item.sId);
    // 如果是添加的工序 并且switch为关闭的状态下 需要删除已选过的数据
    if (!val) {
      if (iIndex1 !== -1) {
        props.setState(pre => {
          slaveData[slaveRowIndex].sBackProcessData?.splice(iIndex1, 1);
          return {
            ...pre,
            // downAbleExtraConfigs: [...downAbleExtraConfigs.slice(0, iIndex), ...downAbleExtraConfigs.slice(iIndex + 1)],
            slaveData,
            calcPriceFinished: false
          };
        });
      }
    }

  };

  // 过滤后的数据

  let downViewConfigs = downAbleConfigsNew
    .filter(item => item.sPartsName === boxModel || !item.sPartsName)
    .map((item, i) => ({
      ...item,
      isSelect: switchStates ? switchStates[item.sName] : false,
      // sName: "sParams" + i,
      sProductClassifyId: item.sId,
    }));

  useEffect(() => {
    if (!switchStates) return ''
    downViewConfigs = downAbleConfigsNew
      .filter(item => item.sPartsName === boxModel || !item.sPartsName)
      .map((item, i) => ({
        ...item,
        isSelect: switchStates ? switchStates[item.sName] : false,
        // sName: "sParams" + i,
        sProductClassifyId: item.sId,
      }));
  }, [switchStates])
  const hasProcessedRef = useRef(false);
  useEffect(() => {
    hasProcessedRef.current = false;
    if (!sBackProcessData?.length || !downViewConfigs) return;
    // 批量状态更新
    const updates = sBackProcessData.reduce((acc, item) => {
      const sName = downViewConfigs.find(x => x.showName === item.sProcessName)?.sName;
      if (sName) acc[sName] = true;
      Object.keys(item).forEach(key => {
        if (/^sParams\d+/.test(key)) {
          acc[key] = true;
        }
      });
      return acc;
    }, {});
    if (Object.keys(updates).length > 0) {
      setSwitchStates(prev => ({ ...prev, ...updates }));
      hasProcessedRef.current = true;
    }
  }, [sBackProcessData, downAbleConfigsNew]);

  const downViewProps = {
    ...props,
    viewConfigs: downViewConfigs,
    tableConfig: { ...slaveConfig, gdsconfigformslave: downAbleConfigs },
    iColValueView: 24,
    viewRow: slaveRowData,
    tableName: `slaveDown${boxModel}`,
  };

  const { productProcessInfo = [] } = masterData;
  const finishedViewProps = {
    ...props,
    viewConfigs: finishedConfigs.map(config => ({
      ...config,
      isSelect: finishedStates ? finishedStates[config.sName] : false,
      costomStyle: productProcessInfo.find(item => item[config.sName])?.sParamConfig ? styles.sParamConfig : "",
    })),
    tableConfig: { ...slaveConfig, gdsconfigformslave: finishedConfigs },
    iColValueView: 24,
    viewRow: { ...masterData, sId: masterData.sId || "123" },
    getViewRow: config => {
      return productProcessInfo.find(item => item[config.sName]) || {};
    },

    tableName: "finished",
    onCostomClick: (showConfig) => {
      props.setState(pre => ({
        ...pre,
        backendParamsConfig: commonUtils.convertStrToObj(productProcessInfo.find(item => item[showConfig.sName])?.sParamConfig, []),
        backendConfig: { sParentFieldsName: showConfig.sName, typeName: "finished", dropDownDataSelected: showConfig },
      }));
    },
  };
  useEffect(() => {
    if (!productProcessInfo?.length || !finishedConfigs) return;
    const updates = productProcessInfo.reduce((acc, item) => {
      const sName = downViewConfigs.find(x => x.showName === item.sProcessName)?.sName;
      if (sName) acc[sName] = true;
      Object.keys(item).forEach(key => {
        if (/^sParams\d+/.test(key)) {
          acc[key] = true;
        }
      });
      return acc;
    }, {});
    if (Object.keys(updates).length > 0) {
      setFinishedStates(prev => ({ ...prev, ...updates }));
    }
  }, [productProcessInfo, finishedConfigs])

  const calcMethodData = commonUtils.convertStrToObj(slaveRowData?.sColumnNameConfigExclusion, []);
  // const radioValue = null;
  const { radioValue = calcMethodData[0]?.sCode } = slaveRowData;
  const [materialLength, setMaterialLength] = useState(0);
  const [materialWidth, setMaterialWidth] = useState(0);


  // 使用 防抖防止输出数据错误
  const debounceTimer = useRef(null);
  const debouncedHandleSaveState = useCallback(
    (...args) => {
      clearTimeout(debounceTimer.current);
      debounceTimer.current = setTimeout(() => {
        handleSaveState(...args);
      }, 500);
    },
    [handleSaveState]
  );
  // 使用 useCallback 确保回调函数的稳定性
  const handleSaveState = (
    length,
    width,
    slaveData,
    masterData,
    dSinglePQty,
    dMaterialsKQty,
    dProductQty,
    scale,
    dWlcd,
    dWlkd,
    innerWidth,
    innerHeight,
    dHorizontal,
    dPortrait,
    dHorizontalType,
    dPortraitType
  ) => {
    // 查找符合条件的索引
    const { selectedNode } = props.state;

    const index = slaveData?.findIndex(x => x.sTreeNodeName === selectedNode.showName && x.sBoxModel === props.boxModel);
    const { isRadio } = slaveData[index] || false
    if (index !== undefined && index !== -1) {
      // 计算开数

      // 获取原始对象并创建一个新的对象进行更新
      const updatedProduct = {
        ...slaveData[index],
        materialLength: dWlcd,
        materialWidth: dWlkd,
        dMachineLength: dWlcd, // 上机长
        dMachineWidth: dWlkd, // 上机宽
        sMaterialsStyle: `${slaveData[index]?.dWlcd || dWlcd}*${slaveData[index]?.dWlkd || dWlkd}`, // 原纸尺寸
        sMachineStyle: `${length || slaveData[index].materialLength}*${width || slaveData[index].materialWidth}`, // 开料尺寸为计算的排版尺寸
        sMaterialRate: (((length * width) / ((slaveData[index].dWlcd || dWlcd) * (slaveData[index].dWlkd || dWlkd))) * 100).toFixed(2),
        newMaterialLength: dWlcd,
        newMaterialWidth: dWlkd,
        sLayoutRate: Number(
          (
            (((length || slaveData[index].materialLength) * (width || slaveData[index].materialWidth)) /
              (slaveData[index].dMaxLength * slaveData[index].dMaxWidth)) *
            100
          ).toFixed(2)
        ),
        // dWlcd: selectedNode.sTypeKey === 'juantong' ? Math.floor(dProductQty / dSinglePQty * ( length/ 1000)) : dWlcd,
        dWlcd: isRadio ? dWlcd : sBillNo ? slaveData[index]?.dWlcd : dWlcd,
        dWlkd: isRadio ? dWlkd : sBillNo ? slaveData[index]?.dWlkd : dWlkd,
        dAuxiliaryQty: Math.floor((dProductQty / dSinglePQty) * (length / 1000)),
        dMachineQty: sBillNo && slaveData[index].dMachineQty ? slaveData[index].dMachineQty : Math.floor(dProductQty / dSinglePQty),
        dSinglePQty: dSinglePQty,
        dMaterialsKQty: dMaterialsKQty,
        scale: scale,
        dPartsLength: innerWidth,
        dPartsWidth: innerHeight,
        dHorizontal: dHorizontalType,
        dPortrait: dPortraitType,
        dHorizontalType: dHorizontalType, // 判断
        dPortraitType: dPortraitType,
        isRadio: false,
      };
      let juantongConfig = {};

      if (selectedNode.sTypeKey === "juantong") {
        const { dYBJJ, dXBJJ, dZBLB } = slaveData[index];
        juantongConfig = {
          dColGap: dYBJJ,
          dRowGap: dXBJJ,
          iCol: dPortraitType,
          iRow: dHorizontalType,
          dCutEdge: dZBLB,
        };
      }
      const newSlaveData = {
        ...updatedProduct,
        ...juantongConfig,
      };
      // 更新状态
      setTimeout(() => {
        props.setState(prevState => ({
          ...prevState,
          slaveData: slaveData.map((item, i) => (i === index ? newSlaveData : item)),
        }));
      }, 200);
    }

    setMaterialLength(length);
    setMaterialWidth(width);
  };
  const onSaveDPartsLength = useCallback((innerWidth, innerHeight, slaveData) => {
    const { selectedNode } = props.state;
    const index = slaveData?.findIndex(x => x.sTreeNodeName === selectedNode.showName && x.sBoxModel === props.boxModel);
    if (index !== undefined && index !== -1) {
      const updatedProduct = {
        ...slaveData[index],
        dPartsLength: innerWidth,
        dPartsWidth: innerHeight,
        materialLength: 0,
        materialWidth: 0,
        dMachineLength: 0, // 上机长
        dMachineWidth: 0, // 上机宽
        newMaterialLength: 0,
        newMaterialWidth: 0,
        sLayoutRate: 0,
        dWlcd: 0,
        dWlkd: 0,
        dMachineQty: 0,
        dSinglePQty: 0,
        dMaterialsKQty: 0,
        scale: 1,
      };
      props.setState(prevState => ({
        ...prevState,
        slaveData: slaveData.map((item, i) => (i === index ? updatedProduct : item)),
      }));
    }
  }, []);
  const boxProps = {
    ...props,
    slaveRowData,
    dSBJJ: slaveRowData?.dXBJJ,
    dZBJJ: slaveRowData?.dYBJJ,
    radioValue: calcMethodData?.find(item => item.sCode === radioValue),
    boxWidth: 190,
    boxHeight: 150,
    textSize: 9,
    isMobile: true,
    // boxPicData,
  };
  const showImgMProps = {
    ...props,
    materialLength,
    materialWidth,
    bBox: true, // 快速报价盒型展示
    width: 180,
    height: 150,
    size: 7,
    isMobile: true,
  };

  const handleChange = v => {
    if (v.length) {
      const newValue = v[0];
      if (newValue === selected) {
        // 如果是再次点击已选中的项，则不取消选中
        return;
      }
      setSelected(newValue);
      const list = selectList.filter(x => x.sBoxType === newValue);
      setBoxsList(list);
      setBoxPopup(true);
    } else {
      const list = selectList.filter(x => x.sBoxType === selected);
      setBoxsList(list);
      setBoxPopup(true);
    }
  };


  const { loading } = props;
  const calcMethod = calcMethodData.map(item => ({
    value: item.sCode,
    label: item.showName,
  }));

  const onCostomClick = showConfig => {
    props.setState(pre => ({
      ...pre,
      backendParamsConfig: commonUtils.convertStrToObj(sBackProcessData?.find(item => item[showConfig.sName0 || showConfig.sName])?.sParamConfig, []),
      backendConfig: { sParentFieldsName: showConfig.sName, sBoxModel: boxModel, typeName: 'slave', dropDownDataSelected: showConfig },
    }));
  };

  useEffect(() => {
    if (selectedNode.sTypeKey === "kapai" || selectedNode.sTypeKey === "juantong") {
      const data = selectList.find(x => x.sTypes === "6");
      if (!data) return '';
      const currentBoxModel = "slaveUp" + props.boxModel;
      props.onDataChange(currentBoxModel, "sName", { sName: data.sName }, data.sId, selectList);
    }
  }, [selectedNode.sTypeKey, selectList]);
  const getImageUrl = (sName) => {
    const imageUrlNew = `${commonConfig.server_host}file/downloadPrice?sLogoName=${sName}&date=${new Date().getTime()}`;
    return imageUrlNew;
  };
  const removeExtension = (filename) => {
    if (!filename) return
    const lastDotIndex = filename.lastIndexOf('.');
    if (lastDotIndex === -1) {
      // 如果字符串中没有点，则返回原字符串
      return filename;
    }
    return filename.substring(0, lastDotIndex);
  }
  let imagesData = useMemo(() => {
    if (!slaveRowData) return [];
    return [
      { src: getImageUrl(removeExtension(slaveRowData.sPackDetailPathUpLoad)), alt: "展开图" },
      { src: getImageUrl(removeExtension(slaveRowData.sPackPath)), alt: "立体图" },
    ];
  }, [slaveRowData?.sPackDetailPathUpLoad, slaveRowData?.sPackPath]);
  if (!slaveRowData.sPackDetailPathUpLoad) {
    imagesData = [{ src: getImageUrl(removeExtension(slaveRowData.sPackPath)), alt: "立体图" }];
  } else if (!slaveRowData.sPackPath) {
    imagesData = [{ src: getImageUrl(removeExtension(slaveRowData.sPackPath)), alt: "立体图" }];
  }
  const [imgVisible, setImgVisible] = useState(false)
  const impositionDetails = commonFunc.showLocalMessage(props, "impositionDetails", "拼版详情");
  const PrintedInformation = commonFunc.showLocalMessage(props, "PrintedInformation", "印刷信息");
  const backEndParameters = commonFunc.showLocalMessage(props, "backEndParameters", "后道参数");
  const choose = commonFunc.showLocalMessage(props, "choose", "选择");
  return (
    <div>
      {selectedNode.bBox ? (
        <div>
          {selectedNode.sTypeKey !== "kapai" ? (
            <div>
              <Selector
                columns={4}
                options={boxTypeList}
                style={{ "--padding": "12px 0" }}
                value={selected ? [selected] : []}
                onChange={v => handleChange(v)}
              />
              <div className={styles.line}></div>
            </div>
          ) : (
            ""
          )}
          <div>
            <Grid columns={4} gap={8}>
              {upViewProps
                ? upViewProps.viewConfigs.map(x => (
                  <Grid.Item>
                    <div className={styles.customer} key={x.id || x.sBig5}>
                      <div className={styles.label}>{x.sBig5}</div>
                      <SelectInput {...upViewProps} itemDetail={x} bCanInput={true} />
                    </div>
                  </Grid.Item>
                ))
                : ""}
            </Grid>
          </div>
          <div className={styles.svgBox}>
            <div style={{ width: "150px", height: "150px" }}>
              <DynamicSVG {...svgProps} />
            </div>
            {slaveRowData && slaveRowData.sPackPath ? <Image src={imagesData[0].src} width={125} height={125} fit="fill" onClick={() => {
              setImgVisible(true)
            }} /> : ""}
            <ImageViewer.Multi
              images={imagesData.map(item => item.src)}
              visible={imgVisible}
              defaultIndex={1}
              onClose={() => {
                setImgVisible(false)
              }}
            />
          </div>

          <Collapse style={{ width: '300px' }} className={styles.CollapseBox} >
            <Collapse.Panel key='1' title={impositionDetails} forceRender>
              <div>
                <Grid columns={3} gap={8}>
                  {upViewProps20
                    ? upViewProps20.viewConfigs.map(x => (
                      <Grid.Item>
                        <div className={styles.customer} key={x.id || x.showName}>
                          <div>{x.showName}</div>
                          <SelectInput {...upViewProps20} itemDetail={x} bCanInput={false} />
                        </div>
                      </Grid.Item>
                    ))
                    : ""}
                </Grid>
                {selectedNode.bBox ? (
                  <div style={{ width: '300px' }}>
                    <div className={styles.svgBox1}>
                      <div style={{ width: "49%", height: "49%", position: "relative" }}>
                        {
                          boxProps.slaveRowData && boxProps.state.masterData ?
                            <Typesetting {...boxProps} onSaveStates={debouncedHandleSaveState} onSaveDPartsLength={onSaveDPartsLength} />
                            : ''
                        }
                      </div>
                      <div style={{ width: "47%", height: "47%", position: "relative", fontWeight: '500' }}>
                        <ShowImgM {...showImgMProps} />
                      </div>
                    </div>
                    <Radio.Group
                      value={radioValue}
                      onChange={e => {
                        const iIndex = slaveData.findIndex(item => item.sId === slaveRowData.sId);
                        slaveData[iIndex].radioValue = e;
                        slaveData[iIndex].isRadio = true;
                        props.setState(pre => ({
                          ...pre,
                          slaveData: slaveData,
                        }));
                      }}
                    >
                      {calcMethod.map(item => (
                        <Radio value={item.value} style={{ marginRight: "8px" }}>
                          {" "}
                          {item.label}
                        </Radio>
                      ))}
                    </Radio.Group>
                  </div>
                ) : (
                  ""
                )}
              </div>
            </Collapse.Panel>
          </Collapse>
        </div>
      ) : (
        ""
      )}

      <div>
        <div className={styles.boxTitle}>
          {PrintedInformation}
          <EditFill color="#BFBFBF" style={{ marginLeft: "16px" }} />
        </div>
        <PrintParamsComponent {...props} />
        <Grid columns={3} gap={8}>
          {upViewProps12
            ? upViewProps12.viewConfigs.map(x => (
              <Grid.Item>
                <div className={styles.customer} key={x.id || x.showName}>
                  <div>{x.showName}</div>
                  <SelectInput {...upViewProps12} itemDetail={x} bCanInput={false} />
                </div>
              </Grid.Item>
            ))
            : ""}
        </Grid>
      </div>

      <div>
        <MaterialsComponent {...props} slaveRowData={slaveRowData} boxModel={boxModel} />
      </div>
      <div>
        <div className={styles.boxTitle}>
          {backEndParameters}
          <EditFill color="#BFBFBF" style={{ marginLeft: "16px" }} />
        </div>

        {downViewProps && downViewProps.viewConfigs && downViewProps.viewConfigs.length
          ? downViewProps.viewConfigs.map((x, i) => (
            <div key={x.sId}>
              <div className={styles.backBox}>
                <div className={styles.backEnd}>{x.showName}</div>
                <Switch checked={!!(switchStates && switchStates[x.sName])} onChange={val => handleSwitchChange(x, val)} />
                <div className={styles.customer} style={{ marginTop: "0", marginLeft: "32px", width: "40%" }}>
                  {switchStates && switchStates[x.sName] ? (
                    // 这里需要数组遍历 多个工序
                    <div className={styles.processFlex}>
                      <SelectInput
                        {...downViewProps}
                        itemDetail={{ ...x, sVisColumnName: "sProcessName" }}
                        downIndex={i}
                        onCostomClick={onCostomClick}
                      />
                      <div className={styles.processBtn}>
                        {!x.sParentName ? (
                          <Button
                            color="primary"
                            fill="solid"
                            size="small"
                            style={{
                              width: "30px",
                              height: "30px",
                              display: "flex",
                              justifyContent: "center",
                              alignItems: "center",
                              textAlign: "center",
                            }}
                            onClick={() => {
                              props.setState(pre => {
                                const newSId = commonUtils.createSid();
                                const newConfig = {
                                  ...x,
                                  sId: newSId,
                                  sParentName: x.showName,
                                  sName: `${x.sName}_${newSId}`,
                                };

                                return {
                                  ...pre,
                                  downAbleExtraConfigs: [...downAbleExtraConfigs, newConfig],
                                };
                              });
                            }}
                          >
                            <AddOutline />
                          </Button>
                        ) : (
                          <Button
                            color="danger"
                            fill="solid"
                            size="small"
                            style={{
                              width: "30px",
                              height: "30px",
                              display: "flex",
                              justifyContent: "center",
                              alignItems: "center",
                              textAlign: "center",
                            }}
                            onClick={() => {
                              const updateSwitch = { ...switchStates };
                              delete updateSwitch[x.sName];
                              setSwitchStates({ ...updateSwitch })
                              props.setState(pre => {
                                const iIndex = downAbleExtraConfigs.findIndex(item => item.sId === x.sId);
                                const slaveRowIndex = slaveData.findIndex(item => item.sId === slaveRowData.sId);
                                const { sBackProcessData = [] } = slaveData[slaveRowIndex];
                                const iIndex1 = sBackProcessData.findIndex(item => item.sProductClassifyId === x.sId);
                                if (iIndex1 !== -1) {
                                  slaveData[slaveRowIndex].sBackProcessData?.splice(iIndex1, 1);
                                }

                                return {
                                  ...pre,
                                  downAbleExtraConfigs: [...downAbleExtraConfigs.slice(0, iIndex), ...downAbleExtraConfigs.slice(iIndex + 1)],
                                  slaveData,
                                };
                              });
                            }}
                          >
                            <MinusOutline />
                          </Button>
                        )}
                      </div>
                    </div>
                  ) : (
                    ""
                  )}
                </div>
              </div>
              <BackendParamsExtraComponent {...props} itemDetail={x} onCostomClick={onCostomClick} backType={'slave'} />
            </div>
          ))
          : ""}


      </div>

      <Dialog
        visible={boxPopup}
        closeOnAction
        onClose={() => {
          setBoxPopup(false);
        }}
        actions={[
          {
            key: "close",
            text: "关闭",
          },
        ]}
        content={
          <div>
            {boxsList.map(item => {
              return (
                <div className={styles.boxListBody}>
                  <div>
                    {item.sName}
                    <Image src={getImageUrl(removeExtension(item.sPackPath))} width={100} height={100}></Image>
                  </div>
                  <Button
                    color="primary"
                    fill="outline"
                    size="small"
                    onClick={val => {
                      const currentBoxModel = "slaveUp" + props.boxModel;
                      props.onDataChange(currentBoxModel, "sName", { sName: item.sName }, item.sId, boxsList);
                      setBoxPopup(false);
                    }}
                  >
                    {choose}
                  </Button>
                </div>
              );
            })}
          </div>
        }
      ></Dialog>
    </div>
  );
};
// 成品工序
const FinishedProcessComponent = props => {
  const { state, boxModel } = props;
  const {
    activeKey,
    slaveConfig,
    masterData,
    selectedNode,
    boxConfig,
    downAbleConfigs = [],
    downAbleExtraConfigs = [],
    finishedConfigs = [],
    slaveData,
  } = state || {};
  const slaveRowData = slaveData.find(item => item.sTreeNodeName === selectedNode.showName && item.sBoxModel === boxModel) || {};

  // 后道参数
  const { sBackProcessData } = slaveRowData || [];
  const [downAbleConfigsNew, setDownAbleConfigsNew] = useState([]);

  const computedDownAbleConfigsNew = useMemo(() => {
    const arr = downAbleConfigs.reduce((pre, cur) => {
      const childConfigs = downAbleExtraConfigs.filter(item => item.sParentName === cur.showName);
      return [...pre, cur, ...childConfigs];
    }, [])
    const sortBySName = (arr) => {
      return arr.slice().sort((a, b) => {
        // 分割前缀和后缀
        const aParts = a.sName.split('_');
        const bParts = b.sName.split('_');
        const aParamsNum = parseInt(aParts[0].replace('sParams', '')) || 0;
        const bParamsNum = parseInt(bParts[0].replace('sParams', '')) || 0;

        if (aParamsNum !== bParamsNum) {
          return aParamsNum - bParamsNum;
        }
        const aHasSuffix = aParts.length > 1;
        const bHasSuffix = bParts.length > 1;
        if (!aHasSuffix && bHasSuffix) return -1;
        if (aHasSuffix && !bHasSuffix) return 1;
        if (aHasSuffix && bHasSuffix) {
          return aParts[1].localeCompare(bParts[1], undefined, { numeric: true });
        }
        return 0;
      });
    }
    const sortedData = arr.reduce((prev, cur) => {
      const exists = prev.find(item => item.sName === cur.sName);
      if (!exists) {
        prev.push(cur);
      }
      return prev;
    }, [])
    return sortBySName(sortedData);
  }, [downAbleConfigs, downAbleExtraConfigs]);

  // 使用 useEffect 设置 downAbleConfigsNew 状态
  useEffect(() => {
    if (!isEqual(downAbleConfigsNew, computedDownAbleConfigsNew)) {
      setDownAbleConfigsNew(computedDownAbleConfigsNew);
    }
  }, [computedDownAbleConfigsNew, downAbleConfigsNew]);

  // 初始化状态，存储每个 Switch 的状态
  const [switchStates, setSwitchStates] = useState(null);
  // 初始化成品工序 
  const [finishedStates, setFinishedStates] = useState(null);
  // 处理成品工序 Switch 变化的函数
  const handleSwitchFinishedChange = (item, val) => {
    setFinishedStates({
      ...finishedStates,
      [item.sName]: val,
    });
    const iIndex = downAbleExtraConfigs.findIndex(x => x.sId === item.sId);
    const slaveRowIndex = slaveData.findIndex(x => x.sId === slaveRowData.sId);
    const { productProcessInfo = [] } = masterData
    const iIndex1 = productProcessInfo.findIndex(x => x.sProductClassifyId === item.sId);
    if (!val) {
      if (iIndex1 !== -1) {
        props.setState(pre => {
          masterData.productProcessInfo?.splice(iIndex1, 1);
          return {
            ...pre,
            masterData,
            calcPriceFinished: false
          };
        });
      }
    }
  };
  // 过滤后的数据

  let downViewConfigs = downAbleConfigsNew
    .filter(item => item.sPartsName === boxModel || !item.sPartsName)
    .map((item, i) => ({
      ...item,
      isSelect: switchStates ? switchStates[item.sName] : false,
      // sName: "sParams" + i,
      sProductClassifyId: item.sId,
    }));

  useEffect(() => {
    if (!switchStates) return ''
    downViewConfigs = downAbleConfigsNew
      .filter(item => item.sPartsName === boxModel || !item.sPartsName)
      .map((item, i) => ({
        ...item,
        isSelect: switchStates ? switchStates[item.sName] : false,
        // sName: "sParams" + i,
        sProductClassifyId: item.sId,
      }));
  }, [switchStates])
  const hasProcessedRef = useRef(false);
  useEffect(() => {
    hasProcessedRef.current = false;
    if (!sBackProcessData?.length || !downViewConfigs) return;
    // 批量状态更新
    const updates = sBackProcessData.reduce((acc, item) => {
      const sName = downViewConfigs.find(x => x.showName === item.sProcessName)?.sName;
      if (sName) acc[sName] = true;
      Object.keys(item).forEach(key => {
        if (/^sParams\d+/.test(key)) {
          acc[key] = true;
        }
      });
      return acc;
    }, {});
    if (Object.keys(updates).length > 0) {
      setSwitchStates(prev => ({ ...prev, ...updates }));
      hasProcessedRef.current = true;
    }
  }, [sBackProcessData, downAbleConfigsNew]);



  const { productProcessInfo = [] } = masterData;
  const finishedViewProps = {
    ...props,
    viewConfigs: finishedConfigs.map(config => ({
      ...config,
      isSelect: finishedStates ? finishedStates[config.sName] : false,
      costomStyle: productProcessInfo.find(item => item[config.sName])?.sParamConfig ? styles.sParamConfig : "",
    })),
    tableConfig: { ...slaveConfig, gdsconfigformslave: finishedConfigs },
    iColValueView: 24,
    viewRow: { ...masterData, sId: masterData.sId || "123" },
    getViewRow: config => {
      return productProcessInfo.find(item => item[config.sName]) || {};
    },

    tableName: "finished",
    onCostomClick: (showConfig) => {
      props.setState(pre => ({
        ...pre,
        backendParamsConfig: commonUtils.convertStrToObj(productProcessInfo.find(item => item[showConfig.sName])?.sParamConfig, []),
        backendConfig: { sParentFieldsName: showConfig.sName, typeName: "finished", dropDownDataSelected: showConfig },
      }));
    },
  };
  useEffect(() => {
    if (!productProcessInfo?.length || !finishedConfigs) return;
    const updates = productProcessInfo.reduce((acc, item) => {
      const sName = downViewConfigs.find(x => x.showName === item.sProcessName)?.sName;
      if (sName) acc[sName] = true;
      Object.keys(item).forEach(key => {
        if (/^sParams\d+/.test(key)) {
          acc[key] = true;
        }
      });
      return acc;
    }, {});
    if (Object.keys(updates).length > 0) {
      setFinishedStates(prev => ({ ...prev, ...updates }));
    }
  }, [productProcessInfo, finishedConfigs])



  return <div style={{ padding: '0 12px', transform: 'translateY(-12px)' }}>
    {finishedViewProps && finishedViewProps.viewConfigs && finishedViewProps.viewConfigs.length
      ? finishedViewProps.viewConfigs.map((x, i) => (
        <div key={x.sId}>
          <div className={styles.backBox}>
            <div className={styles.backEnd}>{x.showName}</div>
            <Switch checked={!!(finishedStates && finishedStates[x.sName])} onChange={val => handleSwitchFinishedChange(x, val)} />
            <div className={styles.customer} style={{ marginTop: "0", marginLeft: "32px", width: "40%" }}>
              {finishedStates && finishedStates[x.sName] ? (
                // 这里需要数组遍历 多个工序
                <div className={styles.processFlex}>
                  <SelectInput
                    {...finishedViewProps}
                    itemDetail={{ ...x, sVisColumnName: "sProcessName" }}
                    downIndex={i}
                    onCostomClick={finishedViewProps.onCostomClick}
                  />
                </div>
              ) : (
                ""
              )}
            </div>
          </div>
          <BackendParamsExtraComponent {...props} itemDetail={x} onCostomClick={finishedViewProps.onCostomClick} backType={'finished'} />
        </div>
      ))
      : ""}
  </div>
}
// 印刷参数组件（印刷、颜色、单双面）
const PrintParamsComponent = props => {
  const { state, setState, boxModel } = props;
  const { slaveConfig, slaveData, selectedNode } = state;
  if (!slaveConfig) return '';
  const slaveRowData = slaveData.find(item => item.sTreeNodeName === selectedNode.showName && item.sBoxModel === boxModel) || {};
  const slaveRowDataIndex = slaveData.findIndex(item => item.sId === slaveRowData.sId);
  const { sBackProcessData = [] } = slaveRowData;
  const printParams = sBackProcessData.filter(item => item.bPrintParams);

  const printParamsConfig = slaveConfig.gdsconfigformslave
    .filter(item => ["sPrint", "sColor", "iPrintModePo"].includes(item.sName))
    .map(item => {
      return {
        ...item,
        iColValue: 8,
      };
    });
  const result = [];
  for (let i = 0; i < printParams.length + 1; i++) {
    const printParamsItem = printParams[i - 1];
    // const viewRow = {
    //   ...(i === 0 ? slaveRowData : printParamsItem),
    //   sProductClassifyId: selectedNode.sId,
    //   sProcessId: i === 0 ? slaveRowData.sId : printParamsItem.sId,
    // };
    const viewRow = { ...(i === 0 ? slaveRowData : printParamsItem), sProductClassifyId: selectedNode.sId };
    const viewTableId = "viewTableId_" + viewRow.sId;

    const viewProps = {
      ...props,
      viewConfigs: printParamsConfig.map(item => ({ ...item, costomStyle: `xlyPrintParams${i}` })),
      tableConfig: { ...slaveConfig, gdsconfigformslave: printParamsConfig },
      iColValueView: 24,
      viewRow,
      tableName: `${i === 0 ? "slaveUp" : "slaveDown"}${boxModel}`,
      onDataChange: (...args) => {
        //  setTimeout(() => {
        //   const oLabel = document.querySelector(`#${viewTableId}`)?.querySelector(`.xlyPrintParams${i}`)?.querySelector(".ant-form-item-label");
        //   oLabel?.click();
        // }, 200);

        if (i === 0) {
          props.onDataChange(...args);
          return;
        }

        const iIndex = sBackProcessData.findIndex(item => item.sId === printParamsItem.sId);
        sBackProcessData[iIndex] = { ...sBackProcessData[iIndex], ...args[2] };
        slaveData[slaveRowDataIndex] = { ...slaveRowData, sBackProcessData };
        setState(pre => {
          return { ...pre, slaveData };
        });
      },
      onCostomClick: (showConfig) => {
        if (showConfig.sName !== "sPrint") return;


        const { sPrintConfig } = state;

        if (!sPrintConfig) return;
        const backendConfigNew = {
          sParentFieldsName: "sPrint",
          sBoxModel: boxModel,
          printParamsId: viewRow.sId,
        };

        const dropDownData = commonUtils.convertStrToObj(sPrintConfig.sChineseDropDown, []);
        const dropDownDataSelected = dropDownData.find(item => item.sId === viewRow.sProcessId);
        if (!dropDownDataSelected) {
          props.setState(pre => ({
            ...pre,
            backendParamsConfig: [],
            backendConfig: {},
          }));
          return;
        }
        const backendParamsConfigNew = commonUtils.convertStrToObj(dropDownDataSelected.sParamConfig, []);

        props.setState(pre => ({
          ...pre,
          backendParamsConfig: backendParamsConfigNew,
          backendConfig: backendConfigNew,
        }));
      },
    };

    result.push(
      <div className={styles.materialsLine}>
        <div className={styles.materialsViewTable}>
          <Grid columns={3} gap={8}>
            {viewProps
              ? viewProps.viewConfigs.map(x => (
                <Grid.Item>
                  <div className={styles.customer} key={x.id || x.showName}>
                    <div>{x.showName}</div>
                    <SelectInput {...viewProps} itemDetail={x} bCanInput={false} />
                  </div>
                </Grid.Item>
              ))
              : ""}
          </Grid>
          {/* <CommonViewTable {...viewProps} /> */}
        </div>
        <div className={styles.materialsBtns} style={{ width: "10%" }}>
          <Button
            color="primary"
            fill="solid"
            size="small"
            style={{ width: "30px", height: "30px", display: "flex", justifyContent: "center", alignItems: "center", textAlign: "center" }}
            onClick={() => {
              const defaultData = commonFunc.getDefaultData({ ...slaveConfig, gdsconfigformslave: printParamsConfig }, { tree: selectedNode });
              sBackProcessData.push({
                sId: commonUtils.createSid(),
                bPrintParams: true,
                ...defaultData,
              });
              slaveData[slaveRowDataIndex] = { ...slaveRowData, sBackProcessData };
              setState(pre => {
                return { ...pre, slaveData };
              });
            }}
          >
            <AddOutline />
          </Button>
          {i !== 0 ? (
            <Button
              style={{
                width: "30px",
                height: "30px",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                textAlign: "center",
                marginTop: "5px",
              }}
              onClick={() => {
                const iIndex = sBackProcessData.findIndex(item => item.sId === printParamsItem.sId);
                sBackProcessData.splice(iIndex, 1);
                slaveData[slaveRowDataIndex] = { ...slaveRowData, sBackProcessData };
                setState(pre => {
                  return { ...pre, slaveData };
                });
              }}
            >
              <MinusOutline />
            </Button>
          ) : (
            ""
          )}
        </div>
      </div>
    );
  }
  return result;
};
// 材料组件
const MaterialsComponent = props => {
  const { state, boxModel } = props;
  const { slaveConfig, slaveData = [], selectedNode = {} } = state;
  let { slaveRowData } = props;
  if (!slaveRowData) return;
  const { sParam = "" } = selectedNode;
  const sParamList = sParam.split(",");
  let materialsInfoDefaultData = sParam ? new Array(sParamList.length).fill({}).map((_, index) => ({ showName: sParamList[index] })) : [{}];
  let { materialsInfo = materialsInfoDefaultData } = slaveRowData;
  const materialsConfig = slaveConfig?.gdsconfigformslave
    .filter(item => item.iTag === 11)
    .map(item => {
      const { sName } = item;
      if (sName === "sMaterialsName") {
        return {
          ...item,
          sVisColumnName: "sMaterialsName",
          iColValue: 20,
        };
      } else if (sName === "sComMaterials") {
        return {
          ...item,
          sName: "bComMaterials",
          iColValue: 4,
        };
      } else {
        return item;
      }
    });
  const extraState = {
    calcPriceFinished: false,
    manyData: [],
  };
  const materialsInfoName = commonFunc.showLocalMessage(props, "materialsInfo", "材料信息");
  return materialsInfo.map((item, index) => {
    let viewRow = { ...materialsInfo[index], sProductClassifyId: selectedNode.sId };
    viewRow = { ...viewRow, sMaterialsName0: viewRow.showName || "" };
    if (!materialsConfig) return;
    let materialsConfigNew = cloneDeep(materialsConfig);
    if (viewRow.showName) {
      const iIndex = materialsConfigNew.findIndex(item => item.sName === "sMaterialsName");
      if (iIndex !== -1) {
        materialsConfigNew[iIndex].showName = viewRow.showName;
      }
    }
    const viewProps = {
      ...props,
      viewConfigs: materialsConfigNew,
      tableConfig: { ...slaveConfig, gdsconfigformslave: materialsConfigNew },
      iColValueView: 24,
      viewRow,
      tableName: `slaveUp${boxModel}`,
      onDataChange: (name, sFieldName, changeValue, sId, dropDownData, isWait) => {
        const iIndex = slaveData.findIndex(item => item.sId === slaveRowData.sId);
        const { sMaterialsName, sMaterialsNo, sAuxiliaryUnit, sMaterialsUnit, dGramWeight, sMaterialsType, dWlkd, dWlcd } = changeValue;

        if (iIndex !== -1) {
          slaveData[iIndex].materialsInfo = materialsInfo.map((item, i) => (i === index ? { ...item, ...changeValue } : item));
          slaveRowData = slaveData[iIndex];
        } else {
          const { selectedNode = {} } = state;
          const { showName: sTreeNodeName } = selectedNode;

          slaveData.push({
            sId: commonUtils.createSid(),
            handleType: "add",
            sBoxModel: boxModel,
            sTreeNodeName,
            materialsInfo: materialsInfo.map((item, i) => (i === index ? { ...item, ...changeValue } : item)),
          });
        }
        props.setState(pre => ({ ...pre, slaveData, slaveRowData, ...extraState }));
      },
    };

    return (
      <div className={styles.materialBox}>
        <div className={styles.boxTitle}>
          {materialsInfoName}
          <EditFill color="#BFBFBF" style={{ marginLeft: "16px" }} />
        </div>
        <div className={styles.materialsLine}>
          <div className={styles.materialsViewTable}>
            <Grid columns={7} gap={8}>
              {viewProps?.viewConfigs && viewProps?.viewConfigs.length ?
                viewProps?.viewConfigs.map((x, i) => {
                  return <div style={{ gridColumn: i > 0 ? 'span 2' : 'span 3' }}>
                    <div className={styles.selectInput} >
                      <SelectInput {...viewProps} itemDetail={{ ...x, sVisColumnName: "sMaterials" }} />
                    </div>
                  </div>
                }) : ''}
            </Grid>
          </div>
          <div className={styles.materialsBtns} style={{ width: "10%" }}>
            <Button
              color="primary"
              fill="solid"
              size="small"
              style={{ width: "30px", height: "30px", display: "flex", justifyContent: "center", alignItems: "center", textAlign: "center" }}
              onClick={() => {
                const iIndex = slaveData.findIndex(item => item.sId === slaveRowData.sId);
                const rowIndex = materialsInfo.findIndex((item, i) => i === index);
                const materialsInfoNew = [...materialsInfo];
                materialsInfoNew.splice(rowIndex + 1, 0, {});
                if (iIndex !== -1) {
                  slaveData[iIndex].materialsInfo = materialsInfoNew;
                } else {
                  const { selectedNode = {} } = state;
                  const { showName: sTreeNodeName } = selectedNode;
                  slaveData.push({
                    sId: commonUtils.createSid(),
                    handleType: "add",
                    sBoxModel: boxModel,
                    sTreeNodeName,
                    materialsInfo: materialsInfoNew,
                  });
                }
                slaveRowData.materialsInfo = materialsInfoNew;
                props.setState(pre => ({ ...pre, slaveData, slaveRowData, ...extraState }));
              }}
            >
              <AddOutline />
            </Button>
            {index !== 0 ? (
              <Button
                style={{
                  width: "30px",
                  height: "30px",
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  textAlign: "center",
                  marginTop: "5px",
                }}
                onClick={() => {
                  const iIndex = slaveData.findIndex(item => item.sId === slaveRowData.sId);
                  const rowIndex = materialsInfo.findIndex((item, i) => i === index);
                  const materialsInfoNew = [...materialsInfo];
                  materialsInfoNew.splice(rowIndex, 1);
                  slaveData[iIndex].materialsInfo = materialsInfoNew;
                  slaveRowData.materialsInfo = materialsInfoNew;
                  props.setState(pre => ({ ...pre, slaveData, slaveRowData, ...extraState }));
                }}
              >
                <MinusOutline />
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
      </div>
    );
  });
};
// 多数量组件
const ManyComponent = props => {
  const { state, setState, enabled, loading } = props;
  const { masterData = {}, calcPriceLoading, calcPriceFinished, manyData = [], slaveData } = state;
  const [submitLoading, setSubmitLoading] = useState(false);
  const [processPercent, setProcessPercent] = useState(0);
  const [selectedRadio, setSelectedRadio] = useState(null);
  const [visible, setVisible] = useState(false);
  const [value, setValue] = useState("");
  const [changeValue, setChangeValue] = useState("");
  // 根据主表数量更改多数量表
  useEffect(() => {
    // if (props?.masterData?.sBillNo) return ''
    const baseCount = masterData.dProductQty || 1000;
    if (manyData.find(x => x.dManyQty === baseCount)) return;

    const manyDataNew = Array(5)
      .fill("")
      .map((item, index) => ({
        sId: commonUtils.createSid(),
        handleType: "add",
        dManyQty: baseCount * (index + 1),
      }));
    setState(pre => ({
      ...pre,
      manyData: manyDataNew,
      manySelectedRowKeys: [manyDataNew[0].sId],
      dProductQty: baseCount,
      dQuickQuoteProductQty: baseCount,
    }));
    props.onSaveState({
      manyDataCache: [],
    });
    // setSelectedRadio(baseCount+'')
  }, [masterData.dProductQty, manyData.length]);
  useEffect(() => {
    if (calcPriceLoading) {
      setProcessPercent(0);
    }
  }, [calcPriceLoading]);

  // 监听确认下单数量结束
  useEffect(() => {
    if (!loading && submitLoading) {
      setSubmitLoading(false);
    }
  }, [loading]);
  const tableProps = {
    ...commonBusiness.getTableTypes("many", { ...props, ...state }),
    fixedHeight: 185,
    enabled: false,
  };
  const { headerColumn, data } = tableProps;
  // 监听父组件状态变化
  useEffect(() => {
    if (!data.length) return;
    setSelectedRadio(Number(props.state.dQuickQuoteProductQty) || data[0].dProductQty);
  }, [props.state.dQuickQuoteProductQty]); // 直接监听父组件的
  // 核价事件
  const onCalcPrice = () => {
    const { state } = props;
    const { masterData = {}, slaveConfig, slaveData = [], selectedNode = {}, backendConfig = {}, boxModelKey = 0, bestAlgorithm, activeKey } = state;
    const addState = {
      ...props.onGetAllDelData(),
      manyDataCache: [],
    };
    props.onSaveState(
      {
        masterData: { ...props.masterData, handleType: props.handleType || "update" },
        ...addState,
      },
      () => {
        props.handleCalcPrice();
      }
    );
    props.setState(pre => ({ ...pre, onCalcPrices: false }));
  };

  const handleRadioChange = (selectedRowKeys, dManyQty) => {
    const dProductQty = manyData.find(item => item.sId === selectedRowKeys.sId).dManyQty;
    // 这一步导致了点击数量没有变化
    // props.slaveData?.forEach(slaveRowData => {
    //   props.onDataChange0("slave", "dProductQty", { dProductQty }, slaveRowData.sId, [], props);
    // });
    // props.onDataChange(currentBoxModel, "sName", { sName: item.sName }, item.sId, boxsList);
    slaveData?.forEach(slaveRowData => {
      slaveRowData.dProductQty = dProductQty
    }
    )
    props.setState(pre => ({
      ...pre,
      manySelectedRowKeys: [selectedRowKeys.sId],
      dQuickQuoteProductQty: dProductQty,
      slaveData,
      dProductQty,
      calcPriceFinished: false,
      isChangeDProductQty: dManyQty
    }));

    setSelectedRadio(dProductQty);
  };

  const changrManyQty = (item, x) => {
    if (x.dataIndex !== 'dManyQty') return ''
    setValue(item.dManyQty);
    setVisible(true);
    setChangeValue(item);
  };

  const getSize = (num) => {
    return num ? Number(num).toFixed(2) : 0;
  }
  const BtnPriceverification = commonFunc.showLocalMessage(props, "BtnPriceverification", "核价");
  const sNuclearPricing = commonFunc.showLocalMessage(props, "sNuclearPricing", "核价中");
  const BtnConfirmQuantity = commonFunc.showLocalMessage(props, "BtnConfirmQuantity", "确认下单数量");
  data.sort((a, b) => a.dManyQty - b.dManyQty);
  return (
    <div style={{ padding: '0 0' }}>
      <div style={{ marginBottom: "16px", textAlign: "right" }}>
        <Button
          color="primary"
          fill="solid"
          loading={loading || calcPriceLoading}
          loadingText={sNuclearPricing}
          onClick={onCalcPrice}
          size="small"
          style={{ marginRight: "16px" }}
        >
          {BtnPriceverification}
        </Button>
      </div>
      <div className={styles.tableBox}>
        <div style={{ width: "16px" }}></div>
        {headerColumn?.map((item, i) => {
          return <div className={styles.tableHeader} style={{ width: ['dManyPrice', "dMaterialsRate"].includes(item.dataIndex) ? '10%' : '16%' }}>{item.title}</div>;
        })}
      </div>
      <div>
        {data && data.length
          ? data.map(item => {
            return (
              <div className={styles.tableBox}>
                <div style={{ width: "16px", "--icon-size": "22px", "--font-size": "16px", "--gap": "8px", lineHeight: '20px', transform: 'translateX(-10px)' }}>
                  <Radio checked={selectedRadio === item.dManyQty} onClick={() => handleRadioChange(item)} style={{ fontSize: '20px' }} />
                </div>
                {
                  headerColumn.map(x=>{
                    return <div className={styles.tableBody}  onClick={() => changrManyQty(item, x)} style={{ width: ['dManyPrice', "dMaterialsRate"].includes(x.dataIndex) ? '10%' : '16%' }}>{ x.dataIndex === 'dManyQty' ? item[x.dataIndex]: getSize(item[x.dataIndex])}</div>
                  })
                }
              </div>
            );
          })
          : ""}
      </div>
      <div style={{ marginTop: "16px", textAlign: "right" }}>
        <Button
          color="success"
          size="small"
          loading={loading || submitLoading}
          disabled={!calcPriceFinished}
          onClick={() => {
            props.onSaveState(
              {
                ...props.onGetAllDelData(),
                masterData: {
                  ...props.masterData,
                  handleType: props.masterData.handleType || "update",
                  sQuoConfig: JSON.stringify(props.onGetFilterState(state)),
                },
                dQuickQuoteProductQty: state.dQuickQuoteProductQty,
                loading: true,
              },
              (newState) => {
                setSubmitLoading(true);
                props.onSubmit(undefined, {
                  ...props, ...newState, state, manyqtysConfig: state.manyConfig, manyqtysData: state.manyData, manyqtysDelData: state.manyData.map(item => {
                    item.handleType = 'del'
                    return item
                  }),
                });
              }
            );
          }}
        >
          {BtnConfirmQuantity}
        </Button>
      </div>
      <CenterPopup visible={visible}>
        <div className={styles.addTabs}>
          <div>请输入数量：</div>
          <Input
            placeholder="请输入内容"
            clearable
            value={value}
            onChange={val => {
              setValue(val);
            }}
          />
          <div className={styles.addTabsBtn}>
            <Button
              color="primary"
              fill="outline"
              size="small"
              style={{ marginRight: "16px" }}
              onClick={() => {
                setValue("");
                setVisible(false);
              }}
            >
              取消
            </Button>
            <Button
              color="primary"
              fill="solid"
              size="small"
              onClick={() => {
                const i = data.findIndex(item => {
                  return item.sId === changeValue.sId;
                });
                if (i !== -1) {
                  data[i].dManyQty = Number(value);
                  handleRadioChange(data[i], data[i].dManyQty);
                }
                setVisible(false);
                setValue("");
                const iIndex = state.manyData.findIndex(item => item.sId === data[i].sId);
                const rowData = { ...state.manyData[iIndex] };
                state.manyData[iIndex] = {
                  sId: rowData.sId,
                  iRowNum: rowData.iRowNum,
                  sParentId: rowData.sParentId,
                  handleType: rowData.handleType,
                  dManyQty: Number(value),
                };

                props.setState(pre => ({
                  ...pre,
                  calcPriceFinished: false,
                  manyData: state.manyData,
                }));

              }}
            >
              确认
            </Button>
          </div>
        </div>
      </CenterPopup>
    </div>
  );
};
// 后道参数额外配置
const BackendParamsExtraComponent = props => {
  const { state, slaveConfig, boxModel } = props;
  const { backendParamsConfig = [], backendConfig = {}, slaveData, selectedNode, masterData = {} } = state;
  const { sParentFieldsName, sBoxModel } = backendConfig;
  if (!backendParamsConfig.length) return "";
  if (sParentFieldsName !== props.itemDetail.sName) return '';
  if (props.backType !== backendConfig.typeName) return '';
  if (!props.itemDetail.isSelect) return '';
  // 使用 useMemo 缓存计算结果
  const slaveRowData = slaveData.find(item => item.sTreeNodeName === selectedNode.showName && item.sBoxModel === sBoxModel) || {};

  const { sBackProcessData = [] } = slaveRowData;
  const { productProcessInfo = [] } = masterData;

  if (sParentFieldsName !== "sPrint" && ![...sBackProcessData, ...productProcessInfo].some(item => item[sParentFieldsName])) return ""
  const viewConfigs = backendParamsConfig.map((item, index) => ({
    ...item,
    // sName0: `sParam${item.iOrder}`,
    sName: item.sFieldName || `sParam${item.iOrder}`,
    showName: item.sParam,
    sDropDownType: item.sParamDropDown ? "sql" : "",
    iColValue: 4,
    sVisColumnName: "sProcessName",
    value: item.sId,
    label: item.sParamDefault,
  }));

  const viewProps = {
    ...props,
    viewConfigs: viewConfigs.map(item => ({
      ...item,
      costomStyle: styles.sParamConfig,
    })),
    tableConfig: { ...slaveConfig, gdsconfigformslave: viewConfigs },
    iColValueView: 24,
    sBackProcessData: [...sBackProcessData, ...productProcessInfo],
    sParentFieldsName,
    viewRow: { sId: slaveRowData.sId },
    getViewRow: config => {
      if (sParentFieldsName === "sPrint") {
        return [slaveRowData, ...sBackProcessData].find(item => item.sId === printParamsId);
      }
      return (
        [...sBackProcessData, ...productProcessInfo]
          .find(item => item[sParentFieldsName])
          ?.sBackendParams?.find(item => item.sParam === config.showName) || {}
      );
    },
    tableName: `sBackendParams${boxModel}`,
    getSqlDropDownData: async (...args) => {
      const showConfig = args[2];
      const { sDropDownType, sParamDropDown = "", sName, sFieldName } = showConfig;
      if (sDropDownType === "sql" && sParamDropDown?.toLowerCase()?.includes("select")) {
        args[2] = {
          ...showConfig,
          showDropDown: sParamDropDown,
        };
        delete args[2].sId;
        const result = await props.getSqlDropDownData(...args);
        const { dropDownData } = result;
        const temp = {
          ...result,
          dropDownData: dropDownData.map(item => ({
            ...item,
            // sId: item.sValue,
            value: item.sValue,
            sParam: showConfig.sParam,
            [sName]: item.sValue,
            sParamKey: sName,
            sFieldName,
          })),
        };
        return temp;
      }
      const dropDownData = sParamDropDown.split(",");
      if (dropDownData?.length) {
        return {
          dropDownData: dropDownData.map(item => ({
            sId: item,
            value: item,
            sParam: showConfig.sParam,
            [sName]: item,
            sParamKey: sName,
          })),
          totalPageCount: 1,
          currentPageNo: 1,
          conditonValues: {},
        };
      }

      return props.getSqlDropDownData(...args);
    },
    onDataChange: (name, sFieldName, changeValue, sId, dropDownData, isWait) => {
      const extraState = {
        calcPriceFinished: false,
      };
      const iIndex = slaveData.findIndex(item => item.sId === slaveRowData.sId);
      if (sParentFieldsName === "sPrint") {
        if (slaveData[iIndex].sId === printParamsId) {
          let slaveDataNew = [...slaveData];
          slaveDataNew[iIndex] = { ...slaveDataNew[iIndex], ...changeValue };
          props.setState(pre => ({ ...pre, slaveData: slaveDataNew }));
        } else {
          const iIndex1 = sBackProcessData.findIndex(item => item.sId === printParamsId);
          let sBackProcessDataNew = [...sBackProcessData];
          sBackProcessDataNew[iIndex1] = { ...sBackProcessDataNew[iIndex1], ...changeValue };
          slaveData[iIndex].sBackProcessData = sBackProcessDataNew;
          props.setState(pre => ({ ...pre, slaveData, ...extraState }));
        }
        return '';
      }
      const sBData = sBoxModel ? slaveData[iIndex].sBackProcessData : productProcessInfo;
      const iIndex1 = sBData.findIndex(item => item[sParentFieldsName]);
      const showConfig = viewConfigs.find(item => item.sName === sFieldName);
      let dropDownDataSelected = dropDownData?.length
        ? dropDownData.find(item => item.sId === changeValue.sId)
        : {
          sId: commonUtils.createSid(),
          value: changeValue.label || changeValue[sFieldName],
          sParam: showConfig.sParam,
          sParamKey: sFieldName,
        };
      if (isWait) {
        dropDownDataSelected = {
          ...changeValue,
          value: changeValue.label || changeValue.sValue,
          sParamKey: sFieldName,
          sParam: showConfig.sParam,
        }
      }
      if (!dropDownDataSelected) return '';
      dropDownDataSelected[sFieldName] = dropDownDataSelected.value || dropDownDataSelected.sValue;
      const { sParam } = dropDownDataSelected;
      const { sBackendParams = [] } = sBData[iIndex1];
      const iIndex2 = sBackendParams.findIndex(item => item.sParam === sParam);
      if (iIndex2 !== -1) {
        sBackendParams[iIndex2] = dropDownDataSelected;
      } else {
        sBackendParams.push(dropDownDataSelected);
      }
      sBData[iIndex1].sBackendParams = sBackendParams;
      if (!showConfig.sName?.startsWith("sParams")) {
        sBData[iIndex1][showConfig.sName] = dropDownDataSelected[showConfig.sName];
        const { dManualLength, dManualWidth } = sBData[iIndex1];
        if (dManualLength !== undefined && dManualWidth !== undefined) {
          sBData[iIndex1].dManualValue = dManualLength * dManualWidth;
        }
      }

      if (sBoxModel) {
        slaveData[iIndex].sBackProcessData = sBData;
        props.setState(pre => ({ ...pre, slaveData, ...extraState }));
      } else {
        masterData.productProcessInfo = sBData;
        props.setState(pre => ({ ...pre, masterData, ...extraState }));
      }
    },
  };

  if (!viewConfigs.length) return '';
  const longestConfig = viewProps.viewConfigs.reduce((prev, current) =>
    current.showName.length > prev.showName.length ? current : prev
  );

  return (
    <div>
      <div>
        <Grid columns={3} gap={8}>
          {viewProps.viewConfigs.map(x => (
            <Grid.Item>
              <div className={styles.customer} key={x.id || x.showName}>
                <div style={{ height: longestConfig?.showName?.length > 5 ? 50 : '' }}>{x.showName}</div>
                <SelectInput
                  {...viewProps}
                  itemDetail={x}
                  getSqlDropDownData={viewProps.getSqlDropDownData}
                  onDataChange={viewProps.onDataChange}
                  onCostomClick={null}
                />
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
    </div>
  );
};
export default QuotationAllprogressDetail;
