import { ref, reactive, toRefs } from "vue";
import * as Exceljs from "exceljs";
import { saveAs } from "file-saver";
import { formatTime, formatAmount3, floatAdd, formatCutNumber, floatMul } from "@/utils/index";
import { cloneDeep } from "lodash-es";
import { isFunction } from "@/utils/is";
import { useUserStore } from "@/stores/modules/user";
import { ElButton, ElMessage, ElPopconfirm, ElMessageBox } from "element-plus";
import { CommonDynamicSelect } from "@/api/modules/common";
import { useHooks } from "@/views/quote/bednetQuote/hooks/index";

interface WidgetTableItem {
  label: string;
  dscrp: any;
  qty?: number | string;
  costamt?: number | string;
  useqty?: number | string;
  price?: number | string;
  [key: string]: any;
}

interface defaultState {
  tableData: any;
  oriTableData: WidgetTableItem[];
  newTableData: WidgetTableItem[];
  enumMap: any;
  // tabldId: number;
  bednet_qingdan: any;
  default_font: any;
  default_alignment: any;
  /**
   * @description 默认边框样式
   */
  default_border: any;
  /**
   * @description 默认表头样式
   */
  defalut_header_style: any;
  variables: variablesProps[];
  /**
   * @description 表头统计单元格
   */
  headerDannumCost: any[];
}

interface wfQingdanProps {
  data: any;
  mxdata?: any;
  /**
   * @description 属性枚举
   */
  enumMap?: any;
  /**
   * @description 面料tab分类
   */
  fabricMx?: any;
  formulakindenum?: any;
  dannum_type?: number;
  formula?: any;
  replace?: any;
  // replace?: any;
  // formula_ori?: any;
  differ?: any;
  /**
   * @description 表头字段
   */
  fields?: any;
}

interface variablesProps {
  /**
   * @description 单元格变量
   */
  cell: string;
  /**
   * @description 变量名称
   */
  field: string;
}

