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

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

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

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

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

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

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

  const onSaveState = (updateFunction, callback) => {
    setState(prevState => {
      let newState = prevState;
      if (typeof updateFunction === "function") {
        newState = updateFunction(prevState);
      }
      if (typeof callback === "function") {
        callback(newState);
      }
      return { ...newState };
    });
  };

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

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

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

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

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

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

  return {
    ...props,
    selectedNode: quotationData,
    manyDataCache: [],
    token,
    getSqlDropDownData,
    onMaterialsChange: handleMaterialsChange,
    sortData,
    handleCalculation,
    onSaveState,
    onSaveData: handleSaveData,
    onButtonClick: handleButtonClick,
    ...state,
  };
};

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

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

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

  const cacheIndex = dQuickQuoteProductQty === undefined ? -1 : manyDataCache.findIndex(item => item.dManyQty === dQuickQuoteProductQty);
  if (cacheIndex === -1) {
    // message.warning("自动计算中，请稍后再试。");
    Toast.show({
      content: "自动计算中，请稍后再试。",
    });
  }
  const dataReturn = cacheIndex === -1 ? (await commonServices.postValueService(props.app.token, value, dataUrl)).data : manyDataCache[cacheIndex];
  if (dataReturn.code === 1) {
    /*   成功   */
    const valueReturn = dataReturn.dataset.rows[0];
    const masterDataArr = valueReturn[`${masterConfig.sTbName.toLowerCase()}_tmp`];
    if (commonUtils.isNotEmptyArr(masterDataArr)) {
      masterData = masterDataArr[0];
    }
    if (cacheIndex !== -1) {
      // masterData.handleType = nextProps.masterData.handleType || "update";
      masterData.sQuoConfig = nextProps.masterData.sQuoConfig;
      masterData.sFormId = nextProps.masterData.sFormId;
      masterData.sBillNo = nextProps.masterData.sBillNo;
    }
    masterData.handleType = masterData.sBillNo ? "update" : "add";
    if (masterData.handleType === "update" && !commonUtils.isEmpty(sMakePerson)) {
      masterData.sMakePerson = sMakePerson;
    }
    slaveData = valueReturn[`${slaveConfig.sTbName.toLowerCase()}_tmp`].map(item => {
      item.handleType = dQuickQuoteProductQty ? "add" : item.handleType;
      return item;
    });
    controlData = valueReturn[`${controlConfig.sTbName.toLowerCase()}_tmp`].map(item => {
      item.handleType = dQuickQuoteProductQty ? "add" : item.handleType;
      return item;
    });
    materialsData = valueReturn[`${materialsConfig.sTbName.toLowerCase()}_tmp`].map(item => {
      item.handleType = dQuickQuoteProductQty ? "add" : item.handleType;
      return item;
    });
    processData = valueReturn[`${processConfig.sTbName.toLowerCase()}_tmp`].map(item => {
      item.handleType = dQuickQuoteProductQty ? "add" : item.handleType;
      return item;
    });
    processData = props.sortData(controlData, processData);
    const addState = {};
    if (commonUtils.isNotEmptyObject(manyqtysConfig)) {
      manyqtysData = valueReturn[`${manyqtysConfig.sTbName.toLowerCase()}_tmp`]?.map((item, index) => {
        return {
          ...item,
          sId: manyqtysData[index] ? manyqtysData[index].sId : item.sId,
          handleType: dQuickQuoteProductQty ? "add" : item.handleType,
        };
      });
      if (cacheIndex === -1 && manyqtysData?.some(item => item.manyData)) {
        addState.manyDataCache = manyqtysData.map((item, index) => {
          let result = {};
          if (index === 0) {
            result = Object.keys(valueReturn).reduce((pre, cur) => {
              if (cur !== `${manyqtysConfig.sTbName.toLowerCase()}_tmp`) {
                pre[cur] = valueReturn[cur];
              }
              return pre;
            }, {});
          } else {
            result = commonUtils.convertStrToObj(item.manyData);
          }

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

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

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

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

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

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

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

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

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

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

    data.push(commonBusiness.mergeData("master", masterConfig.sTbName, [masterData]));
    data.push(commonBusiness.mergeData("slave", slaveConfig.sTbName, slaveData, slaveDelData));
    data.push(commonBusiness.mergeData("control", controlConfig.sTbName, controlData, controlDelData));
    data.push(commonBusiness.mergeData("materials", materialsConfig.sTbName, materialsData, materialsDelData));
    data.push(commonBusiness.mergeData("process", processConfig.sTbName, processData, processDelData));
    if (commonUtils.isNotEmptyObject(colorConfig)) {
      data.push(commonBusiness.mergeData("color", colorConfig.sTbName, colorData, colorDelData));
    }
    if (commonUtils.isNotEmptyObject(packConfig)) {
      data.push(commonBusiness.mergeData("pack", packConfig.sTbName, packData, packDelData));
    }
    console.log(data,props, "onSaveData");

    return;
    // 核价后保存
    props.onSaveData(
      {
        data,
        sClientType: "1",
        loading: false,
        sSysLogSrcId: masterData.sId,
        bIsUnCcg: false,
      },
      props
    );
  }
};
const handleSaveData = async (params, props) => {
  const {
    token,
    sModelsId,
    currentId,
    masterData,
    masterConfig,
    slaveConfig,
    checkConfig,
    billnosetting,
    app,
    sModelsType,
    controlConfig,
    materialsConfig,
    processConfig,
    colorConfig,
    packConfig,
    orderDetailConfig,
    dispatch,
    slaveChildConfig,
  } = props;
  const { userinfo } = app;
  const { copyTo } = app.currentPane;
  const onSendSocketMessage = props.handleSendSocketMessage;
  const BtnSave = commonFunc.showMessage(app.commonConst, "BtnSave"); /* 保存 */
  params.optName = BtnSave;
  const returnData = await commonBusiness.saveData({ token, value: params, sModelsId });
  if (commonUtils.isNotEmptyObject(returnData)) {
    if (commonUtils.isNotEmptyObject(copyTo)) {
      const { slaveData } = copyTo;
      const sIdArray = [];
      slaveData.forEach(item => {
        const redisKey = item.sSlaveId;
        sIdArray.push(redisKey);
      });
      const sId = sIdArray.toString();
      onSendSocketMessage("copyfinish", "noAction", sId, userinfo.sId, null, null);
    }
    onSendSocketMessage("release", "noAction", currentId, userinfo.sId, null, null);
    props.onSaveState({
      enabled: false,
      currentId: masterData.sId,
    });
    // 保存后更新panes,currentPane的checkedId，防止浏览器刷新时重新又变成新增。
    const iPaneIndex = app.panes.findIndex(item => item.key === app.currentPane.key);
    app.panes[iPaneIndex].checkedId = masterData.sId;
    app.currentPane.checkedId = masterData.sId;
    // dispatch({ type: "app/savePanesAndCurrentPane", payload: { panes: app.panes, currentPane: app.currentPane } });

    // if (billnosetting.bAutoCheck) {
    //   await this.handleAudit(1);
    // } else {
    //   await this.handleGetData(masterConfig, slaveConfig, checkConfig);
    //   if ((sModelsType.includes("sales/salesOrder") || sModelsType.includes("manufacture/workOrder")) && !commonUtils.isEmpty(controlConfig)) {
    //     await this.handleGetMemoData(controlConfig, materialsConfig, processConfig, colorConfig, packConfig);
    //   } else if (sModelsType === "purchase/purchaseOrder") {
    //     await this.handleGetOneMemoData("orderDetail", orderDetailConfig);
    //   } else if (sModelsType === "sales/salesSgoods" && !commonUtils.isEmpty(slaveChildConfig)) {
    //     await this.handleGetOneMemoData("slaveChild", slaveChildConfig);
    //   }
    //   if (this.props.app.currentPane.refresh !== undefined) {
    //     this.props.app.currentPane.refresh();
    //   }
    // }
    props.onSaveState({
      loading: false,
    });
    return true;
  } else {
    props.onSaveState({
      loading: false,
    });
    return false;
  }
};
const QuotationAllMaster = baseProps => {
  const props = masterEvent(baseProps);
  if (!props) {
    return null; // 或者加载状态组件
  }
  if (props && !props.masterConfig) {
    return null;
  }

  return <QuotationAllprogressDetail {...props} />;
};
export default QuotationAllMaster;
