import { useRef, useEffect, useState, useCallback, useMemo } from "react";
import { history } from "umi";
import { Toast, Input, Tabs, Selector, Grid, Image, Button, Checkbox, Switch, Dialog, Radio, Space, CenterPopup } 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";
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 = [] } = 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;
    });

    return { ...result, 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]);

  addState.onBackClick = () => {
    props.onSaveState({ masterData: { ...props.masterData, sQuoConfig: JSON.stringify(addState.onGetFilterState(state)) }, quickQuoteModel: false });
  };

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

    if (name === "master") {
      let masterDataNew = { ...masterData, ...changeValue };
      masterDataNew.handleType = masterDataNew.handleType || "update";
      masterDataNew.sId = commonUtils.createSid();
      if (sFieldName === "dProductQty") {
        setState(pre => ({
          ...pre,
          dProductQty: changeValue.dProductQty,
        }));
      }
      if (sFieldName === "sCustomerName") {
        masterDataNew = { ...masterDataNew, sCustomerId: changeValue.sId };
      }
      setState(pre => ({ ...pre, masterData: masterDataNew, ...extraState }));
    } else if (name.includes("slave")) {
      const boxModel = name.replace("slaveUp", "").replace("slaveDown", "");
      if (sFieldName === "sName") {
        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;
        changeValue = {
          ...changeValue,
          ...defaultData,
          ...dropDownDataSelected,
          upAbleConfigsExtra,
          calcMethodData: commonUtils.convertStrToObj(sColumnNameConfigExclusion, []),
          boxPicData: commonUtils.convertStrToObj(sColumnNameConfigPic, []),
        };
      }

      const { selectedNode = {}, slaveConfig } = state;
      const { showName: sTreeNodeName } = selectedNode;
      const iIndex = slaveData.findIndex(item => item.sTreeNodeName === sTreeNodeName && item.sBoxModel === boxModel);
      if (name.includes("slaveDown")) {
        const dropDownDataSelected = dropDownData.find(item => item.sId === changeValue.sId);
        dropDownDataSelected && (dropDownDataSelected[sFieldName] = dropDownDataSelected.sProcessName);
        const extraRowData = {};
        // if (dropDownDataSelected.sProcessName === "胶印") {
        //   extraRowData.sPrintProcessId = dropDownDataSelected.sId;
        // }
        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 };
          const sBackendParams = sParamConfig
            .map((item, index) => {
              const { sParamDefault, sParam } = item;
              return !sParamDefault
                ? ""
                : {
                    sId: commonUtils.createSid(),
                    value: sParamDefault,
                    sParam: sParam,
                    [`sParams${index}`]: sParamDefault,
                  };
            })
            .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.value === dropDownData[0].value);
          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({
            ...changeValue,
            sId: commonUtils.createSid(),
            handleType: "add",
            sBoxModel: boxModel,
            sTreeNodeName,
          });
        } else {
          slaveData[iIndex] = {
            ...(sFieldName === "sName"
              ? {
                  sId: slaveData[iIndex].sId,
                  sBoxModel: boxModel,
                  sTreeNodeName,
                  ...commonFunc.getDefaultData(slaveConfig),
                }
              : 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: slaveData[saveIndex].dProductQty ? slaveData[saveIndex].dProductQty : masterData.dProductQty,
      };
      if (sFieldName === "dWlcd" || sFieldName === "dWlkd") {
        const horizontalBoxes = Math.floor(slaveData[saveIndex]?.dWlkd / slaveData[saveIndex]?.materialWidth);
        const verticalBoxes = Math.floor(slaveData[saveIndex]?.dWlcd / slaveData[saveIndex]?.materialLength);
        const newDMaterialsKQty = horizontalBoxes * verticalBoxes;
        slaveData[saveIndex] = {
          ...slaveData[saveIndex],
          dMachineQty: Math.floor(slaveData[saveIndex].dMachineQty / slaveData[saveIndex].dSinglePQty),
          dMaterialsKQty: newDMaterialsKQty,
        };
      }

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

      if (sFieldName === "sPrint") {
        slaveData[saveIndex] = {
          ...slaveData[saveIndex],
          sProcessId: changeValue.sId,
          sPrintProcessId: changeValue.sId,
          dMachineWidth: slaveData[saveIndex].dWlkd,
          dMachineLength: slaveData[saveIndex].dWlcd,
        };
      }

      if (sFieldName === "dMaxLength") {
        slaveData[saveIndex] = {
          ...slaveData[saveIndex],
          dMaxLength: changeValue.dMachineLength,
          dMaxWidth: changeValue.dMachineWidth,
        };
      }
      setState(pre => ({ ...pre, slaveData, ...extraState }));
    } else if (name === "finished") {
      const { productProcessInfo = [] } = masterData;
      const dropDownDataSelected = dropDownData.find(item => item.sId === changeValue.sId);
      dropDownDataSelected && (dropDownDataSelected[sFieldName] = dropDownDataSelected.sProcessName);
      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 = commonUtils.createSid(); // 目前默认是新增
      setState(pre => ({ ...pre, masterData: masterDataNew, ...extraState }));
    }
  };

  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.map(item => ({ ...item, handleType: "del" }))],
      controlDelData: [...controlDelDataOld, ...controlData.map(item => ({ ...item, handleType: "del" }))],
      materialsDelData: [...materialsDelDataOld, ...materialsData.map(item => ({ ...item, handleType: "del" }))],
      processDelData: [...processDelDataOld, ...processData.map(item => ({ ...item, handleType: "del" }))],
      manyqtysDelData: [...manyqtysDelDataOld, ...manyqtysData.map(item => ({ ...item, handleType: "del" }))],
      colorDelData: [...colorDelDataOld, ...colorData.map(item => ({ ...item, handleType: "del" }))],
      packDelData: [...packDelDataOld, ...packData.map(item => ({ ...item, handleType: "del" }))],
    };
    return addState;
  };

  // 存草稿
  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;

  // 核价按钮
  addState.handleCalcPrice = async () => {
    const { masterData = {}, slaveData = [], selectedNode = {}, extraParts = {} } = state;
    if (commonUtils.isEmptyObject(selectedNode)) {
      // message.error("请先选择产品");
      Toast.show({
        icon: "fail",
        content: "请先选择产品",
      });
      return;
    }
    const mustFieldsMap = {
      sCustomerName: "请先选择客户名称",
      sProductName: "请先输入产品名称",
      sProductUnit: "请先输入产品单位",
      dLength: "请先输入长度",
      dWidth: "请先输入宽度",
      dProductQty: "请先输入数量",
    };

    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 slaveRowDataList =
      slaveData
        .filter(item => item.sTreeNodeName === showName && item.materialsInfo && !item.materialsInfo.some(x => !x.sMaterialsName))
        .filter(item => (bBox ? item.sName : true))
        .filter(item => item.sPrint !== undefined && item.sColor !== undefined && item.iPrintModePo !== undefined) || [];
    if (!slaveRowDataList.length) {
      // message.error("请至少保证一个部件的材料信息填写完整");
      Toast.show({
        icon: "fail",
        content: "请至少保证一个部件的材料信息填写完整",
      });
      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,
      sConsigneeMobile: masterData.sMobile,
      sConsignee: masterData.sContacts,
      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;
            }, {}),
            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)),
            iPrintModePo: Number(item.value),
            processInfo:
              item.sBackProcessData?.map(item => ({
                ...item,
                sProcessId: item.sId,
              })) || [],
          };
        }),
    };
    paramMap.sPartsStyle = (paramMap.partsInfo[0].dPartsLength || 0) + "*" + (paramMap.partsInfo[0].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;
        // 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;
          // 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;
        // 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 newState = {
        materialsConfig,
        masterData: { ...masterData1, ...masterData },
        slaveData,
        controlData,
        materialsData,
        processData,
        fastOrderModalVisible: false,
        quotationAllprogress: 0,
        materialsSelectedRowKeys: [],
        ...addState,
        sInfoArr,
        // bVisiblesInfo: !!commonUtils.isNotEmptyArr(sInfoArr),
        Loading: false,
        // quickQuoteModel: false,
      };
      delete newState.masterData.sQuoConfig;
      const masterProps = {
        ...props,
      };
      setState(pre => ({
        ...pre,
        newNextProps: {
          dQuickQuoteProductQty: state.dQuickQuoteProductQty,
          ...masterProps,
          ...newState,
          manyqtysConfig: state.manyConfig,
          manyqtysData: state.manyData,
        },
      }));

      const result = await props.handleCalculation(
        false,
        { ...masterProps, ...newState, manyqtysConfig: state.manyConfig, manyqtysData: state.manyData },
        true,
        props
      );

      if (commonUtils.isEmptyObject(result)) {
        setState(pre => ({ ...pre, calcPriceLoading: false }));
        return;
      }

      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 };
        props.onSaveState(stateNew, () => {
          // stateNew nextProps
          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, slaveConfig, quotationData, app, sModelsId, masterData } = props;
  const { showName, sUnit } = quotationData;
  const timeRef = useRef(0);

  useEffect(() => {
    const getDropDownData = async props => {
      const showDownConfig = props.state.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);
        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 = {};
        }
        return {
          ...pre,
          ...addState,
          masterData: { sProductName: showName, sProductUnit: sUnit, ...masterData },
          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",
            })),
        };
      });
    };
    getDropDownData(props);
  }, [props.state.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;
  if (!masterConfig) return "";
  const ableConfigs = masterConfig.gdsconfigformslave.filter(item => item.sName && item.bVisible);
  // 处理长宽样式
  const viewConfigs = selectedNode?.bBox && selectedNode.sTypeKey !== "kapai" ? ableConfigs : ableConfigs.filter(x => x.sName !== "dHeight");
  if (selectedNode?.bBox && selectedNode.sTypeKey !== "kapai") {
    viewConfigs.forEach(item => {
      if (item.sName === "dLength" || item.sName === "dWidth") {
        item.iColValue = 4;
      }
    });
  } else {
    viewConfigs.forEach(item => {
      item.iColValue = viewConfigs[0].iColValue;
    });
  }
  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 || "Loading..."}
        <EditFill color="#BFBFBF" style={{ marginLeft: "1rem" }} />
      </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 baseProps = {
    ...props,
  };
  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>尺寸(长*宽*高)</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 className={styles.sizeBox}>
        <div className={styles.customer}>
          <div>数量</div>
          <SelectInput {...dProductQtyProps} bCanInput={true} />
        </div>
        <div className={styles.customer}>
          <div>单位</div>
          <SelectInput {...sProductUnitProps} />
        </div>
        <div className={styles.customer}>
          <div>收货方式</div>
          <SelectInput {...sDeliverNameProps} />
        </div>
      </div>
    </div>
  );
};
const QuotationTabs = props => {
  const { state } = props;
  const { selectedNode } = state;
  const [sAllPartsNameList, setSAllPartsNameList] = useState(selectedNode?.sAllPartsName?.split(",") || []);
  const [activeKey, setActiveKey] = useState(sAllPartsNameList.length ? sAllPartsNameList[0] : null);
  const [visible, setVisible] = useState(false);
  const [value, setValue] = useState("");
  const partsList = selectedNode?.sAllPartsName?.split(",");
  useEffect(() => {
    // 更新父组件的状态
    props.setState(pre => ({ ...pre, boxModel: activeKey }));
  }, [activeKey]);

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

  // 处理添加新标签的逻辑
  const handleAdd = () => {
    // 弹窗
    setVisible(true);
    // const newSAllPartsNameList = [...sAllPartsNameList, '111']; // 创建一个新的数组，包含新增的元素
    // setSAllPartsNameList(newSAllPartsNameList); // 更新状态，触发组件重新渲染
  };

  return (
    <div>
      <div className={styles.tabsBox}>
        <Tabs
          activeKey={activeKey}
          onChange={key => {
            setActiveKey(key);
          }}
        >
          {sAllPartsNameList.length
            ? sAllPartsNameList.map((pane, index) => (
                <>
                  <Tabs.Tab
                    key={pane}
                    title={
                      <div className={styles.tabTitle}>
                        <div>{pane}</div>
                        {partsList.includes(pane) ? (
                          ""
                        ) : (
                          <CloseOutline
                            style={{ marginLeft: "1rem", position: "absolute", top: "0", right: "-2.5rem" }}
                            onClick={() => {
                              const newTabs = sAllPartsNameList.filter(panes => panes !== pane);
                              setSAllPartsNameList(newTabs);
                              // 如果删除的是当前活动的 Tab，选择新的活动 Tab
                              setActiveKey(0);
                            }}
                          />
                        )}
                      </div>
                    }
                  >
                    <BoxComponent {...tabsProps} paneKey={pane} />
                  </Tabs.Tab>
                </>
              ))
            : ""}
        </Tabs>
        <Button
          className={styles.tabAddBtn}
          color="primary"
          fill="solid"
          size="small"
          style={{ width: "1.93rem", height: "1.93rem", 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: "1rem" }}
                onClick={() => {
                  setValue("");
                  setVisible(false);
                }}
              >
                取消
              </Button>
              <Button
                color="primary"
                fill="solid"
                size="small"
                onClick={() => {
                  const newSAllPartsNameList = [...sAllPartsNameList, value]; // 创建一个新的数组，包含新增的元素
                  setSAllPartsNameList(newSAllPartsNameList); // 更新状态，触发组件重新渲染
                  setVisible(false);
                  setValue("");
                }}
              >
                确认
              </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 { 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(null);

  // 获取盒型信息
  useEffect(() => {
    const sId = "17428091410008594700322758474000";
    const url = `${commonConfig.server_host}business/getSelectLimit/${sId}?sModelsId=${sModelsId}&sName=${""}`;
    const body = {
      sSqlCondition: "",
      sKeyUpFilterName: searchValue,
      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);
      }
    });
    // 获取盒型
  }, []);

  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 = [];
  // if(!masterData) return
  if (
    (slaveRowData && slaveRowData.sColumnNameConfig && masterData?.dLength && masterData?.dWidth && masterData?.dHeight) ||
    (selectedNode.sTypeKey === "kapai" && slaveRowData.sColumnNameConfig && masterData.dLength && masterData.dWidth)
  ) {
    const slaveNewData = JSON.parse(slaveRowData.sColumnNameConfig);
    const tables = [
      { name: "盒型类别", value: slaveRowData.sBoxType, type: null },
      { name: "盒身", value: slaveRowData.sBoxBody, type: slaveRowData.sTypes },
      { name: "盒长", value: masterData.dLength ? Number(masterData.dLength) : 0, type: null },
      { name: "盒宽", value: 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(",");
        // 替换公式中的变量为实际值
        const func = new Function(params, `return ${formula}`);
        // 提取变量值
        const args = variableNames.map(name => Number(variables[name]) || 0);
        // 执行函数并返回结果
        return func(...args);
      } catch (error) {
        return 0;
      }
    };

    // 确认是竖向排列还是横向排列
    const L = masterData?.dLength;
    const W = masterData?.dWidth;
    const H = masterData?.dWidth;
    const D = masterData?.dHeight;
    const variables = {
      L,
      W,
      H,
      D,
      ...slaveRowData,
    };
    slaveNewData.forEach(x => {
      let key = 0;
      if (x.sAssignFormula) {
        key = evaluateFormula(x.sAssignFormula, variables);
      } 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 (
          shouldExcludeItem(bAdvancedSetting, ["dPortrait", "dHorizontal"]) ||
          shouldExcludeItem(bFlap, ["dFlap"]) ||
          shouldExcludeItem(bFold, ["sFold", "dAdhesive", "dFold"])
        ) {
          return false;
        }
        if (selectedNode.sTypeKey !== "kapai" && item.sName === "sMagnification") {
          return false;
        }
        return item.iTag === iTag;
      });
    let boxConfigList = [];
    if (iTag === 20) {
      const showNameKeyList = ["dZBLB", "dSBLB", "dYBLB", "dXBLB", "dZBJJ", "dYBJJ", "dSBJJ", "dXBJJ"];
      boxConfigList = boxConfig?.gdsconfigformslave?.filter(item => item.bVisible && showNameKeyList.includes(item.sName)) || [];
    }
    const newConfig = [...boxConfigList, ...config];
    return {
      ...props,
      viewConfigs: newConfig,
      tableConfig: { ...slaveConfig, gdsconfigformslave: newConfig },
      iColValueView: 24,
      viewRow: slaveRowData,
      tableName: `slaveUp${boxModel}`,
    };
  };

  // 印刷参数表单
  let upViewProps12 = getUpViewPropsByITag(12);
  if (upViewProps12 && upViewProps12.viewConfigs && !(selectedNode.sTypeKey === "huace" && slaveRowData.sBoxModel === "封面")) {
    upViewProps12.viewConfigs = upViewProps12.viewConfigs.filter(
      x => x.sName === "sMagnification" || x.sName === "dPartsLength" || x.sName === "dPartsWidth"
    );
  }
  // 拼板信息表单
  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(() => {
    return downAbleConfigs.reduce((pre, cur) => {
      const childConfigs = downAbleExtraConfigs.filter(item => item.sParentName === cur.showName);
      return [...pre, cur, ...childConfigs];
    }, []);
  }, [downAbleConfigs, downAbleExtraConfigs]);

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

  // 初始化状态，存储每个 Switch 的状态
  const [switchStates, setSwitchStates] = useState(null);

  // 处理 Switch 变化的函数
  const handleSwitchChange = (item, val) => {
    setSwitchStates({
      ...switchStates,
      [item.sName]: val,
    });
  };
  // 过滤后的数据
  const 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,
    }));
  const downViewProps = {
    ...props,
    viewConfigs: downViewConfigs,
    tableConfig: { ...slaveConfig, gdsconfigformslave: downAbleConfigs },
    iColValueView: 24,
    viewRow: slaveRowData,
    tableName: `slaveDown${boxModel}`,
  };

  // 获取sType为3的
  // const { productProcessInfo = [] } = masterData;
  // const finishedViewProps = {
  //   ...props,
  //   viewConfigs: finishedConfigs
  //     .filter(item => item.sPartsName === boxModel || !item.sPartsName)
  //     .map((item, i) => ({
  //       ...item,
  //       isSelect: switchStates ? switchStates[item.sName] : false,
  //       // sName: "sParams" + i,
  //       sProductClassifyId: item.sId,
  //     })),
  //   tableConfig: { ...slaveConfig, gdsconfigformslave: finishedConfigs },
  //   iColValueView: 24,
  //   viewRow: masterData,
  //   tableName: "finished",
  // };
  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);
  // 使用 useCallback 确保回调函数的稳定性
  const handleSaveState = useCallback(
    (length, width, slaveData, masterData, dSinglePQty, dMaterialsKQty, dProductQty, scale, dWlcd, dWlkd, innerWidth, innerHeight) => {
      // 查找符合条件的索引
      const { selectedNode } = props.state;

      const index = slaveData?.findIndex(x => x.sTreeNodeName === selectedNode.showName && x.sBoxModel === props.boxModel);
      // 判断展长展宽是否可以放下原纸
      const isDPartsLength =
        slaveData[index]?.dPartsLength < slaveData[index]?.dMaxLength && slaveData[index]?.dPartsWidth < slaveData[index]?.dMaxWidth;

      if (index !== undefined && index !== -1) {
        // 计算开数

        // 获取原始对象并创建一个新的对象进行更新
        const updatedProduct = {
          ...slaveData[index],
          materialLength: length,
          materialWidth: width,
          dMachineLength: length, // 上机长
          dMachineWidth: width, // 上机宽
          sMaterialsStyle: `${slaveData[index]?.dWlcd || 0}*${slaveData[index]?.dWlkd || 0}`, // 原纸尺寸
          sMachineStyle: `${length || slaveData[index].materialLength}*${width || slaveData[index].materialWidth}`, // 开料尺寸为计算的排版尺寸
          sMaterialRate: (((length * width) / (dWlcd * dWlkd)) * 100).toFixed(2),
          newMaterialLength: length,
          newMaterialWidth: width,
          sLayoutRate: Number(
            (
              (((length || slaveData[index].materialLength) * (width || slaveData[index].materialWidth)) /
                (slaveData[index].dMaxLength * slaveData[index].dMaxWidth)) *
              100
            ).toFixed(2)
          ),
          dWlcd: dWlcd,
          dWlkd: dWlkd,
          dMachineQty: Math.floor(dProductQty / dSinglePQty),
          dSinglePQty: dSinglePQty,
          dMaterialsKQty: dMaterialsKQty,
          scale: scale,
          dPartsLength: innerWidth,
          dPartsWidth: innerHeight,
        };
        // 更新状态
        props.setState(prevState => ({
          ...prevState,
          slaveData: slaveData.map((item, i) => (i === index ? updatedProduct : item)),
        }));
      }

      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: 200,
    height: 150,
    size: 9,
  };

  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 getTableCloum = (i, child) => {
    if (!sBackProcessData) return;
    const value = sBackProcessData.find(item => item[child.sName]) || {};
    if (!value) return;
    const { bSetArea, bSetQty, sName, sSetQtyUnt } = value;
    const viewConfigs = [];
    if (bSetArea) {
      viewConfigs.push({
        sName: "dManualLength",
        showName: "x",
        iColValue: bSetQty ? 8 : 12,
        placeholder: "长",
        value: value.dManualLength ? value.dManualLength + "" : "",
      });
      viewConfigs.push({
        sName: "dManualWidth",
        showName: "mm",
        iColValue: bSetQty ? 8 : 12,
        placeholder: "宽",
        value: value.dManualWidth ? value.dManualWidth + "" : "",
      });
    }
    if (bSetQty) {
      viewConfigs.push({
        sName: "dManualQty",
        showName: sSetQtyUnt || "",
        iColValue: bSetArea ? 8 : 24,
        placeholder: "数量",
        value: value.dManualQty ? value.dManualQty + "" : "",
      });
    }
    const viewProps = {
      ...props,
      viewConfigs: viewConfigs,
      tableConfig: { ...slaveConfig, gdsconfigformslave: viewConfigs },
      iColValueView: 24,
      viewRow: value,
      tableName: `slaveDown${boxModel}${sName}`,
    };
    const onDataChange = (name, sFieldName, changeValue) => {
      const iIndex = slaveData.findIndex(item => item.sId === slaveRowData.sId);
      const iIndex1 = slaveData[iIndex].sBackProcessData.findIndex(item => item[child.sName]);

      slaveData[iIndex].sBackProcessData[iIndex1][sFieldName] = changeValue;
      const { dManualLength, dManualWidth } = slaveData[iIndex].sBackProcessData[iIndex1];
      if (dManualLength !== undefined && dManualWidth !== undefined) {
        slaveData[iIndex].sBackProcessData[iIndex1].dManualValue = dManualLength * dManualWidth;
      }
      props.setState(pre => ({ ...pre, slaveData }));
    };
    return viewConfigs.length ? (
      <Grid columns={3} gap={8}>
        {viewProps.viewConfigs.map(x => (
          <Grid.Item>
            <div className={styles.customer} key={x.id || x.showName} style={{ marginTop: "0", display: "flex", alignItems: "center" }}>
              <Input
                placeholder=""
                onChange={e => {
                  onDataChange(viewProps.tableName, x.sName, e, x);
                }}
              ></Input>
              <div style={{ width: "30%", textAlign: "center" }}>{x.showName}</div>
            </div>
          </Grid.Item>
        ))}
      </Grid>
    ) : (
      ""
    );
  };
  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 },
    }));
  };

  useEffect(() => {
    if (selectedNode.sTypeKey === "kapai") {
      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]);

  return (
    <div>
      {selectedNode.bBox ? (
        <div>
          {selectedNode.sTypeKey !== "kapai" ? (
            <div>
              <Selector
                columns={4}
                options={boxTypeList}
                style={{ "--padding": "0.8rem 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>{x.sBig5}</div>
                        <SelectInput {...upViewProps} itemDetail={x} bCanInput={true} />
                      </div>
                    </Grid.Item>
                  ))
                : ""}
            </Grid>
          </div>
          <div className={styles.svgBox}>
            <div style={{ width: "9.375rem", height: "9.375rem" }}>
              <DynamicSVG {...svgProps} />
            </div>
            {slaveRowData && slaveRowData.sPackPath ? <Image src={slaveRowData.sPackPath} width={125} height={125} fit="fill" /> : ""}
          </div>
        </div>
      ) : (
        ""
      )}

      <div>
        <div className={styles.boxTitle}>
          印刷信息
          <EditFill color="#BFBFBF" style={{ marginLeft: "1rem" }} />
        </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>
        {selectedNode.bBox ? (
          <div>
            <div>
              <div className={styles.boxTitle}>
                拼版信息
                <EditFill color="#BFBFBF" style={{ marginLeft: "1rem" }} />
              </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={() => {
                              // if (x.showDropDown) return false;
                              return true;
                            }}
                          />
                        </div>
                      </Grid.Item>
                    ))
                  : ""}
              </Grid>
            </div>
            <div className={styles.svgBox1}>
              <div style={{ width: "49%", height: "49%", position: "relative" }}>
                <Typesetting {...boxProps} onSaveStates={handleSaveState} onSaveDPartsLength={onSaveDPartsLength} />
              </div>
              <div style={{ width: "47%", height: "47%", position: "relative" }}>
                <ShowImgM {...showImgMProps} />
              </div>
            </div>
            <Radio.Group
              value={radioValue}
              onChange={e => {
                const iIndex = slaveData.findIndex(item => item.sId === slaveRowData.sId);
                slaveData[iIndex].radioValue = e;
                props.setState(pre => ({
                  ...pre,
                  slaveData: slaveData,
                }));
              }}
            >
              {calcMethod.map(item => (
                <Radio value={item.value} style={{ marginRight: "0.5rem" }}>
                  {" "}
                  {item.label}
                </Radio>
              ))}
            </Radio.Group>
          </div>
        ) : (
          ""
        )}
      </div>
      <div>
        <MaterialsComponent {...props} slaveRowData={slaveRowData} boxModel={boxModel} />
      </div>
      <div>
        <div className={styles.boxTitle}>
          后道参数
          <EditFill color="#BFBFBF" style={{ marginLeft: "1rem" }} />
        </div>

        {downViewProps && downViewProps.viewConfigs && downViewProps.viewConfigs.length
          ? downViewProps.viewConfigs.map((x, i) => (
              <div>
                <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: "2rem", 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: "1.93rem",
                                height: "1.93rem",
                                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: "1.93rem",
                                height: "1.93rem",
                                display: "flex",
                                justifyContent: "center",
                                alignItems: "center",
                                textAlign: "center",
                              }}
                              onClick={() => {
                                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[x.sName]);
                                  slaveData[slaveRowIndex].sBackProcessData?.splice(iIndex1, 1);
                                  return {
                                    ...pre,
                                    downAbleExtraConfigs: [...downAbleExtraConfigs.slice(0, iIndex), ...downAbleExtraConfigs.slice(iIndex + 1)],
                                    slaveData,
                                  };
                                });
                              }}
                            >
                              <MinusOutline />
                            </Button>
                          )}
                        </div>
                      </div>
                    ) : (
                      ""
                    )}
                  </div>
                </div>
                {getTableCloum(i, x)}
              </div>
            ))
          : ""}
        {finishedConfigs && finishedConfigs.viewConfigs && finishedConfigs.viewConfigs.length
          ? finishedConfigs.viewConfigs.map((x, i) => (
              <div>
                <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: "2rem", width: "40%" }}>
                    {switchStates && switchStates[x.sName] ? (
                      <SelectInput {...downViewProps} itemDetail={{ ...x, sVisColumnName: "sProcessName", sDropDownType: "sql" }} downIndex={i} />
                    ) : (
                      ""
                    )}
                  </div>
                </div>
                {getTableCloum(i, x)}
              </div>
            ))
          : ""}
      </div>
      <BackendParamsExtraComponent {...props} onCostomClick={onCostomClick} />
      <div>
        <div className={styles.projectBtn}>
          <div className={styles.boxTitle} style={{ marginTop: "2rem" }}>
            多数量报价
            <EditFill color="#BFBFBF" style={{ marginLeft: "1rem" }} />
          </div>
        </div>
        <ManyComponent {...props}></ManyComponent>
      </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={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);
                    }}
                  >
                    选择
                  </Button>
                </div>
              );
            })}
          </div>
        }
      ></Dialog>
    </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 };

    const viewProps = {
      ...props,
      viewConfigs: printParamsConfig,
      tableConfig: { ...slaveConfig, gdsconfigformslave: printParamsConfig },
      iColValueView: 24,
      viewRow,
      tableName: `${i === 0 ? "slaveUp" : "slaveDown"}${boxModel}`,
      onDataChange: (...args) => {
        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 };
        });
      },
    };

    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: "1.93rem", height: "1.93rem", display: "flex", justifyContent: "center", alignItems: "center", textAlign: "center" }}
            onClick={() => {
              sBackProcessData.push({
                sId: commonUtils.createSid(),
                bPrintParams: true,
              });
              slaveData[slaveRowDataIndex] = { ...slaveRowData, sBackProcessData };
              setState(pre => {
                return { ...pre, slaveData };
              });
            }}
          >
            <AddOutline />
          </Button>
          {i !== 0 ? (
            <Button
              style={{
                width: "1.93rem",
                height: "1.93rem",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                textAlign: "center",
                marginTop: "0.3rem",
              }}
              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: [],
  };
  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;
        const masterials = {
          sMaterialsName,
          sMaterialsNo,
          sMaterialsId: changeValue.sId,
          sAuxiliaryUnit,
          sMaterialsUnit,
          dGramWeight,
          sMaterialsType,
          dWlkd,
          dWlcd,
        };
        if (iIndex !== -1) {
          slaveData[iIndex].materialsInfo = materialsInfo.map((item, i) => (i === index ? { ...item, ...masterials } : 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, ...masterials } : item)),
          });
        }
        props.setState(pre => ({ ...pre, slaveData, slaveRowData, ...extraState }));
      },
    };

    return (
      <div>
        材料信息
        <div className={styles.materialsLine}>
          <div className={styles.selectInput} style={{ width: "50%" }}>
            <SelectInput {...viewProps} itemDetail={materialsConfigNew[0]} />
          </div>
          <div className={styles.materialBtns}>
            <div className={styles.materialBtns}>
              <span>来料</span>
              <Checkbox />
            </div>
            <Button
              color="primary"
              fill="solid"
              size="small"
              style={{ width: "1.93rem", height: "1.93rem", 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>
            <Button
              style={
                index === 0 || viewRow.showName
                  ? {
                      visibility: "hidden",
                      width: "1.93rem",
                      height: "1.93rem",
                      display: "flex",
                      justifyContent: "center",
                      alignItems: "center",
                      textAlign: "center",
                    }
                  : { width: "1.93rem", height: "1.93rem", 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);
                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 = [], dQuickQuoteProductQty } = state;
  const [submitLoading, setSubmitLoading] = useState(false);
  const [processPercent, setProcessPercent] = useState(0);
  const [selectedRadio, setSelectedRadio] = useState(null);
  // 根据主表数量更改多数量表
  useEffect(() => {
    const baseCount = masterData.dProductQty || 1000;
    if (manyData[0]?.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);
      // window.tempWsAction = ({ data } = {}) => {
      //   const { action, msg } = commonUtils.convertStrToObj(data, {});
      //   if (action === "quotationAllprogress") {
      //     setProcessPercent(msg);
      //   }
      // };
    } else {
      // window.tempWsAction = null;
    }
  }, [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 addState = {
      ...props.onGetAllDelData(),
      manyDataCache: [],
    };
    props.onSaveState(
      {
        masterData: { ...props.masterData, handleType: props.isDraftSaved ? "add" : "update" },
        ...addState,
      },
      () => {
        props.handleCalcPrice();
      }
    );
  };
  const handleRadioChange = selectedRowKeys => {
    const dProductQty = manyData.find(item => item.sId === selectedRowKeys.sId).dManyQty;
    // 这一步导致了点击数量没有变化
    // props.slaveData?.forEach(slaveRowData => {
    //   props.onDataChange0("slave", "dProductQty", { dProductQty }, slaveRowData.sId, [], props);
    // });
   
    props.setState(pre => ({
      ...pre,
      manySelectedRowKeys: selectedRowKeys.sId,
      dQuickQuoteProductQty: dProductQty,
    }));
    setSelectedRadio(dProductQty);
  };
  return (
    <div>
      <div style={{ marginBottom: "1rem", textAlign: "right" }}>
        <Button
          color="primary"
          fill="solid"
          loading={loading || calcPriceLoading}
          loadingText="核价中"
          onClick={onCalcPrice}
          size="small"
          style={{ marginRight: "1rem" }}
        >
          核价
        </Button>
        <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,
              },
              () => {
                setSubmitLoading(true);
                props.onSubmit(undefined, props);
              }
            );
          }}
        >
          确认下单数量
        </Button>
      </div>
      <div className={styles.tableBox}>
        <div style={{ width: "1rem" }}></div>
        {headerColumn.map(item => {
          return <div className={styles.tableHeader}>{item.title}</div>;
        })}
      </div>
      <div>
        {data && data.length
          ? data.map(item => {
              return (
                <div className={styles.tableBox} onClick={() => handleRadioChange(item)}>
                  <div style={{ width: "1rem", "--icon-size": "1.375rem", "--font-size": "1rem", "--gap": "0.5rem" }}>
                    <Radio checked={selectedRadio === item.dManyQty} />
                  </div>
                  <div className={styles.tableBody}>{item.dManyQty}</div>
                  <div className={styles.tableBody}>{item.dPrintMoney}</div>
                  <div className={styles.tableBody}>{item.dAfterProcessMoney}</div>
                  <div className={styles.tableBody}>{item.dMaterialsMoney}</div>
                  <div className={styles.tableBody}>{item.dManyPrice}</div>
                  <div className={styles.tableBody}> {item.dDiscountMoney}</div>
                </div>
              );
            })
          : ""}
      </div>
    </div>
  );
};
// 后道参数额外配置
const BackendParamsExtraComponent = props => {
  const { state, slaveConfig, boxModel } = props;
  const { backendParamsConfig = [], backendConfig = {}, slaveData, selectedNode } = state;
  const { sParentFieldsName, sBoxModel } = backendConfig;
  if (!backendParamsConfig.length) return "";
  // 使用 useMemo 缓存计算结果
  const slaveRowData = slaveData.find(item => item.sTreeNodeName === selectedNode.showName && item.sBoxModel === sBoxModel) || {};

  const { sBackProcessData = [] } = slaveRowData;
  const viewConfigs = backendParamsConfig.map((item, index) => ({
    ...item,
    sName0: `sParam${index + 1}`,
    sName: item.sFieldName || `sParam${index + 1}`,
    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,
    sParentFieldsName,
    getViewRow: config => {
      return sBackProcessData.find(item => item[sParentFieldsName])?.sBackendParams?.find(item => item.sParam === config.showName) || {};
    },
    tableName: `sBackendParams${boxModel}`,
    getSqlDropDownData: (...args) => {
      const showConfig = args[2];
      const { sParamDropDown = "", sName0, sName } = showConfig;
      const dropDownData = sParamDropDown.split(",");
      if (dropDownData?.length) {
        return {
          dropDownData: dropDownData.map(item => ({
            sId: commonUtils.createSid(),
            value: item,
            sParam: showConfig.sParam,
            [sName]: item,
            sParamKey: sName0,
            sParamKeyNew: sName,
          })),
          totalPageCount: 1,
          currentPageNo: 1,
          conditonValues: {},
        };
      }

      return props.getSqlDropDownData(...args);
    },
    onDataChange: (name, sFieldName, changeValue, sId, dropDownData, isWait) => {
      const iIndex = slaveData.findIndex(item => item.sId === slaveRowData.sId);
      const iIndex1 = slaveData[iIndex].sBackProcessData.findIndex(item => item[sParentFieldsName]);
      const showConfig = viewConfigs.find(item => item.sName === sFieldName);
      let extraState = {};

      const dropDownDataSelected = dropDownData?.length
        ? dropDownData.find(item => item.label === changeValue[sFieldName])
        : {
            sId: commonUtils.createSid(),
            value: changeValue[sFieldName],
            sParam: showConfig.sParam,
            [sFieldName]: changeValue[sFieldName],
            sParamKey: showConfig.sName0,
            sParamKeyNew: sFieldName,
          };
      const { sParam } = dropDownDataSelected;
      const { sBackendParams = [] } = slaveData[iIndex].sBackProcessData[iIndex1];
      const iIndex2 = sBackendParams.findIndex(item => item.sParam === sParam);
      if (iIndex2 !== -1) {
        sBackendParams[iIndex2] = dropDownDataSelected;
      } else {
        sBackendParams.push(dropDownDataSelected);
      }
      slaveData[iIndex].sBackProcessData[iIndex1].sBackendParams = sBackendParams;
      if (!showConfig.sName?.startsWith("sParams")) {
        slaveData[iIndex].sBackProcessData[iIndex1][showConfig.sName] = dropDownDataSelected[showConfig.sName];
        const { dManualLength, dManualWidth } = slaveData[iIndex].sBackProcessData[iIndex1];
        if (dManualLength !== undefined && dManualWidth !== undefined) {
          slaveData[iIndex].sBackProcessData[iIndex1].dManualValue = dManualLength * dManualWidth;
        }
      }

      const itemDetail = viewProps.viewConfigs.find(x => x.sName === sFieldName);
      props.setState(pre => ({ ...pre, slaveData }));
      // props.onCostomClick(itemDetail);
    },
  };

  if (!viewConfigs.length) return;
  return (
    <div>
      <div className={styles.boxTitle}>
        后道参数额外配置
        <EditFill color="#BFBFBF" style={{ marginLeft: "1rem" }} />
      </div>
      <div>
        <Grid columns={3} gap={8}>
          {viewProps.viewConfigs.map(x => (
            <Grid.Item>
              <div className={styles.customer} key={x.id || x.showName}>
                <div>{x.showName}</div>
                <SelectInput
                  {...viewProps}
                  itemDetail={x}
                  getSqlDropDownData={viewProps.getSqlDropDownData}
                  onDataChange={viewProps.onDataChange}
                  onCostomClick={null}
                />
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
    </div>
  );
};
export default QuotationAllprogressDetail;