export const useHooksCpQuote = (t?: any) => {
  const { userInfo } = useUserStore();

  const state = reactive<defaultState>({
    // tabldId: 0,
    tableData: [],
    bednet_qingdan: [],
    oriTableData: [
      {
        label: "核价编码",
        dscrp: data => data.mattresscode,
        qty: "",
        costamt: "",
        useqty: "",
        price: ""
      },
      {
        label: "核价名称",
        dscrp: data => data.mattressname,
        qty: "",
        costamt: "",
        useqty: "",
        price: ""
      },
      {
        label: "床垫类别",
        dscrp: data => {
          let _enum = state.enumMap.get("mattresstypeid");
          let result = "";
          if (_enum) {
            result = _enum.find(t => t.value == data.mattresstypeid).label ?? "";
          }
          return result;
        },
        qty: "",
        costamt: "",
        useqty: "",
        price: ""
      },
      {
        label: "床垫规格",
        dscrp: data => {
          return `${data.mattress_width} * ${data.mattress_length} * ${data.mattress_height}`;
        },
        qty: "",
        costamt: "",
        useqty: "",
        price: ""
      },
      {
        label: "拆装、布套",
        dscrp: data => {
          let arr = [];
          if (Number(data.if_m_chai) == 1) {
            arr.push("面拆");
          }
          if (Number(data.if_z_chai) == 1) {
            arr.push("中拆");
          }
          if (Number(data.if_d_chai) == 1) {
            arr.push("底拆");
          }
          if (Number(data.if_n_butao) == 1) {
            arr.push("内布套");
          }
          if (Number(data.if_w_butao) == 1) {
            arr.push("外布套");
          }
          return arr.join(" ");
        },
        qty: "",
        costamt: "",
        useqty: "",
        price: ""
      }
    ],
    newTableData: [],
    enumMap: null,
    default_font: { size: 12, name: "宋体" },
    default_alignment: {
      vertical: "middle", // 垂直居中
      horizontal: "left", // 水平居左
      wrapText: true // 自动换行
    },
    defalut_header_style: {
      font: { size: 15, bold: true, name: "宋体" },
      alignment: { horizontal: "right" },
      height: 26
    },
    default_border: {
      top: { style: "thin", color: { argb: "FF000000" } },
      left: { style: "thin", color: { argb: "FF000000" } },
      bottom: { style: "thin", color: { argb: "FF000000" } },
      right: { style: "thin", color: { argb: "FF000000" } }
    },
    variables: [],
    headerDannumCost: [
      {
        level: "部门不含税价",
        level1: "小计",
        cellCol: "J",
        rowIndex: 0,
        showCell: "G1",
        field: "dannum_cost2"
      },
      {
        level: "部门不含税价",
        level1: "小计",
        cellCol: "K",
        rowIndex: 0,
        showCell: "I1",
        field: "dannum_cost1"
      },
      {
        level: "部门不含税价",
        level1: "小计",
        cellCol: "L",
        rowIndex: 0,
        showCell: "K1",
        field: "dannum_cost4"
      },
      {
        level: "部门不含税价",
        level1: "小计",
        cellCol: "M",
        rowIndex: 0,
        showCell: "M1",
        field: "dannum_cost3"
      }
    ]
  });

  const isFilterPrice = data => {
    return formatAmount3({ val: data });
  };

  const setResultData = (target: any, label: string, value: any) => {
    let result = cloneDeep(target);
    let _value = formatCutNumber({ val: value });
    result.label = label;
    if (userInfo.usermode == 0) {
      result.costamt = _value;
      result.costamt_1 = _value;
      result.costamt_2 = _value;
      result.costamt_3 = _value;
      result.costamt_4 = _value;
    }
    return result;
  };

  const wf_retrieve_qingdan_bednet = async (data: any, index: any, isNew = false) => {
    const { getDataMxAdd, getDataMxSpring, dataCallback } = useHooks(t);
    const bednet = data.list[0];
    let s_bednet_qingdan = [];
    let bednet_qingdan_item = [];
    let default_bednet_qingdan = {
      level: "车间成本",
      level1: "总床网车间成本",
      level2: `床网${index + 1} - 总材料成本`
    };

    // let bednetMxData = [];
    // let bednetMxSpringData = [];
    console.log("wf_retrieve_qingdan_bednet data :>> ", data);
    let res = await getDataMxAdd({ arg_bednetid: bednet.bednetid });
    let mxResult = dataCallback(res);
    console.log("wf_retrieve_qingdan_bednet mxResult :>> ", mxResult);

    let ls_床网名称,
      ls_区区,
      ls_卷包,
      ls_规格,
      ls_排列,
      ls_床网高度,
      ls_弹簧,
      ls_边铁,
      ls_底面无纺布,
      ls_上垫层物料,
      ls_下垫层物料,
      ls_入袋无纺布,
      ls_四周加硬排数 = "",
      ls_弹叉 = "",
      ls_海绵包边物料 = "",
      ls_填充海绵物料 = "";
    let item: any = {};

    let res2 = await getDataMxSpring({ arg_bednetid: bednet.bednetid });
    let springResult = dataCallback(res2);
    console.log("springResult :>> ", springResult);

    //床网名称
    s_bednet_qingdan.push({
      pzname: "床网名称"
    });

    let enumItem = data.tableinfo.columns.find((item: any) => item.field == "bednettypeid");
    console.log("bednettypeid enumItem :>> ", enumItem);
    let _pznamemx = "";
    if (enumItem) {
      _pznamemx = enumItem.enum.find((item: any) => item.value == bednet.bednettypeid)?.label;
    }

    //床网类型
    s_bednet_qingdan.push({
      pzname: "床网类型",
      pznamemx: _pznamemx,
      amt: 0,
      useqty: 0
    });
    ls_床网名称 = s_bednet_qingdan[1].pznamemx;

    //规格
    s_bednet_qingdan.push({
      pzname: "规格",
      pznamemx: bednet.mattress_width + "*" + bednet.mattress_length + "*" + bednet.mattress_height,
      amt: 0,
      useqty: 0
    });
    ls_规格 = bednet.mattress_width + "*" + bednet.mattress_length;

    //排列
    s_bednet_qingdan.push({
      pzname: "排列",
      pznamemx: mxResult.list[0].spring_qty_width + "*" + mxResult.list[0].spring_qty_length,
      amt: 0,
      useqty: 0
    });
    ls_排列 = mxResult.list[0].spring_qty_width + "*" + mxResult.list[0].spring_qty_length;

    //床网高度
    s_bednet_qingdan.push({
      pzname: "床网高度",
      pznamemx: mxResult.list[0].bednet_height + "高",
      amt: 0,
      useqty: 0
    });
    ls_床网高度 = mxResult.list[0].bednet_height + "高";

    item = {
      pzname: "弹簧线径/高度/口径/中心直径/圈数",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };

    //弹簧线径/高度/口径/中心直径/圈数
    if (Number(mxResult.list[0].if_part) == 0) {
      item.pznamemx = mxResult.list[0].springname;
      ls_弹簧 = mxResult.list[0].springname;

      let result = cloneDeep(default_bednet_qingdan);
      result.label = "弹簧";
      result.dscrp = ls_弹簧;

      if (userInfo.usermode == 0) {
        result.costamt = bednet.spring_mtrl_cost;
        result.costamt_1 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].spring_mtrl_cost ?? 0, 1 + mxResult.list[0].dannum1_rate) })
        );
        result.costamt_2 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].spring_mtrl_cost ?? 0, 1 + mxResult.list[0].dannum2_rate) })
        );
        result.costamt_3 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].spring_mtrl_cost ?? 0, 1 + mxResult.list[0].dannum3_rate) })
        );
        result.costamt_4 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].spring_mtrl_cost ?? 0, 1 + mxResult.list[0].dannum4_rate) })
        );
      }
      bednet_qingdan_item.push(result);
    } else {
      let ls_left, ls_right, ls_t_temp, ls_t_name;
      if (springResult.list.length > 0) {
        ls_t_name = springResult.list[0].springname;
        ls_left = ls_t_name.substring(0, ls_t_name.indexOf("/"));
        ls_right = ls_t_name.substring(ls_t_name.indexOf("/") + 1);
        // //提取 / 之前的字符串
        // ls_left = springResult.list[0].springname.split("/")[0];
        // //提取 / 之后的字符串
        // ls_right = springResult.list[0].springname.split("/")[1];
        ls_t_temp = ls_left;

        springResult.list.map((t, i) => {
          console.log("springResult.list t, i :>> ", t, i, i >= 1 && ls_t_temp);
          if (i >= 1 && ls_t_temp) {
            //提取 / 之前的字符串

            ls_left = t.springname.substring(0, t.springname.indexOf("/"));
            // ls_left = t.springname.split("/")[0];
            //提取 / 之后的字符串
            ls_t_temp = ls_t_temp + "+" + ls_left;

            console.log("ls_t_temp :>> ", ls_t_temp);
          }
          let result = cloneDeep(default_bednet_qingdan);
          result.label = "弹簧";
          result.dscrp = t.springname;
          if (userInfo.usermode == 0) {
            result.costamt = t.spring_mtrl_cost;
            result.costamt_1 = isFilterPrice(
              formatCutNumber({ val: floatMul(t.spring_mtrl_cost ?? 0, 1 + mxResult.list[0].dannum1_rate) })
            );
            result.costamt_2 = isFilterPrice(
              formatCutNumber({ val: floatMul(t.spring_mtrl_cost ?? 0, 1 + mxResult.list[0].dannum2_rate) })
            );
            result.costamt_3 = isFilterPrice(
              formatCutNumber({ val: floatMul(t.spring_mtrl_cost ?? 0, 1 + mxResult.list[0].dannum3_rate) })
            );
            result.costamt_4 = isFilterPrice(
              formatCutNumber({ val: floatMul(t.spring_mtrl_cost ?? 0, 1 + mxResult.list[0].dannum4_rate) })
            );
          }
          bednet_qingdan_item.push(result);
        });
      }
      ls_弹簧 = ls_t_temp + "/" + ls_right;
    }
    s_bednet_qingdan.push(item);
    console.log("s_bednet_qingdan ls_弹簧:>> ", ls_弹簧);

    //多区弹簧/高度/口径/中心直径/圈数
    // springResult.list.map((t, i) => {
    //   s_bednet_qingdan.push({
    //     pzname: `多区弹簧${i + 1}/高度/口径/中心直径/圈数`,
    //     pznamemx: t.springname,
    //     amt: 0,
    //     useqty: 0
    //   });
    // });
    for (let i = 0; i < 5; i++) {
      s_bednet_qingdan.push({
        pzname: `多区弹簧${i + 1}/高度/口径/中心直径/圈数`,
        pznamemx: springResult.list[i]?.springname ?? "",
        amt: 0,
        useqty: 0
      });
    }

    //边铁条数
    item = {
      pzname: "边铁条数",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(mxResult.list[0].side_iron_qty) > 0) {
      item.pznamemx = mxResult.list[0].side_iron_qty + "条";
      ls_边铁 = Number(mxResult.list[0].side_iron_qty) + "条边铁";

      let result = cloneDeep(default_bednet_qingdan);
      result.label = "边铁";
      result.dscrp = ls_边铁;

      if (userInfo.usermode == 0) {
        result.costamt = mxResult.list[0].side_iron_mtrl_cost;
        result.costamt_1 = mxResult.list[0].side_iron_mtrl_cost;
        result.costamt_2 = mxResult.list[0].side_iron_mtrl_cost;
        result.costamt_3 = mxResult.list[0].side_iron_mtrl_cost;
        result.costamt_4 = mxResult.list[0].side_iron_mtrl_cost;
      }
      bednet_qingdan_item.push(result);
    } else {
      ls_边铁 = "无边铁";
    }
    s_bednet_qingdan.push(item);

    //底面无纺布
    item = {
      pzname: "底面无纺布",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(mxResult.list[0].fabrics2_mtrlid) > 0) {
      let enumItem = mxResult.tableinfo.columns.find((item: any) => item.field == "fabrics2_mtrlid");
      let _pznamemx = "";
      let enumItem_enum = null;

      console.log("fabrics2_mtrlid enumItem :>> ", enumItem);
      if (enumItem) {
        enumItem_enum = enumItem.enum.find((item: any) => item.value == mxResult.list[0].fabrics2_mtrlid);
        _pznamemx = enumItem_enum?.label;
      }
      item.pznamemx = _pznamemx;
      ls_底面无纺布 = _pznamemx;

      let result = cloneDeep(default_bednet_qingdan);
      result.label = "底面无纺布";
      result.dscrp = ls_底面无纺布;

      if (userInfo.usermode == 0) {
        result.costamt = mxResult.list[0].fabrics2_mtrl_cost;
        result.costamt_1 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].fabrics2_mtrl_cost ?? 0, 1 + enumItem_enum?.dannum1_rate) })
        );
        result.costamt_2 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].fabrics2_mtrl_cost ?? 0, 1 + enumItem_enum?.dannum2_rate) })
        );
        result.costamt_3 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].fabrics2_mtrl_cost ?? 0, 1 + enumItem_enum?.dannum3_rate) })
        );
        result.costamt_4 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].fabrics2_mtrl_cost ?? 0, 1 + enumItem_enum?.dannum4_rate) })
        );
      }
      bednet_qingdan_item.push(result);
    } else {
      ls_底面无纺布 = "";
    }
    console.log("ls_底面无纺布 :>> ", ls_底面无纺布);
    s_bednet_qingdan.push(item);

    //入袋无纺布
    item = {
      pzname: "入袋无纺布",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    console.log("Number(bednet.fabrics1_mtrlid) :>> ", Number(mxResult.list[0].fabrics1_mtrlid), mxResult.list[0]);
    if (Number(mxResult.list[0].fabrics1_mtrlid) > 0) {
      let enumItem = mxResult.tableinfo.columns.find((item: any) => item.field == "fabrics1_mtrlid");
      let enumItem_enum = null;
      let _pznamemx = "";
      if (enumItem) {
        enumItem_enum = enumItem.enum.find((item: any) => item.value == mxResult.list[0].fabrics1_mtrlid);
        _pznamemx = enumItem_enum?.label;
      }
      item.pznamemx = _pznamemx;
      ls_入袋无纺布 = _pznamemx;

      let result = cloneDeep(default_bednet_qingdan);
      result.label = "入袋无纺布";
      result.dscrp = ls_入袋无纺布;
      if (userInfo.usermode == 0) {
        result.costamt = mxResult.list[0].fabrics1_mtrl_cost;
        result.costamt_1 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].fabrics1_mtrl_cost ?? 0, 1 + enumItem_enum?.dannum1_rate) })
        );
        result.costamt_2 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].fabrics1_mtrl_cost ?? 0, 1 + enumItem_enum?.dannum2_rate) })
        );
        result.costamt_3 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].fabrics1_mtrl_cost ?? 0, 1 + enumItem_enum?.dannum3_rate) })
        );
        result.costamt_4 = isFilterPrice(
          formatCutNumber({ val: floatMul(mxResult.list[0].fabrics1_mtrl_cost ?? 0, 1 + enumItem_enum?.dannum4_rate) })
        );
      }
      bednet_qingdan_item.push(result);
    } else {
      ls_入袋无纺布 = "";
    }
    s_bednet_qingdan.push(item);

    //上垫层物料
    item = {
      pzname: "上垫层物料",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.felt_mtrlid) > 0) {
      item.pznamemx = bednet.mtrl_felt_name;
      ls_上垫层物料 = bednet.mtrl_felt_name;

      let result = cloneDeep(default_bednet_qingdan);
      result.label = "上垫层物料";
      result.dscrp = ls_上垫层物料;

      if (userInfo.usermode == 0) {
        result.costamt = bednet.felt_mtrl_cost;
        result.costamt_1 = bednet.felt_mtrl_cost;
        result.costamt_2 = bednet.felt_mtrl_cost;
        result.costamt_3 = bednet.felt_mtrl_cost;
        result.costamt_4 = bednet.felt_mtrl_cost;
      }
      bednet_qingdan_item.push(result);
    } else {
      ls_上垫层物料 = "";
    }
    s_bednet_qingdan.push(item);

    //下垫层物料
    item = {
      pzname: "下垫层物料",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.felt_x_mtrlid) > 0) {
      item.pznamemx = bednet.mtrl_felt_x_name;
      ls_下垫层物料 = bednet.mtrl_felt_x_name;

      let result = cloneDeep(default_bednet_qingdan);
      result.label = "下垫层物料";
      result.dscrp = ls_下垫层物料;
      if (userInfo.usermode == 0) {
        result.costamt = bednet.felt_mtrl_x_cost;
        result.costamt_1 = bednet.felt_mtrl_x_cost;
        result.costamt_2 = bednet.felt_mtrl_x_cost;
        result.costamt_3 = bednet.felt_mtrl_x_cost;
        result.costamt_4 = bednet.felt_mtrl_x_cost;
      }
      bednet_qingdan_item.push(result);
    } else {
      ls_下垫层物料 = "";
    }
    s_bednet_qingdan.push(item);

    //四周加硬排数
    item = {
      pzname: "四周加硬排数",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(mxResult.list[0].hard_around_row) > 0) {
      item.pznamemx = mxResult.list[0].hard_around_row + "排" + mxResult.list[0].hard_around_springname;
      ls_四周加硬排数 = "四周加硬" + mxResult.list[0].hard_around_row + "排" + mxResult.list[0].hard_around_springname;
    }
    console.log("ls_四周加硬排数 :>> ", ls_四周加硬排数);
    s_bednet_qingdan.push(item);

    //四周加硬弹簧线径/高度/口径/中心直径/圈数
    item = {
      pzname: "四周加硬弹簧线径/高度/口径/中心直径/圈数",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(mxResult.list[0].if_hard_around) > 0) {
      item.pznamemx = mxResult.list[0].hard_around_springname;

      let result = cloneDeep(default_bednet_qingdan);
      result.label = "四周加硬弹簧";
      result.dscrp = mxResult.list[0].hard_around_springname;
      if (userInfo.usermode == 0) {
        result.costamt = mxResult.list[0].hard_around_mtrl_cost;
        result.costamt_1 = mxResult.list[0].hard_around_mtrl_cost;
        result.costamt_2 = mxResult.list[0].hard_around_mtrl_cost;
        result.costamt_3 = mxResult.list[0].hard_around_mtrl_cost;
        result.costamt_4 = mxResult.list[0].hard_around_mtrl_cost;
      }
      bednet_qingdan_item.push(result);
    }
    s_bednet_qingdan.push(item);

    //海绵包边物料
    item = {
      pzname: "海绵包边物料",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (bednet.mtrl_sponge_name) {
      item.pznamemx = bednet.mtrl_sponge_name;
      ls_海绵包边物料 = bednet.sponge_thickness + "分" + bednet.sponge_height + "高" + bednet.mtrl_sponge_name;

      let result = cloneDeep(default_bednet_qingdan);
      result.label = "海绵包边物料:" + bednet.mtrl_sponge_name;
      result.dscrp = ls_海绵包边物料;
      if (userInfo.usermode == 0) {
        result.costamt = bednet.sponge_mtrl_cost;
        result.costamt_1 = bednet.sponge_mtrl_cost;
        result.costamt_2 = bednet.sponge_mtrl_cost;
        result.costamt_3 = bednet.sponge_mtrl_cost;
        result.costamt_4 = bednet.sponge_mtrl_cost;
      }
      bednet_qingdan_item.push(result);
    }
    s_bednet_qingdan.push(item);

    //海绵包边物料厚度
    item = {
      pzname: "海绵包边物料厚度",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.sponge_thickness) > 0) {
      item.pznamemx = bednet.sponge_thickness + "分";
    }
    s_bednet_qingdan.push(item);

    //填充海绵物料
    item = {
      pzname: "填充海绵物料",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (bednet.mtrl_sponge_tc_name) {
      item.pznamemx = bednet.mtrl_sponge_tc_name;
      ls_填充海绵物料 = bednet.sponge_tc_thickness + "分" + bednet.sponge_tc_height + "高" + bednet.mtrl_sponge_tc_name;

      let result = cloneDeep(default_bednet_qingdan);
      result.label = "填充海绵物料:" + bednet.mtrl_sponge_tc_name;
      result.dscrp = ls_填充海绵物料;
      if (userInfo.usermode == 0) {
        result.costamt = bednet.sponge_mtrl_tc_cost;
        result.costamt_1 = bednet.sponge_mtrl_tc_cost;
        result.costamt_2 = bednet.sponge_mtrl_tc_cost;
        result.costamt_3 = bednet.sponge_mtrl_tc_cost;
        result.costamt_4 = bednet.sponge_mtrl_tc_cost;
      }
      bednet_qingdan_item.push(result);
    } else {
      ls_填充海绵物料 = "";
    }
    s_bednet_qingdan.push(item);

    //填充包边物料厚度
    item = {
      pzname: "填充包边物料厚度",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.sponge_tc_thickness) > 0) {
      item.pznamemx = bednet.sponge_tc_thickness + "分厚，" + bednet.sponge_tc_height + "分高，" + bednet.mtrl_sponge_tc_name;
    }
    s_bednet_qingdan.push(item);

    //封边物料
    item = {
      pzname: "封边物料",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (bednet.mtrl_edge_name) {
      item.pznamemx = bednet.mtrl_edge_name;
    }
    s_bednet_qingdan.push(item);

    //封边高度
    item = {
      pzname: "封边高度",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.edge_height) > 0) {
      item.pznamemx = bednet.edge_height + "高";
    }
    s_bednet_qingdan.push(item);

    //胶条包角
    item = {
      pzname: "胶条包角",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.if_rsorwa) > 0) {
      item.pznamemx = "有";
    }
    s_bednet_qingdan.push(item);

    //海绵打孔
    item = {
      pzname: "海绵打孔",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.if_sponge_drilling) > 0) {
      item.pznamemx = "有";
    }
    s_bednet_qingdan.push(item);

    //弹叉数量
    item = {
      pzname: "弹叉数量",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    console.log("ls_弹叉  bf:>> ", ls_弹叉, bednet.fork_qty);
    if (Number(bednet.fork_qty) > 0) {
      item.pznamemx = bednet.fork_qty + "只弹叉";
      ls_弹叉 = bednet.fork_qty + "只弹叉";
    }
    console.log("ls_弹叉 :>> ", ls_弹叉);
    s_bednet_qingdan.push(item);

    //15分布条
    item = {
      pzname: "15分布条",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.if_15strip) > 0) {
      item.pznamemx = "有";
    }
    s_bednet_qingdan.push(item);

    //蛇线线径
    item = {
      pzname: "蛇线线径",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.snake_wire_diameter) > 0) {
      item.pznamemx = bednet.snake_wire_diameter;
    }
    s_bednet_qingdan.push(item);

    //四周口袋弹簧排数
    item = {
      pzname: "四周口袋弹簧排数",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.pocket_around_row) > 0) {
      item.pznamemx = bednet.pocket_around_row + "排";
    }
    s_bednet_qingdan.push(item);

    //四周口袋弹簧线径/高度/口径/中心直径/圈数
    item = {
      pzname: "四周口袋弹簧线径/高度/口径/中心直径/圈数",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(bednet.if_pocket_around) > 0) {
      item.pznamemx = bednet.pocket_around_springname;
    }
    s_bednet_qingdan.push(item);

    //设置床网名称

    //床网类型丨规格丨排列丨高度丨单/多区丨线径丨边铁丨海绵包边丨四周加硬丨弹叉丨底面物料
    let ls_temp_name = s_bednet_qingdan[1].pznamemx + "丨" + s_bednet_qingdan[3].pznamemx + "丨" + s_bednet_qingdan[4].pznamemx; // + s_bednet_qingdan[3].pznamemx + '丨'

    if (Number(bednet.if_part) > 0) {
      ls_temp_name += "丨" + bednet.duo_qv_str + "区";
    } else {
      if (s_bednet_qingdan[5].pznamemx != "") {
        ls_temp_name += "丨" + "单区";
      } else {
        ls_temp_name += "丨" + "多区";
      }
    }

    if (Number(bednet.if_part) > 0) {
      ls_区区 = bednet.duo_qv_str + "区";
    } else {
      ls_区区 = "单区";
    }

    if (s_bednet_qingdan[5].pznamemx != "") {
      ls_temp_name += "丨" + s_bednet_qingdan[5].pznamemx;
    } else {
      if (s_bednet_qingdan[6].pznamemx != "") {
        ls_temp_name += "丨" + s_bednet_qingdan[6].pznamemx.split("/")[0];
      }
      if (s_bednet_qingdan[7].pznamemx != "") {
        ls_temp_name += "丨" + s_bednet_qingdan[7].pznamemx.split("/")[0];
      }
      if (s_bednet_qingdan[8].pznamemx != "") {
        ls_temp_name += "丨" + s_bednet_qingdan[8].pznamemx.split("/")[0];
      }
      if (s_bednet_qingdan[9].pznamemx != "") {
        ls_temp_name += "丨" + s_bednet_qingdan[9].pznamemx.split("/")[0];
      }
      if (s_bednet_qingdan[10].pznamemx != "") {
        ls_temp_name += "丨" + s_bednet_qingdan[10].pznamemx.split("/")[0];
      }
    }

    if (s_bednet_qingdan[11].pznamemx != "") {
      ls_temp_name += "|" + "有边铁";
    } else {
      ls_temp_name += "|" + "无边铁";
    }

    if (s_bednet_qingdan[19].pznamemx != "") {
      ls_temp_name += "|" + +s_bednet_qingdan[19].pznamemx + s_bednet_qingdan[18].pznamemx + "有海绵包边";
    }

    if (s_bednet_qingdan[16].pznamemx != "") {
      ls_temp_name += "丨" + "四周加硬" + s_bednet_qingdan[16].pznamemx;
    }

    if (s_bednet_qingdan[26].pznamemx != "") {
      ls_temp_name += "丨" + s_bednet_qingdan[26].pznamemx;
    }

    if (s_bednet_qingdan[12].pznamemx != "") {
      ls_temp_name += "丨" + "底面" + s_bednet_qingdan[12].pznamemx;
    } else {
      if (s_bednet_qingdan[14].pznamemx == "") {
        ls_temp_name += "丨" + "底一张" + s_bednet_qingdan[15].pznamemx;
      } else {
        if (s_bednet_qingdan[15].pznamemx == "") {
          ls_temp_name += "丨" + "面一张" + s_bednet_qingdan[14].pznamemx;
        } else {
          ls_temp_name += "丨" + "面底各一张" + s_bednet_qingdan[14].pznamemx;
        }
      }
    }

    if (s_bednet_qingdan[21].pznamemx != "") {
      ls_temp_name += "丨" + s_bednet_qingdan[21].pzname + +s_bednet_qingdan[21].pznamemx;
    }

    console.log("wfqingdan data.list[0].if_jb :>> ", data, bednet.if_jb);
    ls_卷包 = Number(bednet.if_jb) > 0 ? "卷包" : "";

    //20231128修改
    //名称：	袋装网丨单区丨卷包丨90*180丨12*31丨20高丨2.0/16.0/5.70/6.70/5.00丨2条无边铁丨底面75g白色无纺布丨上垫层1张1100g黑毡丨下垫层物料1张100g黑毡丨入袋70g白色无纺布丨四周加硬2排丨10弹叉丨8.分20高HA3070海绵包边丨8.分20高HA3070填充海绵|erp编码:

    if (ls_床网名称.indexOf("袋装") > -1) {
      ls_temp_name =
        ls_床网名称 +
        "丨" +
        ls_区区 +
        "丨" +
        ls_卷包 +
        "丨" +
        ls_规格 +
        "丨" +
        ls_排列 +
        "丨" +
        ls_床网高度 +
        "丨" +
        ls_弹簧 +
        "丨" +
        ls_边铁 +
        "丨" +
        ls_底面无纺布 +
        "丨" +
        ls_上垫层物料 +
        "丨" +
        ls_下垫层物料 +
        "丨" +
        ls_入袋无纺布 +
        "丨" +
        ls_四周加硬排数 +
        "丨" +
        ls_弹叉 +
        "丨" +
        ls_海绵包边物料 +
        "丨" +
        ls_填充海绵物料;
    }

    s_bednet_qingdan[0].pzname = "床网名称";
    s_bednet_qingdan[0].pznamemx = ls_temp_name;
    s_bednet_qingdan[0].amt = bednet.nottax_factory_cost;
    s_bednet_qingdan[0].useqty = 0;

    // 新公式补充显示旧公式缺失的明细
    if (isNew) {
      //蛇线材料成本
      if (bednet.snake_wire_mtrl_cost > 0) {
        bednet_qingdan_item.push(setResultData(default_bednet_qingdan, "蛇线材料成本", bednet.snake_wire_mtrl_cost));
      }

      //四周口袋弹簧成本
      if (bednet.pocket_around_spring_cost > 0) {
        bednet_qingdan_item.push(setResultData(default_bednet_qingdan, "四周口袋弹簧成本", bednet.pocket_around_spring_cost));
      }

      //四周口袋无纺布成本
      if (bednet.pocket_around_fabrics_cost > 0) {
        bednet_qingdan_item.push(setResultData(default_bednet_qingdan, "四周口袋无纺布成本", bednet.pocket_around_fabrics_cost));
      }

      //胶水材料成本
      if (bednet.glue_mtrl_cost > 0) {
        bednet_qingdan_item.push(setResultData(default_bednet_qingdan, "胶水材料成本", bednet.glue_mtrl_cost));
      }

      //C钉/夹码材料
      if (bednet.cnail_mtrl_cost > 0) {
        bednet_qingdan_item.push(setResultData(default_bednet_qingdan, "C钉/夹码材料", bednet.cnail_mtrl_cost));
      }

      //封边材料成本
      if (bednet.edge_mtrl_cost > 0) {
        bednet_qingdan_item.push(setResultData(default_bednet_qingdan, "封边材料成本", bednet.edge_mtrl_cost));
      }

      //弹叉材料成本
      if (bednet.fork_mtrl_cost > 0) {
        bednet_qingdan_item.push(setResultData(default_bednet_qingdan, "弹叉材料成本", bednet.fork_mtrl_cost));
      }

      //胶条/包角材料成本
      if (bednet.rsorwa_mtrl_cost > 0) {
        bednet_qingdan_item.push(setResultData(default_bednet_qingdan, "胶条/包角材料成本", bednet.rsorwa_mtrl_cost));
      }

      //包装总成本
      if (bednet.packet_mtrl_cost > 0) {
        bednet_qingdan_item.push(setResultData(default_bednet_qingdan, "包装总成本", bednet.packet_mtrl_cost));
      }
    }

    state.bednet_qingdan.push(bednet_qingdan_item);

    console.log("s_bednet_qingdan :>> ", s_bednet_qingdan);
    console.log("bednet_qingdan_item :>> ", bednet_qingdan_item);
    return s_bednet_qingdan;
  };

  const f_get_bednet_qingdan = async (bednetid: any, index: any, isNew = false) => {
    if (!Number(bednetid)) return [];
    let _params = {
      dsname: "web_bednet_define",
      queryparams: {
        arg_bednetid: bednetid
      }
    };
    let res = await CommonDynamicSelect(_params);
    let _data: any = {};
    if (res?.datatable?.length) {
      _data = res?.datatable[0];
    }
    let result = {
      list: res?.datatable,
      tableinfo: res?.tableinfo
    };
    console.log("f_get_bednet_qingdan _data:>> ", _data);

    if (!Number(_data.deptid)) {
      throw new Error(_data.bednetcode + ", deptid错误！");
      return [];
    }

    let deptEnum = state.enumMap.get("deptid");
    let _pricelistid = 0;
    if (deptEnum) {
      let depItem = deptEnum.find((item: any) => item.value == _data.deptid);
      console.log("depItem :>> ", depItem);
      if (depItem) {
        _pricelistid = Number(depItem.pricelistid);
      }
    }

    if (!Number(_data.bednettypeid)) {
      throw new Error(_data.bednetcode + ", bednettypeid错误！");
    }

    if (!Number(_pricelistid)) {
      throw new Error(_data.bednetcode + ", pricelistid错误！");
    }

    let rtStr = await wf_retrieve_qingdan_bednet(result, index, isNew);

    //带上erpcode?
    return rtStr;
  };

  /**
   * @description 新报价清单列
   * @param data
   */
  const set_new_table_data = (params: any) => {
    let { data, mxdata, formula, fabricMx, formulakindenum, enumMap } = params;

    console.log("set_new_table_data params :>> ", params);
    let arr = [];

    /**
     * @description 车间成本
     */
    arr = arr.concat(init_new_formula_item(params, "【车间成本】"));
    // let cushionsItem = mxdata.find((itm: any) => itm.field == "cushions");
    // if (cushionsItem) {
    //   if (cushionsItem.data.bednet.length > 0) {
    //     cushionsItem.data.bednet.map((itm: any, index: any) => {
    //       if (itm.mtrlid > 0) {
    //         arr = arr.concat(
    //           init_new_formula_item(
    //             { ...params, formula: params.formula_bednet },
    //             "【车间成本】",
    //             `床网${index + 1}-`,
    //             "replace_bednet"
    //           )
    //         );
    //       }
    //     });
    //   }
    // }
    // arr = arr.concat(
    //   init_new_formula_item({ ...params, formula: params.formula_bednet }, "【车间成本】", "床网-", "replace_bednet")
    // );
    arr = arr.concat(init_new_formula_item(params, "【不含税出厂价】"));
    arr = arr.concat(init_new_formula_item(params, "【部门不含税价】"));
    arr = arr.concat(init_new_formula_item(params, "【部门含税价】"));
    arr = arr.concat(init_new_formula_item(params, "【外币价】"));
    arr = arr.concat(init_new_formula_item(params, "【佣金】"));

    console.log("set_new_table_data arr :>> ", arr);
    return arr;
  };

  const init_new_formula_item = (
    { formula, differ, dannum_type, formula_bednet, mxdata }: any,
    target: string,
    prefix = "",
    replaceKey = "replace"
  ) => {
    let formulaItem = formula.find((item: any) => item.label == target);
    console.log("init_new_formula_item formulaItem :>> ", formulaItem);
    let arr = [];
    let item = {
      level: target.replace("【", "").replace("】", ""),
      level1: "",
      level2: "",
      label: "",
      dscrp: "",
      qty: "",
      costamt: "",
      costamt_1: "",
      costamt_2: "",
      costamt_3: "",
      costamt_4: "",
      useqty: "",
      price: ""
    };
    if (formulaItem) {
      let reg = /\【(.*?)\】/g;
      let formulaItemArr = formulaItem.value.match(reg);

      console.log("init_new_formula_item formulaItemArr :>> ", formulaItemArr);
      if (formulaItemArr.length) {
        formulaItemArr.map(fName => {
          let _item = {
            level: target.replace("【", "").replace("】", ""),
            level1: prefix + fName.replace("【", "").replace("】", ""),
            level2: "",
            label: "",
            dscrp: "",
            qty: "",
            costamt: "",
            costamt_1: "",
            costamt_2: "",
            costamt_3: "",
            costamt_4: "",
            useqty: "",
            price: ""
          };

          if (target == "【车间成本】") {
            /**
             * @description 总床垫车间成本明细
             */
            if (fName.indexOf("床垫车间成本") > -1) {
              let _formulaItem = formula.find((item: any) => item.label == fName);
              if (_formulaItem) {
                let _formulaItemArr = _formulaItem.value.match(reg);
                if (_formulaItemArr.length) {
                  console.log("formulaMattressMx _formulaItemArr:>> ", _formulaItem, _formulaItemArr);

                  _formulaItemArr.map(_fName => {
                    let _itemMattress = cloneDeep(_item);
                    _itemMattress.level2 = _fName.replace("【", "").replace("】", "");

                    if (userInfo.usermode == 0) {
                      differ.map((itm: any) => {
                        let _valueReplace = itm[replaceKey].find((t: any) => t.label == _fName);
                        _itemMattress["costamt_" + itm.type] = _valueReplace?.value ?? 0;
                        if (dannum_type == itm.type) {
                          _itemMattress.costamt = _valueReplace?.value ?? 0;
                        }
                      });
                    }
                    console.log("init_new_formula_item _itemMattress item :>> ", _itemMattress, differ);
                    arr.push(_itemMattress);
                  });
                }
              }
            } else if (fName.indexOf("床网车间成本") > -1) {
              /**
               * @description 总床网车间成本明细
               */
              let _formulaBendnet = formula_bednet.find((item: any) => item.label == target);
              if (_formulaBendnet) {
                let _formulaItemArr = _formulaBendnet.value.match(reg);
                if (_formulaItemArr.length) {
                  console.log("formulaMattressMx _formulaItemArr :>> ", _formulaItemArr);
                  let cushionsItem = mxdata.find((itm: any) => itm.field == "cushions");
                  if (cushionsItem) {
                    if (cushionsItem.data.bednet.length > 0) {
                      cushionsItem.data.bednet
                        .filter(item => item.mtrlid > 0)
                        .map((o: any, index: any) => {
                          _formulaItemArr.map(_fName => {
                            let _itemBednet = cloneDeep(_item);
                            _itemBednet.level2 = `床网${index + 1} - ` + _fName.replace("【", "").replace("】", "");

                            if (userInfo.usermode == 0) {
                              differ.map((itm: any) => {
                                let _valueReplace = itm.replace_bednet[index][replaceKey].find((t: any) => t.label == _fName);
                                console.log("formulaMattressMx _valueReplace :>> ", itm, index, _valueReplace);
                                _itemBednet["costamt_" + itm.type] = _valueReplace?.value ?? 0;
                                if (dannum_type == itm.type) {
                                  _itemBednet.costamt = _valueReplace?.value ?? 0;
                                }
                              });
                            }
                            arr.push(_itemBednet);
                          });
                        });
                    }
                  }
                }
              }
            }
            _item.level2 = "小计";
          }

          if (userInfo.usermode == 0) {
            differ.map((itm: any) => {
              let _valueReplace = itm[replaceKey].find((t: any) => t.label == fName);
              _item["costamt_" + itm.type] = _valueReplace?.value ?? 0;
              if (dannum_type == itm.type) {
                _item.costamt = _valueReplace?.value ?? 0;
              }
            });
          }

          console.log("init_new_formula_item 小计 item :>> ", item);
          arr.push(_item);
        });
      }

      if (userInfo.usermode == 0) {
        differ.map((itm: any) => {
          let _valueReplace = itm[replaceKey].find((t: any) => t.label == target);

          item["costamt_" + itm.type] = _valueReplace?.value ?? 0;
          if (dannum_type == itm.type) {
            item.costamt = _valueReplace?.value ?? 0;
          }
        });
      }
      item.level1 = "小计";
      console.log("item :>> ", item);
      arr.push(item);
    }
    return arr;
  };

  /**
   * @description 刷新报价清单
   */
  const wf_retrieve_qingdan = async (params: wfQingdanProps, isNew?: boolean, ifExpandAll?: boolean) => {
    let { data, mxdata, fabricMx, formulakindenum, enumMap } = params;
    state.bednet_qingdan = [];
    let _isNew = isNew ?? false;
    let _ifExpandAll = ifExpandAll ?? false;
    state.enumMap = enumMap;
    state.tableData = [];
    let _tData = cloneDeep(state.oriTableData);
    state.tableData = _tData.map(item => {
      for (const key in item) {
        if (isFunction(item[key])) {
          item[key] = item[key](data);
        }
      }
      return item;
    });

    console.log("wf_retrieve_qingdan isNew :>> ", isNew);
    if (_isNew) {
      state.tableData = set_new_table_data(params);
    }

    console.log("mxdata data:>> ", mxdata, data);
    let _mxitm = null;
    let level_mattress = "车间成本";
    let level1_mattress = "总床垫车间成本";
    let level2_mattress = "总材料成本";
    let result_default: any = {
      level: level_mattress,
      level1: level1_mattress,
      level2: level2_mattress
    };
    let mattressArr: any = [];
    for (let index = 0; index < mxdata.length; index++) {
      let item = mxdata[index];
      switch (item.field) {
        case "tabpage_8":
        case "tabpage_9":
        case "tabpage_10":
        case "tabpage_11":
        case "tabpage_12":
          _mxitm = fabricMx.find(t => t.name == item.field);
          item.data.map(itm => {
            if ((Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0) && _mxitm.type.includes(Number(itm.formulakind))) {
              let result: any = cloneDeep(result_default);
              result.label = itm.chastr != "" ? itm.chastr : item.label;
              let _formulaName = "";
              if (formulakindenum) {
                _formulaName = formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
              }

              _formulaName = _formulaName.replace(item.replace, "");

              // console.log("_formulaName  rp:>> ", _formulaName, item.replace);
              result.dscrp = `${_formulaName}：${itm.mtrlname}`;

              if (Number(itm.thickness) > 0) {
                result.dscrp += ` 厚度：${itm.thickness}`;
              }
              result.qty = Number(itm.qty);
              if (userInfo.usermode == 0) {
                result.costamt = itm.costamt ?? 0;
                result.costamt_1 = floatMul(itm.costamt ?? 0, 1 + itm.dannum1_rate);
                result.costamt_2 = floatMul(itm.costamt ?? 0, 1 + itm.dannum2_rate);
                result.costamt_3 = floatMul(itm.costamt ?? 0, 1 + itm.dannum3_rate);
                result.costamt_4 = floatMul(itm.costamt ?? 0, 1 + itm.dannum4_rate);
                result.useqty = Number(itm.useqty ?? 0);
                result.price = isFilterPrice(itm.price ?? 0);
              }
              result.index = index;
              mattressArr.push(result);
            }
          });
          break;
        case "tabpage_13":
          _mxitm = fabricMx.find(t => t.name == item.field);
          item.data.map(itm => {
            if (
              (Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0) &&
              !_mxitm.type.includes(Number(itm.formulakind))
            ) {
              let result: any = cloneDeep(result_default);
              // result.label = itm.label;
              result.label = "其他工艺";
              let _formulaName = "";
              if (formulakindenum) {
                _formulaName = formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
              }

              _formulaName = _formulaName.replace(item.replace, "");
              result.dscrp = `${_formulaName}：${itm.mtrlname}`;

              if (Number(itm.thickness) > 0) {
                result.dscrp += ` 厚度：${isFilterPrice(itm.thickness)}`;
              }
              result.qty = Number(itm.qty);
              if (userInfo.usermode == 0) {
                result.costamt = itm.costamt ?? 0;
                result.costamt_1 = floatMul(itm.costamt ?? 0, 1 + itm.dannum1_rate);
                result.costamt_2 = floatMul(itm.costamt ?? 0, 1 + itm.dannum2_rate);
                result.costamt_3 = floatMul(itm.costamt ?? 0, 1 + itm.dannum3_rate);
                result.costamt_4 = floatMul(itm.costamt ?? 0, 1 + itm.dannum4_rate);
                result.useqty = Number(itm.useqty ?? 0);
                result.price = isFilterPrice(itm.price ?? 0);
              }
              result.index = index;
              mattressArr.push(result);
            }
          });
          break;
        case "cushions": // 垫层
          let _index = index;
          console.log("cushions item.data.bednet :>> ", item.data.bednet);
          console.log("cushions item.data.cushions :>> ", item.data.cushions);
          // 记录床位索引
          let bendet999Index = 0;

          // item.data.cushions.map(async itm => {
          for (let k = 0; k < item.data.cushions.length; k++) {
            let itm = item.data.cushions[k];
            if (Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0 || [999].includes(Number(itm.formulakind))) {
              let result: any = cloneDeep(result_default);
              let _formulaName = "";
              if (formulakindenum) {
                _formulaName = formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
              }

              result.label = _formulaName;
              result.dscrp = itm.mtrlname;

              if (![999].includes(Number(itm.formulakind))) {
                if (Number(itm.thickness) > 0) {
                  result.dscrp += ` 厚度：${isFilterPrice(itm.thickness)}`;
                }
                result.qty = Number(itm.qty);
                if (userInfo.usermode == 0) {
                  result.costamt = itm.costamt ?? 0;
                  result.costamt_1 = floatMul(itm.costamt ?? 0, 1 + itm.dannum1_rate);
                  result.costamt_2 = floatMul(itm.costamt ?? 0, 1 + itm.dannum2_rate);
                  result.costamt_3 = floatMul(itm.costamt ?? 0, 1 + itm.dannum3_rate);
                  result.costamt_4 = floatMul(itm.costamt ?? 0, 1 + itm.dannum4_rate);
                  result.useqty = Number(itm.useqty ?? 0);
                  result.price = isFilterPrice(itm.price ?? 0);
                }

                result.index = _index;
                mattressArr.push(result);
              } else {
                // 999是床网

                console.log("itm.formulakind 9999:>> ", itm.formulakind);

                let ll_bednetid = 0;
                let ld_bednet_height = 0;
                let s_bednet_qingdan = [];
                // let arg_temp_msg;
                if (item.data.bednet.length && item.data.bednet[0].mtrlid > 0) {
                  if (item.data.bednet.length == 1) {
                    //单床网
                    ll_bednetid = item.data.bednet[0].mtrlid;
                    let s_bednet_qingdan = await f_get_bednet_qingdan(ll_bednetid, 0, _isNew);
                    console.log("cushions item.data.bednet s_bednet_qingdan :>> ", s_bednet_qingdan);
                    if (s_bednet_qingdan.length) {
                      result.dscrp = s_bednet_qingdan[0].pznamemx;
                      result.qty = 1;
                      if (userInfo.usermode == 0) {
                        result.costamt = isFilterPrice(s_bednet_qingdan[0]?.amt ?? 0);
                        result.useqty = "";
                        result.price = "";
                      }
                    }
                  } else {
                    //多床网
                    ll_bednetid = item.data.bednet[bendet999Index].mtrlid;
                    console.log("f_get_bednet_qingdan t ll_bednetid:>> ", bendet999Index, item.data.bednet[bendet999Index]);
                    let s_bednet_qingdan = await f_get_bednet_qingdan(ll_bednetid, bendet999Index, _isNew);
                    if (s_bednet_qingdan.length) {
                      result.dscrp = s_bednet_qingdan[0].pznamemx;
                      result.qty = 1;
                      if (userInfo.usermode == 0) {
                        result.costamt = isFilterPrice(s_bednet_qingdan[0]?.amt ?? 0);
                        result.useqty = "";
                        result.price = "";
                      }
                    }
                    console.log("f_get_bednet_qingdan t s_bednet_qingdan :>> ", s_bednet_qingdan);

                    bendet999Index++;
                  }

                  // 旧公式添加，新公式已分离显示
                  if (!_isNew) {
                    result.index = _index;
                    // 查找数组中,从结尾数起最后出现的index=_index的元素的索引，在起后面插入result
                    let _arrData = cloneDeep(mattressArr);
                    let _last = _arrData.reverse().findIndex(t => t.index == _index);
                    if (_last == -1) {
                      mattressArr.push(result);
                    } else {
                      mattressArr.splice(mattressArr.length - _last, 0, result);
                    }
                  }
                }
              }
            }
            // });
          }
          break;
        case "accessories": // 辅料
          item.data.map(itm => {
            if (Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0) {
              let result: any = cloneDeep(result_default);
              result.label = itm.label;
              let _formulaName = "";
              if (formulakindenum) {
                _formulaName = formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
              }

              result.label = _formulaName;
              result.dscrp = itm.mtrlname;

              if (Number(itm.thickness) > 0) {
                result.dscrp += ` 厚度：${isFilterPrice(itm.thickness)}`;
              }
              result.qty = Number(itm.qty);
              if (userInfo.usermode == 0) {
                result.costamt = itm.costamt ?? 0;
                result.costamt_1 = floatMul(itm.costamt ?? 0, 1 + itm.dannum1_rate);
                result.costamt_2 = floatMul(itm.costamt ?? 0, 1 + itm.dannum2_rate);
                result.costamt_3 = floatMul(itm.costamt ?? 0, 1 + itm.dannum3_rate);
                result.costamt_4 = floatMul(itm.costamt ?? 0, 1 + itm.dannum4_rate);
                result.useqty = Number(itm.useqty ?? 0);
                result.price = isFilterPrice(itm.price ?? 0);
              }
              result.index = index;
              mattressArr.push(result);
            }
          });
          break;
        case "packag":
          console.log("packag item.data :>> ", item.data, formulakindenum);
          item.data.map(itm => {
            console.log("(Number(itm.mtrlid) > 0 |:>> ", Number(itm.mtrlid) > 0);
            console.log(
              "(N Number(itm.costamt) != 0) :>> ",
              Number(itm.costamt) != 0,
              Number(itm.costamt),
              itm.costamt,
              Number(itm?.costamt),
              Number(itm?.costamt) != 0
            );
            console.log(
              "(Number(itm.mtrlid) > 0 || Number(itm.costamt) != 0) :>> ",
              Number(itm.mtrlid) > 0 || Number(itm.costamt) != 0
            );
            if (Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0) {
              let result: any = cloneDeep(result_default);
              result.label = itm.label;
              let _formulaName = "";
              if (formulakindenum) {
                _formulaName = formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
              }
              result.label = _formulaName;

              result.dscrp = Number(itm.mtrlid) > 0 ? itm.mtrlname : _formulaName;

              if (Number(itm.thickness) > 0) {
                result.dscrp += ` 厚度：${isFilterPrice(itm.thickness)}`;
              }
              result.qty = Number(itm.qty);
              if (userInfo.usermode == 0) {
                result.costamt = itm.costamt ?? 0;
                result.costamt_1 = floatMul(itm.costamt ?? 0, 1 + itm.dannum1_rate);
                result.costamt_2 = floatMul(itm.costamt ?? 0, 1 + itm.dannum2_rate);
                result.costamt_3 = floatMul(itm.costamt ?? 0, 1 + itm.dannum3_rate);
                result.costamt_4 = floatMul(itm.costamt ?? 0, 1 + itm.dannum4_rate);
                result.useqty = Number(itm.useqty ?? 0);
                result.price = isFilterPrice(itm.price ?? 0);
              }
              result.index = index;
              mattressArr.push(result);
            }
          });
          break;
        case "innerClothLayerMx":
        case "topCottonMx":
          console.log("innerClothLayer item.data :>> ", item.data, formulakindenum);

          item.data.map(itm => {
            if (Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0) {
              let result: any = cloneDeep(result_default);
              result.label = itm.chastr != "" ? itm.chastr : item.label;
              let _formulaName = "";
              if (formulakindenum) {
                _formulaName = formulakindenum.find(t => t.value == itm.formulakind)?.label ?? "";
              }

              _formulaName = _formulaName.replace(item.replace, "");

              // console.log("_formulaName  rp:>> ", _formulaName, item.replace);
              result.dscrp = `${_formulaName}：${itm.mtrlname}`;

              if (Number(itm.thickness) > 0) {
                result.dscrp += ` 厚度：${isFilterPrice(itm.thickness)}`;
              }
              result.qty = Number(itm.qty);
              if (userInfo.usermode == 0) {
                result.costamt = itm.costamt ?? 0;
                result.costamt_1 = floatMul(itm.costamt ?? 0, 1 + itm.dannum1_rate);
                result.costamt_2 = floatMul(itm.costamt ?? 0, 1 + itm.dannum2_rate);
                result.costamt_3 = floatMul(itm.costamt ?? 0, 1 + itm.dannum3_rate);
                result.costamt_4 = floatMul(itm.costamt ?? 0, 1 + itm.dannum4_rate);
                result.useqty = Number(itm.useqty ?? 0);
                result.price = isFilterPrice(itm.price ?? 0);
              }
              result.index = index;
              mattressArr.push(result);
            }
          });
          break;
      }
    }

    if (!isNew) {
      state.tableData = state.tableData.concat(mattressArr);
      state.tableData.push({
        label: "地区",
        dscrp: data.area ?? "",
        qty: "",
        costamt: "",
        useqty: "",
        price: ""
      });
      state.tableData.push({
        label: "柜型",
        dscrp: data.cabinet_type ?? "",
        qty: "",
        costamt: "",
        useqty: "",
        price: ""
      });
    } else {
      if (_ifExpandAll) {
        console.log("state.tableData bf:>> ", state.tableData);
        console.log("smattressArr bf:>> ", mattressArr);

        // 插入床垫车间成本-总材料成本明细
        let _idx = state.tableData.findIndex(t => t.level1.indexOf("床垫车间成本") > -1 && t.level2 === "总材料成本");
        if (_idx > -1) {
          state.tableData[_idx].label = "小计";
          state.tableData.splice(_idx, 0, ...mattressArr);
        }

        // 插入床网车间成本-总材料成本明细
        let cushionsItem = mxdata.find((itm: any) => itm.field == "cushions");
        if (cushionsItem) {
          if (cushionsItem.data.bednet.length > 0) {
            cushionsItem.data.bednet.map((itm: any, index: any) => {
              if (itm.mtrlid > 0) {
                let _idx = state.tableData.findIndex(
                  t => t.level1.indexOf("床网车间成本") > -1 && t.level2 === `床网${index + 1} - 总材料成本`
                );

                console.log("smattressArr smattressArr _idx :>> ", _idx, index, state.bednet_qingdan, state.tableData);
                if (_idx > -1) {
                  state.tableData[_idx].label = "小计";
                  state.bednet_qingdan[index] && state.tableData.splice(_idx, 0, ...state.bednet_qingdan[index]);
                }
              }
            });
          }
        }
      }
    }

    // state.tableData = state.tableData.map(item => {
    //   item.id = item.id ?? null;
    //   item.parentId = item.parentId ?? null;
    //   return item;
    // });

    console.log("state.tableData state.tableData:>> ", state.tableData);
  };

  const formatAmount = (value: any) => {
    return Number(value).toFixed(2);
    // console.log("formatAmount value :>> ", value, formatAmount3({ val: value }));
    // let t = formatAmount3({ val: value })
    // if (t % 1 === 0) {
    //   console.log(t);
    //   return t
    // } else {
    //   return t.toFixed(2)
    // }
  };

  const getSummaries = (data: any, field) => {
    // const { columns, data } = param;
    // console.log("getSummaries param :>> ", param);
    let sums = "";
    const values = data.map(item => Number(item[field]?.toString().replace(/,/g, "")));
    if (!values.every(value => Number.isNaN(value))) {
      // console.log("values :>> ", values);
      sums = `${values.reduce((prev, curr) => {
        // console.log("prev,curr :>> ", prev, curr);
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return floatAdd(prev, curr);
        } else {
          return prev;
        }
      }, 0)}`;
    }

    return sums;
  };

  /**
   * @description 旧核价格式
   * @param params
   * @param fileName
   */
  const toExcelQuote = async (params: wfQingdanProps, fileName: string) => {
    const { data, mxdata } = params;
    console.log("mainData :>> ", params);

    const workbook = new Exceljs.Workbook(); // 创建工作簿
    const worksheet = workbook.addWorksheet("sheet1"); // 创建工作表（sheet1）
    // 冻结前7行
    worksheet.views = [{ state: "frozen", xSplit: 0, ySplit: 7 }];

    // // 设置整个工作表的背景颜色为白色
    // worksheet.eachRow(row => {
    //   // row.eachCell(cell => {
    //   //   cell.fill = {
    //   //     type: "pattern",
    //   //     pattern: "solid",
    //   //     bgColor: { argb: "FFFFFFFF" } // 白色
    //   //   };
    //   // });
    //   row.eachCell({ includeEmpty: true }, function (cell, rowNumber) {
    //     cell.fill = {
    //       type: "pattern",
    //       pattern: "solid",
    //       bgColor: { argb: "FFFFFF" } // 白色
    //     };
    //   });
    // });

    // 宽度设置
    const ACol = worksheet.getColumn("A");
    ACol.width = 0.78;
    const BCol = worksheet.getColumn("B");
    BCol.width = 13.55;
    BCol.key = "label";
    BCol.style = {
      font: state.default_font,
      alignment: { ...state.default_alignment, vertical: "top" }
    };
    const CCol = worksheet.getColumn("C");
    CCol.width = 49.33;
    CCol.key = "dscrp";
    CCol.style = {
      font: state.default_font,
      alignment: state.default_alignment
    };
    const DCol = worksheet.getColumn("D");
    DCol.width = 5.69;
    DCol.key = "qty";
    DCol.style = {
      font: state.default_font,
      alignment: { ...state.default_alignment, horizontal: "center" }
    };
    const ECol = worksheet.getColumn("E");
    ECol.width = 10;
    ECol.key = "costamt";
    ECol.style = {
      font: state.default_font,
      alignment: { ...state.default_alignment, horizontal: "right" }
    };
    const FCol = worksheet.getColumn("F");
    FCol.width = 13;
    FCol.key = "useqty";
    FCol.style = {
      font: state.default_font,
      alignment: { ...state.default_alignment, horizontal: "right" }
    };
    const GCol = worksheet.getColumn("G");
    GCol.width = 12.48;
    GCol.key = "price";
    GCol.style = {
      font: state.default_font,
      alignment: { ...state.default_alignment, horizontal: "right" }
    };

    //======================================= 第一行 =================================
    // 合并A1到L1的单元格 （大标题）
    worksheet.mergeCells("B1:F1");
    const cellB1 = worksheet.getCell("B1");

    let foreign_cost = formatAmount(data?.foreign_cost);
    let currency = Number(data?.moneyrate) != 1 ? "美金" : "人民币";
    cellB1.value = `报价日期:${formatTime(data.createtime, "{y}-{m}-{d}", false)}  报价金额:${foreign_cost}${currency}报价清单`;
    // 设置第一行的单元格样式
    cellB1.font = { size: 15, bold: true, name: "宋体" };
    cellB1.alignment = state.default_alignment;
    worksheet.getRow(1).height = 26; // 设置行高

    //======================================= 第二行 =================================
    worksheet.mergeCells("B2:F2");
    const cellB2 = worksheet.getCell("B2");
    cellB2.value = `财务底价:${formatAmount(data.nottax_dept_cost)}     佣金点数:${formatAmount(
      data.commission
    )}     税率:${formatAmount(data.taxrate)}      `;
    cellB2.font = state.default_font;
    cellB2.alignment = state.default_alignment;
    worksheet.getRow(2).height = 39;

    //======================================= 第三行 =================================
    worksheet.mergeCells("B3:F3");
    const cellB3 = worksheet.getCell("B3");
    cellB3.value = `额外点数:${formatAmount(data.other_rate)}       额外费用:${formatAmount(
      data.extras_cost
    )}     汇率:${formatAmount(data.moneyrate)}      				`;
    cellB3.font = state.default_font;
    cellB3.alignment = state.default_alignment;
    worksheet.getRow(3).height = 18;

    //======================================= 第四行 =================================
    worksheet.mergeCells("B4:F4");
    const cellB4 = worksheet.getCell("B4");
    cellB4.value = `款式费用:${formatAmount(data.hrcost)}     边带费用:${formatAmount(
      data.biandaicost
    )}     总成本:${formatAmount(data.total_cost)}     				`;
    cellB4.font = state.default_font;
    cellB4.alignment = state.default_alignment;
    worksheet.getRow(4).height = 18;

    //======================================= 第五行 =================================
    worksheet.mergeCells("B5:F5");
    const cellB5 = worksheet.getCell("B5");
    cellB5.value = `工厂利润率${formatAmount(data.profitrate)}   工艺点数:${formatAmount(
      data.profitrate_point
    )}     不含税出厂价:${formatAmount(data.nottax_factory_cost)}    				`;
    cellB5.font = state.default_font;
    cellB5.alignment = state.default_alignment;
    worksheet.getRow(5).height = 18;

    //======================================= 第六行 =================================
    worksheet.mergeCells("B6:F6");
    const cellB6 = worksheet.getCell("B6");
    cellB6.value = `部门利润率:${formatAmount(data.dept_profitrate)}    FOB费用:${formatAmount(
      data.fob
    )}    部门售价:${formatAmount(data.nottax_dept_cost)}     				`;
    cellB6.font = state.default_font;
    cellB6.alignment = state.default_alignment;
    worksheet.getRow(6).height = 18;

    //======================================= 第七行 =================================
    worksheet.mergeCells("B7:F7");
    const cellB7 = worksheet.getCell("B7");
    cellB7.value = `让利点数:${formatAmount(data.dept_profitrate_rangli)}     海绵款扣点:${formatAmount(data.haimian_point)}    				`;
    cellB7.font = state.default_font;
    cellB7.alignment = state.default_alignment;
    worksheet.getRow(7).height = 18;

    //======================================= 第八行 =================================

    console.log("百分 state.tableData :>> ", state.tableData);
    await wf_retrieve_qingdan(params);
    console.log("af state.tableData :>> ", JSON.stringify(state.tableData));

    const headerRows = worksheet.insertRow(
      8,
      { label: "项目", dscrp: "内容", qty: "数量", costamt: "金额", useqty: "用量", price: "单价" },
      "n"
    );
    const insertedRows = worksheet.insertRows(9, state.tableData, "n");
    // const cellBSum = worksheet.getCell(`B${9 + state.tableData.length}`);
    // cellBSum.value = "材料合计:";
    // const cellESum = worksheet.getCell(`E${9 + state.tableData.length}`);
    // cellESum.value = getSummaries(state.tableData, "costamt");
    const footerRows = worksheet.insertRow(
      9 + state.tableData.length,
      {
        label: "材料合计:",
        dscrp: "",
        qty: "",
        costamt: getSummaries(state.tableData, "costamt"),
        costamt_1: getSummaries(state.tableData, "costamt_1"),
        costamt_2: getSummaries(state.tableData, "costamt_2"),
        costamt_3: getSummaries(state.tableData, "costamt_3"),
        costamt_4: getSummaries(state.tableData, "costamt_4"),
        useqty: "",
        price: ""
      },
      "n"
    );

    // 设置单元格边框
    let default_border: any = {
      top: { style: "thin", color: { argb: "FF000000" } },
      left: { style: "thin", color: { argb: "FF000000" } },
      bottom: { style: "thin", color: { argb: "FF000000" } },
      right: { style: "thin", color: { argb: "FF000000" } }
    };
    headerRows.eachCell(cell => {
      cell.border = default_border;
    });
    footerRows.eachCell(cell => {
      cell.border = default_border;
    });
    insertedRows.map(row => {
      row.eachCell(cell => {
        cell.border = default_border;
      });
    });

    // label列内容相同时合并单元格
    let same = 0;
    state.tableData.map((t, i) => {
      // label列内容相同的时候,多行合并单元格
      if (i > 0 && t.label === state.tableData[i - 1].label) {
        same++;
      } else {
        if (same > 0) {
          worksheet.mergeCells(`B${9 + i - 1}:B${9 + i - 1 - same}`);
        }
        same = 0;
      }
    });

    console.log("wf_retrieve_qingdan tableData :>> ", state.tableData);

    // insertedRows.values = {
    //   fill: {
    //     type: 'pattern',
    //     pattern:'darkVertical',
    //     fgColor:{argb:'FFFF0000'}
    //   }
    // };

    // let rows = [];
    // state.tableData.map(t => {
    //   let arr = [];
    //   for (const key in t) {
    //     arr.push(t[key]);
    //   }
    //   rows.push(arr);
    // });

    // // 将表格添加到工作表
    // worksheet.addTable({
    //   name: "MyTable",
    //   ref: "B8",
    //   style: {
    //     theme: "",
    //   },
    //   headerRow: true,
    //   totalsRow: true,
    //   columns: [
    //     { name: "项目", totalsRowLabel: "材料合计:" },
    //     { name: "内容" },
    //     { name: "数量" },
    //     { name: "金额", totalsRowFunction: "sum",  },
    //     { name: "用量" },
    //     { name: "单价" }
    //   ],
    //   rows: rows
    // });

    // 下载工作簿
    workbook.xlsx.writeBuffer().then(buffer => {
      saveAs(new Blob([buffer], { type: "application/octet-stream" }), fileName + ".xlsx");
    });
  };

  /**
   * @description 新核价格式
   * @param params
   * @param fileName 文件名
   * @param ifShowDetail 是否显示明细
   */
  const toExcelQuoteNew = async (params: wfQingdanProps, fileName: string, ifShowDetail = true) => {
    const { data, fields, formula, replace } = params;
    console.log("toExcelQuoteNew mainData :>> ", params);

    let variableCellArr = [];

    const workbook = new Exceljs.Workbook(); // 创建工作簿
    const worksheet = workbook.addWorksheet("sheet1"); // 创建工作表（sheet1）

    // 宽度设置
    const ACol = worksheet.getColumn("A");
    ACol.width = 0.78;
    ACol.key = "";
    getColumnStyle(worksheet, "B", "level", 13.55, { vertical: "top" });
    getColumnStyle(worksheet, "C", "level1", 13.55, { vertical: "top" });
    getColumnStyle(worksheet, "D", "level2", 13.55);

    // let mergeCellName = "K";
    let _val = "";

    /**
     * @description 头部大小大结果坐标
     */
    if (ifShowDetail) {
      // 展开明细
      getColumnStyle(worksheet, "E", "label", 13.55, { horizontal: "center" });
      getColumnStyle(worksheet, "F", "dscrp", 26, { horizontal: "right" });
      getColumnStyle(worksheet, "G", "qty", 13.55, { horizontal: "right" });
      getColumnStyle(worksheet, "H", "useqty", 13.55, { horizontal: "right" });
      getColumnStyle(worksheet, "I", "price", 13.55, { horizontal: "right" });
      getColumnStyle(worksheet, "J", "costamt_2", 13.55, { horizontal: "right" });
      getColumnStyle(worksheet, "K", "costamt_1", 13.55, { horizontal: "right" });
      getColumnStyle(worksheet, "L", "costamt_4", 13.55, { horizontal: "right" });
      getColumnStyle(worksheet, "M", "costamt_3", 13.55, { horizontal: "right" });
      // mergeCellName = "K";
    } else {
      getColumnStyle(worksheet, "E", "costamt_2", 13.55, { horizontal: "right" });
      getColumnStyle(worksheet, "F", "costamt_1", 13.55, { horizontal: "right" });
      getColumnStyle(worksheet, "G", "costamt_4", 13.55, { horizontal: "right" });
      getColumnStyle(worksheet, "H", "costamt_3", 13.55, { horizontal: "right" });
      // mergeCellName = "G";
      state.headerDannumCost = [
        {
          level: "部门不含税价",
          level1: "小计",
          cellCol: "E",
          rowIndex: 0,
          showCell: "G1"
        },
        {
          level: "部门不含税价",
          level1: "小计",
          cellCol: "F",
          rowIndex: 0,
          showCell: "I1"
        },
        {
          level: "部门不含税价",
          level1: "小计",
          cellCol: "G",
          rowIndex: 0,
          showCell: "K1"
        },
        {
          level: "部门不含税价",
          level1: "小计",
          cellCol: "H",
          rowIndex: 0,
          showCell: "M1"
        }
      ];
    }

    //======================================= 第一行 =================================
    // 合并A1到L1的单元格 （大标题）
    // worksheet.mergeCells(`B1:${mergeCellName}1`);
    // const cellB1 = worksheet.getCell("B1");

    let foreign_cost = formatAmount(data?.foreign_cost);
    let currency = Number(data?.moneyrate) != 1 ? "美金" : "人民币";
    let _val1 = `报价日期:${formatTime(data.createtime, "{y}-{m}-{d}", false)}`;
    setCellOrMergeCell(worksheet, 1, `B1:E1`, { value: _val1, font: { size: 15, bold: true, name: "宋体" }, height: 26 });
    // setCellOrMergeCell(worksheet, 1, `E1:G1`, "报价清单", 26, { size: 15, bold: true, name: "宋体" }, { horizontal: "center" });
    setCellOrMergeCell(worksheet, 1, `F1`, { value: "标准金额:", ...state.defalut_header_style });
    setCellOrMergeCell(worksheet, 1, `H1`, { value: "散单金额:", ...state.defalut_header_style });
    setCellOrMergeCell(worksheet, 1, `J1`, { value: "小单金额:", ...state.defalut_header_style });
    setCellOrMergeCell(worksheet, 1, `L1`, { value: "大单金额:", ...state.defalut_header_style });

    //======================================= 第二行 =================================
    let rowIndex = 2;
    if (fields.length > 0) {
      _val = "";
      let rowArr = [
        {
          sCell: "B",
          eCell: "E"
        },
        {
          sCell: "F",
          eCell: "I"
        },
        {
          sCell: "J",
          eCell: "M"
        }
      ];
      fields
        .filter(t => t.type != "variable")
        .forEach((t, i) => {
          let rowItem = rowArr[i % 3];
          let _cell = `${rowItem.sCell + rowIndex}:${rowItem.eCell + rowIndex}`;

          _val = `${t.label}: ${t.value}`;
          setCellOrMergeCell(worksheet, rowIndex, _cell, { value: _val.trim() });
          // 每三个一行
          if ((i + 1) % 3 == 0) {
            rowIndex = (i + 1) / 3 + 2;
          }
        });

      if (userInfo.usermode == 0) {
        fields
          .filter(t => t.type == "variable")
          .forEach((t, i) => {
            // 每三个一行
            if (i % 3 == 0) {
              rowIndex++;
            }
            let rowItem = rowArr[i % 3];
            let _cell = `${rowItem.sCell + rowIndex}:${getPreLetter(rowItem.eCell) + rowIndex}`;
            let _cellname_var = rowItem.eCell + rowIndex;

            state.variables.push({
              cell: _cellname_var,
              field: t.field
            });

            _val = `${t.label}:`;
            setCellOrMergeCell(worksheet, rowIndex, _cell, { value: _val });

            const _cellVar = worksheet.getCell(_cellname_var);
            _cellVar.value = t.value;
            _cellVar.font = state.default_font;
            _cellVar.alignment = state.default_alignment;
            _cellVar.fill = {
              type: "pattern",
              pattern: "darkTrellis",
              fgColor: { argb: "FF90c5ff" },
              bgColor: { argb: "FF90c5ff" }
            };

            variableCellArr.push({
              cell: _cellname_var,
              label: t?.jointo ?? t.label,
              jointo: t?.jointo
            });
          });
      }
    }
    console.log("表格内容 bf rowIndex :>> ", rowIndex);
    rowIndex++;

    const headerRows = worksheet.insertRow(
      rowIndex,
      {
        level: "类目",
        level1: "一级项目",
        level2: "二级项目",
        label: "项目",
        dscrp: "内容",
        qty: "数量",
        useqty: "用量",
        price: "单价",
        costamt_2: "标准金额",
        costamt_1: "散单金额",
        costamt_4: "小单金额",
        costamt_3: "大单金额"
      },
      "n"
    );

    // 冻结前7行
    console.log("冻结行数rowIndex :>> ", rowIndex);
    worksheet.views = [{ state: "frozen", xSplit: 0, ySplit: rowIndex }];
    console.log("冻结行数rowIndex end:>> ", rowIndex);

    //======================================= 表格内容 =================================
    console.log("百分 state.tableData :>> ", state.tableData);
    await wf_retrieve_qingdan(params, true, ifShowDetail);
    console.log("af state.tableData :>> ", state.tableData);
    console.log("表格内容 ed rowIndex :>> ", rowIndex);
    rowIndex++;
    const insertedRows = worksheet.insertRows(rowIndex, state.tableData, "n");

    //======================================= 替换单元格方法 =================================
    console.log("替换单元格方法 insertedRows :>> ", insertedRows);

    // insertedRows[0]._cells[4]._value.model.value

    headerRows.eachCell(cell => {
      cell.border = state.default_border;
    });
    // footerRows.eachCell(cell => {
    //   cell.border = default_border;
    // });
    let _formula = cloneDeep(formula);
    let _replace = cloneDeep(replace);
    // 记录哪些行有小计
    state.tableData.map((o, i) => {
      if ([o.level1, o.level2, o.label].includes("小计")) {
        switch (true) {
          case o.label === "小计":
            _formula.forEach(itm => {
              if (isFilterLabel(itm.label) === o.level2) {
                itm.rowIndex = i + rowIndex;
              }
            });
            break;
          case o.level2 === "小计":
            _formula.forEach(itm => {
              if (isFilterLabel(itm.label) === o.level1) {
                itm.rowIndex = i + rowIndex;
              }
            });
            break;
          case o.level1 === "小计":
            console.log("object :>> ", _formula);
            _formula.forEach(itm => {
              if (isFilterLabel(itm.label) === o.level) {
                itm.rowIndex = i + rowIndex;
              }
            });
            break;
        }

        state.headerDannumCost.forEach(itm => {
          let matchArr = [];
          for (const key in itm) {
            if (["level", "level1", "level2", "label"].includes(key)) {
              console.log("object :>> ", itm[key], o[key]);
              if (itm[key] === o[key]) {
                matchArr.push(true);
              } else {
                matchArr.push(false);
              }
            }
          }
          if (matchArr.every(itm => itm)) {
            itm.rowIndex = i + rowIndex;
          }
        });
      } else {
        let key = "";
        switch (true) {
          case o.label != "":
            key = o.label;
            break;
          case o.level2 != "":
            key = o.level2;
            break;
          case o.level1 != "":
            key = o.level1;
            break;
          case o.level2 != "":
            key = o.level2;
            break;
          default:
            key = o.level;
            break;
        }
        _replace.forEach(itm => {
          if (isFilterLabel(itm.label) === key) {
            if (!itm.hasOwnProperty("rowArr")) {
              itm.rowArr = [];
            }
            itm.rowArr.push(i + rowIndex);
          }
        });
        // if (_replaceMap.has(o.label)) {
        //   let _row = _replaceMap.get(o.level);
        //   if (!_row.hasOwnProperty("rowArr")) {
        //     _row.rowArr = [];
        //   }
        //   _row.rowArr.push(i + rowIndex);
        //   _replaceMap.set(o.level, _row);
        // }
      }
    });

    // 替换公式中出现的单元格
    console.log("记录哪些行有 _formulaMap :>> ", _formula);
    console.log("记录哪些行有 _replaceMap :>> ", _replace);
    // insertedRows.map(row => {
    //   row.eachCell(cell => {
    //     console.log('cell.value :>> ', cell.value);
    //     if (cell.value === "小计")
    //   });
    // })

    insertedRows.map(row => {
      row.eachCell((cell: any) => {
        console.log("insertedRows row cell :>> ", cell, cell.value, cell._column._key);
        let _cellCol = cell.address.match(/[a-zA-Z]+/g)[0];
        let _cellRow = Number(cell.address.match(/[0-9]+/g)[0]);
        let oriValue = cell.value;
        // if (cell.value == "小计") {
        if (["costamt_2", "costamt_1", "costamt_3", "costamt_4"].includes(cell._column._key) && userInfo.usermode == 0) {
          // 只取字符串中出现的数字
          console.log("_cellRow :>> ", _cellRow);
          let _formulaItem = _formula.find(o => o.rowIndex == _cellRow);
          console.log("_formulaItem :>> ", _formulaItem);

          if (_formulaItem) {
            // 公式替换
            let ifNotMatch = false;
            let formulaArr = funcFormulaToArray(_formulaItem.value);
            formulaArr = formulaArr.map((o: any) => {
              if (o.indexOf("[") === 0) {
                let _rItem = _replace.find(itm => isFilterLabel(itm.label) === o.slice(1, -1));
                // let _fItem = _formula.find(itm => isFilterLabel(itm.label) === o.slice(1, -1));
                // if (_fItem && _fItem?.rowIndex) {
                //   console.log("公式替换_fItem", _fItem);
                //   return _cellCol + _fItem?.rowIndex;
                // } else
                if (_rItem) {
                  if (_rItem.hasOwnProperty("rowArr")) {
                    let idx = _rItem.rowArr.find(item => item < _cellRow);
                    if (!idx) {
                      idx = _rItem.rowArr[0];
                    }
                    return _cellCol + idx;
                  } else {
                    console.log("_rItem.value ,oriv :>> ", _rItem.value, oriValue);
                    ifNotMatch = true;
                    return _rItem.value;
                  }
                }
              }
              return o;
            });
            if (!ifNotMatch) {
              cell.value = {
                formula: `=${formulaArr.join("")}`
              };
              cell.numFmt = "0.00";
            }
          } else {
            // 指向公式
            let _rItem = _replace.find(itm => itm?.rowArr && itm?.rowArr.includes(_cellRow));
            if (_rItem) {
              let _formulaItem = _formula.find(o => o.label == _rItem.label && o.rowIndex < _cellRow);
              if (_formulaItem) {
                cell.value = {
                  formula: `=${_cellCol + _formulaItem.rowIndex}`
                };
                cell.numFmt = "0.00";
              }

              // 替换特殊单元格
              let _variable = variableCellArr.find(itm => itm.label === isFilterLabel(_rItem.label));
              console.log("_variable _rItem:>> ", _variable, _rItem, variableCellArr, isFilterLabel(_rItem.label));
              if (_variable) {
                if (_variable?.jointo) {
                  cell.value = {
                    formula: `=${_variable.cell} + ${oriValue}`
                  };
                } else {
                  cell.value = {
                    formula: `=${_variable.cell}`
                  };
                }
              }
            }
          }
          cell.numFmt = "0.00";
          // let _formulaItem = _formulaMap.get(cell.value);
          // console.log("_formulaItem :>> ", _formulaItem);
        }
        cell.border = state.default_border;
      });
    });

    // 结果显示在头部
    state.headerDannumCost.forEach(o => {
      let _val = data[o.field];
      if (userInfo.usermode == 0) {
        _val = {
          formula: `=${o.cellCol + o.rowIndex}`
        };
      }
      setCellOrMergeCell(worksheet, 1, o.showCell, {
        value: _val,
        numFmt: "0.00",
        ...state.defalut_header_style
      });
    });

    toMergeCells(worksheet, "level", "B", rowIndex);
    toMergeCells(worksheet, "level1", "C", rowIndex);
    toMergeCells(worksheet, "level2", "D", rowIndex);
    ifShowDetail && toMergeCells(worksheet, "label", "E", rowIndex);

    //======================================= 下载工作簿 =================================
    workbook.xlsx.writeBuffer().then(buffer => {
      saveAs(new Blob([buffer], { type: "application/octet-stream" }), fileName + ".xlsx");
    });
  };

  const getColumnStyle = (worksheet: any, colNuame: string, key: string, width: number, style: any = {}) => {
    const col = worksheet.getColumn(colNuame);
    col.width = width;
    col.key = key;
    col.style = {
      font: state.default_font,
      alignment: { ...state.default_alignment, ...style }
    };
  };

  /**
   * @description 设置或合并单元格
   * @param worksheet
   * @param rowIndex 当前行索引
   * @param mergeCellName 单元格名称，有“：”则合并单元格
   * @param option 单元格样式参数
   *      @param value String=>内容, Object=>表达式
   *      @param font 字体样式
   *      @param alignment 单元格样式
   *      @param height 行高度默认18
   */

  const setCellOrMergeCell = (worksheet: any, rowIndex: Number, mergeCellName: string, option: any = {}) => {
    let colName = mergeCellName;

    let { value, font = state.default_font, alignment = {}, height = 18, numFmt } = option;

    if (mergeCellName.indexOf(":") > -1) {
      worksheet.mergeCells(mergeCellName);
      worksheet.getRow(rowIndex).height = height; // 设置行高
      colName = mergeCellName.split(":")[0];
    }

    const cellB1 = worksheet.getCell(colName);
    cellB1.value = value;
    // 设置第一行的单元格样式
    cellB1.font = font;
    cellB1.alignment = { ...state.default_alignment, ...alignment };

    if (numFmt) {
      cellB1.numFmt = numFmt;
    }
  };

  /**
   * @description 取上一个字母(从A到Z)
   * @param letter 当前字母
   * @returns, z -> y, a -> z, b -> a
   */
  const getPreLetter = letter => {
    let code = letter.charCodeAt(0);
    if (code === 65) {
      return String.fromCharCode(code + 25);
    } else {
      return String.fromCharCode(code - 1);
    }
  };

  /**
   * @description 合并单元格
   */
  const toMergeCells = (worksheet: any, field: string, cellname: string, startRowIndex: number) => {
    // label列内容相同时合并单元格
    let same = 0;
    state.tableData.map((t, i) => {
      // label列内容相同的时候,多行合并单元格
      if (i > 0 && t[field] && t[field] === state.tableData[i - 1][field]) {
        same++;
      } else {
        if (same > 0) {
          worksheet.mergeCells(`${cellname}${startRowIndex + i - 1 - same}:${cellname}${startRowIndex + i - 1}`);
        }
        same = 0;
      }
    });
    if (same > 0) {
      worksheet.mergeCells(
        `${cellname}${startRowIndex + state.tableData.length - 1 - same}:${cellname}${startRowIndex + state.tableData.length - 1}`
      );
    }
  };

  const isFilterLabel = (val: any) => {
    return val.replace(/【/g, "").replace(/】/g, "");
  };

  const funcFormulaToArray = (formula: string) => {
    if (!formula) return [];
    let result = [];
    let lastIndex = 0;
    let _formula = formula;
    _formula = formula.replace(/【/g, "[").replace(/】/g, "]");
    let fArr = _formula.match(/\[(.*?)\]/g); //匹配方括号及其内容。

    fArr.forEach((match, index) => {
      let start = _formula.indexOf(match, lastIndex);
      let end = start + match.length;

      // 添加匹配前的部分
      result.push(_formula.slice(lastIndex, start));

      // 添加匹配到的内容
      result.push(match);

      // 更新 lastIndex
      lastIndex = end;
    });

    // 添加最后一部分
    result.push(formula.slice(lastIndex));

    return result.filter(t => t);
  };

  return {
    ...toRefs(state),
    wf_retrieve_qingdan,
    toExcelQuote,
    toExcelQuoteNew
  };
};
