/* eslint-disable */
import { useRef, useEffect, useState, useCallback, useMemo } from "react";
import { Tabs, Selector, Grid, Image, Button, Checkbox, Switch, Dialog, Toast } from "antd-mobile";
import { AddOutline, MinusOutline } 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 JsonData from "./index.json";
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";
const QuickQuoteEvent = props => {
  const { location } = props;
  const selectedNode = JSON.parse(location.state).quotationData;
  const addState = {};
  const [masterConfig, setMasterConfig] = useState(null);
  const { sModelsId } = props;

  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 = [] } = state;
  const { bLinkFieledClick } = props;
  const [hideBackBtn, setHideBackBtn] = useState(false);
  const [enabled, setEnabled] = useState(props.enabled);
  useEffect(() => {
    setState(pre => ({ ...pre, selectedNode }));
  }, []);
  useEffect(() => {
    setHideBackBtn(!bLinkFieledClick);
    setEnabled(!bLinkFieledClick || props.enabled);
  }, [bLinkFieledClick, props.enabled]);
  useEffect(() => {
    // 获取 masterConfig
    const configUrl = `${commonConfig.server_host}business/getModelBysId/${"172129113112117428019179600"}?sModelsId=${"172129113112117428019179600"}`;
    commonServices
      .getService(props.app.token, configUrl)
      .then(({ data: configReturn }) => {
        if (configReturn.code === 1) {
          const formData = configReturn.dataset.rows[0]?.formData;
          setMasterConfig(formData);
          setState(pre => ({ ...pre, masterConfig: formData, slaveConfig: formData[1] }));
        }
      })
      .catch(error => {});
    const formDataUrl = `${commonConfig.server_host}business/getModelBysId/${sModelsId}?sModelsId=${sModelsId}`;
    commonServices
      .getService(props.app.token, formDataUrl)
      .then(({ data: formDataReturn }) => {
        if (formDataReturn.code === 1) {
          const formDatas = formDataReturn.dataset.rows[0]?.formData;
          setState(pre => ({ ...pre, formData: formDatas }));
        }
      })
      .catch(error => {});
  }, []);

  // 获取盒型定义配置
  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 { masterData = {}, slaveData = [], selectedNode = {} } = state;

    const extraState = {
      calcPriceFinished: false,
      manyData: [],
    };

    if (name === "master") {
      const masterDataNew = { ...masterData, ...changeValue };
      masterDataNew.handleType = masterDataNew.handleType || "update";
      masterDataNew.sId = masterDataNew.sId || commonUtils.createSid();
      if (sFieldName === "dProductQty") {
        setState(pre => ({
          ...pre,
          dProductQty: changeValue.dProductQty,
        }));
      }

      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[sFieldName]);
        dropDownDataSelected && (dropDownDataSelected[sFieldName] = dropDownDataSelected.sProcessName);
        const extraRowData = {};
        // if (dropDownDataSelected.sProcessName === "胶印") {
        //   extraRowData.sPrintProcessId = dropDownDataSelected.sId;
        // }
        if (iIndex === -1) {
          slaveData.push({
            sId: commonUtils.createSid(),
            handleType: "add",
            sBoxModel: boxModel,
            sTreeNodeName,
            sBackProcessData: dropDownDataSelected === undefined ? [] : [dropDownDataSelected],
            ...extraRowData,
          });
        } else {
          const sBackProcessData = slaveData[iIndex].sBackProcessData || [];
          const iIndex1 = sBackProcessData.findIndex(item => item.sProductClassifyId === dropDownData[0].sProductClassifyId);
          if (iIndex1 === -1) {
            dropDownDataSelected !== undefined && sBackProcessData.push(dropDownDataSelected);
          } else {
            if (dropDownDataSelected === undefined) {
              sBackProcessData.splice(iIndex1, 1);
            } else {
              sBackProcessData[iIndex1] = dropDownDataSelected;
            }
          }
          slaveData[iIndex].sBackProcessData = sBackProcessData;

          slaveData[iIndex] = {
            ...slaveData[iIndex],
            ...extraRowData,
            handleType: slaveData[iIndex].handleType || "update",
          };
        }
      } else {
        if (iIndex === -1) {
          slaveData.push({
            ...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]),
        };
      }

      setState(pre => ({ ...pre, slaveData, ...extraState }));
    } else if (name === "finished") {
      const { productProcessInfo = [] } = masterData;
      const dropDownDataSelected = dropDownData.find(item => item.sId === changeValue[sFieldName]);
      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 = 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("请先填写客户名称和产品名称");
      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",
          };
        }),
        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,
      },
      () => {
        props.onButtonClick("BtnDraft");
      }
    );
  };

  addState.onSaveDraft = onSaveDraft;

  // 核价按钮
  addState.handleCalcPrice = async () => {
    const { masterData = {}, slaveData = [], selectedNode = {}, extraParts = {} } = state;

    if (commonUtils.isEmptyObject(selectedNode)) {
      message.error("请先选择产品");
      return;
    }
    const mustFieldsMap = {
      sCustomerName: "请先选择客户名称",
      sProductName: "请先输入产品名称",
      sProductUnit: "请先输入产品单位",
      dLength: "请先输入长度",
      dWidth: "请先输入宽度",
      dProductQty: "请先输入数量",
    };

    const checkResult = Object.keys(mustFieldsMap).find(item => masterData[item] === undefined);
    if (checkResult) {
      message.error(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("请至少保证一个部件的材料信息填写完整");
      return;
    }

    setState(pre => ({ ...pre, calcPriceLoading: true, calcPriceFinished: false }));

    const { sModelsId, token, sBoxModel } = props;
    const extraPartsList = extraParts[showName] || [];
    const sAllPartsNameList = [...sAllPartsName.split(","), ...extraPartsList];

    const masterDataNew = {
      ...masterData,
      cpProcessName: masterData.cpProcessName || "",
      productProcessInfo: masterData.productProcessInfo?.map(item => ({ ...item, sProcessId: item.sId })) || [],
      sProductClassifyId: sId,
      sProductName1: masterData.sProductName,
      dProductWidth: masterData.dWidth,
      dProductLength: masterData.dLength,
      dProductHeight: masterData.dHeight,
      sProductStyle:
        masterData.dHeight !== undefined
          ? `${masterData.dLength}*${masterData.dWidth}*${masterData.dHeight}`
          : `${masterData.dLength}*${masterData.dWidth}`,
    };
    const paramMap = {
      bQuotation: true,
      ...masterDataNew,
      product: masterDataNew,
      sPartsStyle: "",
      partsInfo: sAllPartsNameList
        .map(partName => {
          const temp = {
            ...slaveData.find(item => item.sTreeNodeName === showName && item.sBoxModel === partName),
          };
          return temp;
        })
        .filter(item => commonUtils.isNotEmptyObject(item) && item.materialsInfo && item.materialsInfo.length)
        .map(item => {
          return {
            ...Object.keys(item).reduce((pre, cur) => {
              if (typeof item[cur] !== "object") {
                pre[cur] = item[cur];
              }
              return pre;
            }, {}),
            dPartsQty: masterData.dProductQty,
            iPositiveColor: Number(item.sColor),
            sPartsName: item.sBoxModel,
            materialsInfo: item.materialsInfo?.filter(x => commonUtils.isNotEmptyObject(x)),
            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 url = `${commonConfig.server_host}calculationStd/countMoney?sModelsId=${sModelsId}`;
    const dataReturn = (await commonServices.postValueService(token, paramMap, url)).data;

    if (dataReturn.code === 1) {
      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}` });
          }
        });
      }
      if (errorFlag) {
        setState(pre => ({ ...pre, calcPriceLoading: false }));
        return;
      }

      // 返回数据赋值
      const { slaveData: stateSlaveData = [] } = state;
      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;
        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 result = await props.handleCalculation(
        false,
        { ...props, ...newState, manyqtysConfig: state.manyConfig, manyqtysData: state.manyData },
        true
      );

      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, () => {
          onSaveDraft(preNew, stateNew);
        });
        return preNew;
      });
    } else {
      message.error(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,
    masterConfig: masterConfig && masterConfig.length ? masterConfig[0] : {},
  };
};

const QuotationAllprogressDetail = baseProps => {
  // const props = QuickQuoteEvent(baseProps);
  const [state, setState] = useState(JsonData.state);
  const props = {
    ...baseProps,
    ...JsonData,
    setState,
    state,
  };
  return (
    <div className={styles.quotationDetailBox}>
      <QuotationDetail {...props} />
    </div>
  );
};

const QuotationDetail = props => {
  const { location, app, sModelsId, state, masterData, selectedNode = {} } = props;
  const { token } = app;
  const { formData = [], masterConfig } = state || {};
  const { quotationData } = JSON.parse(location.state) || {};
  if (!masterConfig) return;
  //masterData 主表数据
  // 获取主表信息
  const viewConfigs = masterConfig.gdsconfigformslave.filter(item => item.sName && item.bVisible);
  const viewProps = {
    ...props,
    viewConfigs: viewConfigs,
    tableConfig: masterConfig,
    iColValueView: 24,
    viewRow: { ...masterData, sProductClassifyId: selectedNode.sId },
    tableName: "master",
  };

  return (
    <div>
      <div>{quotationData?.showName || "Loading..."}</div>

      <div>
        <MasterComponent {...viewProps} />
      </div>
      <div>
        <QuotationTabs {...props} />
      </div>
    </div>
  );
};
const MasterComponent = props => {
  const { viewConfigs, masterData } = props;

  const customer = viewConfigs?.find(x => x.sName === "sCustomerName") || {};
  const customerProps = {
    ...props,
    itemDetail: customer,
    sValue: masterData.sCustomerName,
    id: masterData.sCustomerId,
    No: masterData.sCustomerNo,
  };
  const product = viewConfigs?.find(x => x.sName === "sProductName") || {};
  const productProps = {
    ...props,
    itemDetail: product,
    bCanInput: true,
    sValue: masterData.sProductName,
  };
  const dLength = viewConfigs?.find(x => x.sName === "dLength") || {};

  const dLengthProps = {
    ...props,
    itemDetail: dLength,
    bCanInput: true,
    sValue: masterData.dLength,
  };
  const dWidth = viewConfigs?.find(x => x.sName === "dWidth") || {};
  const dWidthProps = {
    ...props,
    itemDetail: dWidth,
    bCanInput: true,
    sValue: masterData.dWidth,
  };
  const dHeight = viewConfigs?.find(x => x.sName === "dHeight") || {};
  const dHeightProps = {
    ...props,
    itemDetail: dHeight,
    bCanInput: true,
    sValue: masterData.dHeight,
  };
  const dProductQty = viewConfigs?.find(x => x.sName === "dProductQty") || {};
  const dProductQtyProps = {
    ...props,
    itemDetail: dProductQty,
    bCanInput: true,
    sValue: masterData.dProductQty,
  };
  const sProductUnit = viewConfigs?.find(x => x.sName === "sProductUnit") || {};
  const sProductUnitProps = {
    ...props,
    itemDetail: sProductUnit,
    sValue: masterData.sProductUnit,
  };
  const sDeliverName = viewConfigs?.find(x => x.sName === "sDeliverName") || {};
  const sDeliverNameProps = {
    ...props,
    itemDetail: sDeliverName,
    sValue: masterData.sDeliverName,
  };
  const baseProps = {
    ...props,
  };
  return (
    <div>
      <div className={styles.customer}>
        <div>{customerProps.formData.showName}</div>
        <SelectInput {...customerProps} />
      </div>
      <div className={styles.customer}>
        <div>{productProps.formData.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} />
            </div>
            <div style={{ width: "30%", textAlign: "center" }}>X</div>
          </div>
          <div className={styles.sizeItem}>
            <div style={{ width: "70%" }}>
              <SelectInput {...dWidthProps} />
            </div>{" "}
            <div style={{ width: "30%", textAlign: "center" }}>X</div>
          </div>
          <div className={styles.sizeItem}>
            <div style={{ width: "70%" }}>
              <SelectInput {...dHeightProps} />
            </div>
            <div style={{ width: "30%", textAlign: "center" }}>mm</div>
          </div>
        </div>
      </div>
      <div className={styles.sizeBox}>
        <div className={styles.customer}>
          <div>数量</div>
          <SelectInput {...dProductQtyProps} />
        </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 sAllPartsName = selectedNode?.sAllPartsName;
  const sAllPartsNameList = sAllPartsName?.split(",");
  const [activeKey, setActiveKey] = useState(sAllPartsNameList && sAllPartsNameList.length ? sAllPartsNameList[0] : null);

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

  const tabsProps = {
    ...props,
    boxModel: activeKey,
  };
  return (
    <Tabs
      activeKey={activeKey}
      onChange={key => {
        setActiveKey(key);
      }}
    >
      {sAllPartsNameList && sAllPartsNameList.length
        ? sAllPartsNameList.map((pane, index) => (
            <Tabs.Tab key={pane} title={pane}>
              <BoxComponent {...tabsProps} paneKey={pane} />
            </Tabs.Tab>
          ))
        : ""}
    </Tabs>
  );
};

// 内容
const BoxComponent = props => {
  const { state, boxModel } = props;
  const { activeKey, slaveConfig, masterData, selectedNode, boxConfig, downAbleConfigs = [], slaveData } = state || {};
  const { sModelsId } = props;
  const [selectList, setSelectList] = useState([]);
  const [boxTypeList, setBoxTypeList] = useState([]);
  const [searchValue, setSearchValue] = useState("");
  const [slaveRowData, setSlaveRowData] = useState(null);
  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: 20,
    };
    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);
      }
    });
    // 获取盒型
  }, []);

  useEffect(() => {
    props.setState(prevState => ({
      ...prevState,
      slaveRowData,
    }));
  }, [slaveRowData]);

  useEffect(() => {
    // changeBox()
    if (selectList.length <= 0) return;
    const boxModelData = slaveData.find(x=>x.sBoxModel === boxModel)
    const selectListDetail = selectList.find(x=>x.sName === boxModelData?.sName)
    setSelected(selectListDetail?.sBoxType);
    changeBox(selectListDetail)
  }, [slaveData, selectList]);
  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 (slaveRowData && slaveRowData.sColumnNameConfig && masterData.dLength && masterData.dWidth && masterData.dHeight) {
    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,
  };
  // 印刷参数
  // if (!slaveConfig) return;
  const getUpViewPropsByITag = iTag => {
    if (!slaveConfig) return;
    const config = slaveConfig.gdsconfigformslave.filter(item => {
      if (item.sName === "dSumPQty" && selectedNode.sTypeKey !== "huace") {
        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}`,
    };
  };

  // 印刷参数表单
  const upViewProps12 = getUpViewPropsByITag(12);
  // 拼板信息表单
  const upViewProps20 = getUpViewPropsByITag(20);

  // 后道参数
  const downViewProps = {
    ...props,
    viewConfigs: downAbleConfigs
      .filter(item => item.sPartsName === boxModel || !item.sPartsName)
      .map(item => {
        return {
          ...item,
          isSelect: false,
        };
      }),
    tableConfig: { ...slaveConfig, gdsconfigformslave: downAbleConfigs },
    iColValueView: 24,
    viewRow: slaveRowData,
    tableName: `slaveDown${boxModel}`,
  };
  const calcMethodData = commonUtils.convertStrToObj(slaveRowData?.sColumnNameConfigExclusion, []);
  const radioValue = calcMethodData[0]?.sCode;
  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) / (slaveData[index].dWlcd * slaveData[index].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,
    // 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 changeBox = item => {
    // if (!item) return
    const data = selectList.find(x => x.sId === item.sId);
    if (!data) return;
    const slaveNewData = JSON.parse(data.sColumnNameConfig).map(x => {
      return {
        [x.sName]: x.sDefault,
      };
    });
    const slaveDataDetail = slaveData.find(item => item.sTreeNodeName === selectedNode.showName && item.sBoxModel === boxModel) || {};
    
    const rowData = {
      ...slaveDataDetail,
      ...data,
      ...Object.assign({}, ...slaveNewData),
    };
    setSlaveRowData(rowData);
    setBoxPopup(false);
  };
  return (
    <div>
      <Selector
        columns={4}
        options={boxTypeList}
        style={{ "--padding": "0.8rem 0" }}
        value={selected ? [selected] : []}
        onChange={v => handleChange(v)}
      />
      <div>
        <Grid columns={4} gap={8}>
          {showUpAbleConfigsExtra.map(x => (
            <Grid.Item>
              <div className={styles.customer} key={x.id || x.sBig5}>
                <div>{x.sBig5}</div>
                <SelectInput {...props} {...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>
        <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>
        <div>拼版信息</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={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>
      <div>
        <MaterialsComponent {...props} />
      </div>
      <div>
        <div>后道参数</div>
        {downViewProps.viewConfigs.map((x, i) => (
          <div>
            {x.showName}
            <Switch
              onChange={async val => {
                console.log(val, x, "val");
              }}
            />
          </div>
        ))}
      </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={changeBox(item)}>
                    选择
                  </Button>
                </div>
              );
            })}
          </div>
        }
      ></Dialog>
    </div>
  );
};

// 材料组件
const MaterialsComponent = props => {
  const { state, boxModel } = props;
  const { slaveRowData, slaveConfig, slaveData = [], selectedNode = {} } = state;
  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 || "" };
    let materialsConfigNew = JSON.parse(JSON.stringify(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);
        if (iIndex !== -1) {
          slaveData[iIndex].materialsInfo = materialsInfo.map((item, i) => (i === index ? { ...item, ...changeValue } : item));
        } else {
          const { selectedNode = {} } = state;
          const { showName: sTreeNodeName } = selectedNode;
          slaveData.push({
            sId: commonUtils.createSid(),
            handleType: "add",
            sBoxModel: boxModel,
            sTreeNodeName,
            materialsInfo: materialsInfo.map((item, i) => (i === index ? { ...item, ...changeValue } : item)),
          });
        }

        props.setState(pre => ({ ...pre, slaveData, ...extraState }));
      },
    };

    return (
      <div>
        材料信息
        <div className={styles.materialsLine}>
          <div className={styles.selectInput} style={{ width: "50%" }}>
            <SelectInput {...viewProps} />
          </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,
                  });
                }
                props.setState(pre => ({ ...pre, slaveData, ...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" }
              }
            >
              <AddOutline />
            </Button>
          </div>
        </div>
      </div>
    );
  });
};
// 多数量组件
const ManyComponent = props => {
  const { state, setState, enabled, loading } = props;
  const { masterData = {}, calcPriceLoading, calcPriceFinished, manyData = [] } = state;
  const [submitLoading, setSubmitLoading] = useState(false);
  const [processPercent, setProcessPercent] = useState(0);
  const tableProps = {
    ...commonBusiness.getTableTypes("many", { ...props, ...state }),
    fixedHeight: 185,
    enabled: false,
  };
  const { headerColumn, data } = tableProps;
  return (
    <div>
      <div className={styles.tableBox}>
        {headerColumn.map(item => {
          return <div className={styles.tableHeader}>{item.title}</div>;
        })}
      </div>
      <div>
        {data.map(item => {
          return (
            <div className={styles.tableBox}>
              <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>
  );
};
export default QuotationAllprogressDetail;
