import React, { useState, useCallback } from "react";
import { history } from "umi";
import { Tabs, Selector, Grid, Image } from "antd-mobile";
import commonConfig from "@/utils/config";
import * as commonServices from "@/services/services";
import * as commonFunc from "@/components/Common/commonFunc";
import { useEffect } from "react";
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 QuotationAllprogressDetail = props => {
  // const {state} = props.location

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

const QuotationDetail = props => {
  const { location, app, sModelsId } = props;
  const { token } = app;
  const [state, setState] = useState(null);
  const addState = {};

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

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

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

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

  //   return { ...result, slaveData: slaveDataNew, manyData: manyDataNew };
  // };

  // 初始化状态
  const { formData = [] } = state || {};
  const { quotationData } = JSON.parse(location.state) || {};
  const [masterConfig, setMasterConfig] = useState(null);
  // 获取主表信息
  // useEffect(() => {
  //   const configUrl = `${commonConfig.server_host}business/getModelBysId/${sModelsId}?sModelsId=${sModelsId}`;
  //   commonServices.getService(token, configUrl).then(({ data: configReturn }) => {
  //     if (configReturn.code === 1) {
  //       const formData = configReturn.dataset.rows[0].formData;
  //       setMasterConfig(formData[0]);

  //       setState(pre => ({ ...pre, formData }));
  //     }
  //   });
  // }, []);
  // useEffect(() => {
  //   // 安全地解析 state
  //   let parsedState = {};
  //   try {
  //     parsedState = JSON.parse(location.state || "{}");
  //   } catch (error) {
  //     console.error("Error parsing state:", error);
  //   }
  //   const { sModelsId } = parsedState;
  //   // 构造请求 URL
  //   const configUrl = `${commonConfig.server_host}business/getModelBysId/${"172129113112117428019179600"}?sModelsId=${"172129113112117428019179600"}`;
  //   // 调用服务获取数据
  //   commonServices
  //     .getService(token, configUrl)
  //     .then(({ data: configReturn }) => {
  //       if (configReturn.code === 1) {
  //         const formData = configReturn.dataset.rows[0]?.formData;
  //         setState(pre => ({ ...pre, ...JsonData, selectedNode: quotationData, boxConfig: formData[0], masterConfig: formData[0] }));
  //       }
  //     })
  //     .catch(error => {
  //       console.error("Error fetching data:", error);
  //     });
  // }, [location, app]);

  // const sQuoConfig = commonUtils.convertStrToObj(JsonData.masterData.sQuoConfig, {});
  // const [state, setState] = useState(addState.onGetFilterState(sQuoConfig, true));
  // 主表
  const list = JsonData.state?.masterConfig?.gdsconfigformslave.filter(item => item.sName && item.bVisible);
  // 客户
  const customer = list?.find(x => x.showName === "客户名称") || {};
  const customerProps = {
    ...props,
    ...JsonData,
    formData: customer,
    // masterConfig,
  };
  const product = list?.find(x => x.showName === "产品名称") || {};
  const productProps = {
    ...props,
    ...JsonData,
    formData: product,
    // masterConfig,
  };
  // setState
  const baseProps = {
    ...props,
    ...JsonData,
    // state,
    // masterConfig,
  };

  return (
    <div>
      <div>{quotationData?.showName || "Loading..."}</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 {...productProps} />
            </div>
            <div style={{ width: "30%", textAlign: "center" }}>X</div>
          </div>
          <div className={styles.sizeItem}>
            <div style={{ width: "70%" }}>
              <SelectInput {...productProps} />
            </div>{" "}
            <div style={{ width: "30%", textAlign: "center" }}>X</div>
          </div>
          <div className={styles.sizeItem}>
            <div style={{ width: "70%" }}>
              <SelectInput {...productProps} />
            </div>
            <div style={{ width: "30%", textAlign: "center" }}>mm</div>
          </div>
        </div>
      </div>
      <div className={styles.sizeBox}>
        <div className={styles.customer}>
          <div>数量</div>
          <SelectInput {...productProps} />
        </div>
        <div className={styles.customer}>
          <div>单位</div>
          <SelectInput {...customerProps} />
        </div>
        <div className={styles.customer}>
          <div>收货方式</div>
          <SelectInput {...customerProps} />
        </div>
      </div>
      <div>
        <QuotationTabs {...baseProps} setState={setState} />
      </div>
    </div>
  );
};

const QuotationTabs = props => {
  const { location } = props;
  const { state } = location;
  const JsonState = state ? JSON.parse(state) : "";
  const sAllPartsName = JsonState ? JsonState.quotationData.sAllPartsName : "";
  const sAllPartsNameList = sAllPartsName.split(",");
  const [activeKey, setActiveKey] = useState(sAllPartsNameList[0]);

  useEffect(() => {
    // 更新父组件的状态
    props.setState(pre => ({ ...pre, activeKey, 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, slaveData } = state || {};
  const { sModelsId } = props;
  const [selectList, setSelectList] = useState([]);
  const [searchValue, setSearchValue] = useState("");

  useEffect(() => {
    // 17428091410008594700322758474000
    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,
          };
        });
        setSelectList(list);
      }
    });
    // 获取盒型
  }, [boxModel]);
  const slaveRowData = slaveData.find(item => item.sTreeNodeName === selectedNode.showName && item.sBoxModel === boxModel) || {};
  const { sColumnNameConfig } = slaveRowData || {};
  const upAbleConfigsExtra = commonUtils.convertStrToObj(sColumnNameConfig, []).map(item => ({
    ...item,
    sValue: item.sDefault,
    iColValue: item.iColValue || 6,
  }));
  const showUpAbleConfigsExtra = upAbleConfigsExtra.filter(x => x.bVisible === 1);
  let boxList = [];
  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 => {
    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 { calcMethodData = [], boxPicData = [], radioValue = calcMethodData[0]?.sCode } = slaveRowData;
  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),
    // boxPicData,
  };
  return (
    <div>
      <Selector
        columns={4}
        options={selectList}
        defaultValue={["3"]}
        style={{ "--padding": "0.8rem" }}
        onChange={v => {
          if (v.length) {
            const data = selectList.find(x => x.sId === v[0]);
            const slaveNewData = JSON.parse(data.sColumnNameConfig).map(x => {
              return {
                [x.sName]: x.sDefault,
              };
            });
            const rowData = {
              ...data,
              ...Object.assign({}, ...slaveNewData),
            };
            props.setState(prevState => ({
              ...prevState,
              slaveRowData: rowData,
            }));
          }
        }}
      />
      <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.viewConfigs.map(x => (
            <Grid.Item>
              <div className={styles.customer} key={x.id || x.showName}>
                <div>{x.showName}</div>
                <SelectInput {...upViewProps12} {...x} bCanInput={false} />
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
      <div>
        <div>拼版信息</div>
        <Grid columns={3} gap={8}>
          {upViewProps20.viewConfigs.map(x => (
            <Grid.Item>
              <div className={styles.customer} key={x.id || x.showName}>
                <div>{x.showName}</div>
                <SelectInput {...upViewProps12} {...x} bCanInput={false} />
              </div>
            </Grid.Item>
          ))}
        </Grid>
      </div>
      <div>
        <div style={{ width: "9.375rem", height: "9.375rem", position: "relative" }}>
          <Typesetting {...boxProps} onSaveStates={handleSaveState} onSaveDPartsLength={onSaveDPartsLength} />
        </div>
        <div>{/* <ShowImgM {...showImgMProps} /> */}</div>
      </div>
    </div>
  );
};
export default QuotationAllprogressDetail;
