import { ref, reactive, toRefs } from "vue";
import * as Exceljs from "exceljs";
import { saveAs } from "file-saver";
import { formatTime, formatAmount3, floatAdd } 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";
import { use } from "vxe-table";

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[];
  enumMap: any;
}

interface wfQingdanProps {
  data: any;
  mxdata?: any;
  /**
   * @description 属性枚举
   */
  enumMap?: any;
  /**
   * @description 面料tab分类
   */
  fabricMx?: any;
  formulakindenum?: any;
}

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

  const state = reactive<defaultState>({
    tableData: [],
    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: ""
      }
    ],
    enumMap: null
  });

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

  const wf_retrieve_qingdan_bednet = async (data: any) => {
    const { getDataMxAdd, getDataMxSpring, dataCallbackMx } = useHooks(t);
    let s_bednet_qingdan = [];

    let bednetMxData = [];
    let bednetMxSprintData = [];
    let res = await getDataMxAdd({ arg_bednetid: data.bednetid });
    let mxResult = dataCallbackMx(res);
    console.log("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: data.bednetid });
    let springResult = dataCallbackMx(res2);
    console.log("springResult :>> ", springResult);

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

    let enumItem = data.tableinfo.columns.find((item: any) => item.field == "bednettypeid");
    let _pznamemx = "";
    if (enumItem) {
      _pznamemx = enumItem.enum.find((item: any) => item.value == data.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: data.list[0].mattress_width + "*" + data.list[0].mattress_length + "*" + data.list[0].mattress_height,
      amt: 0,
      useqty: 0
    });
    ls_规格 = data.list[0].mattress_width + "*" + data.list[0].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;
    } else {
      let ls_left, ls_right, ls_t_temp;
      if (springResult.list.length > 0) {
        //提取 / 之前的字符串
        ls_left = springResult.list[1].springname.split("/")[0];
        //提取 / 之后的字符串
        ls_right = springResult.list[1].springname.split("/")[1];
        ls_t_temp = ls_left;

        springResult.list.map((t, i) => {
          if (i >= 1 && !ls_t_temp) {
            //提取 / 之前的字符串
            ls_left = t.springname.split("/")[0];
            //提取 / 之后的字符串
            ls_t_temp = ls_t_temp + "+" + ls_left;
          }
        });
      }
      ls_弹簧 = ls_t_temp + "/" + ls_right;
    }
    s_bednet_qingdan.push(item);

    //多区弹簧/高度/口径/中心直径/圈数
    // 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) + "条边铁";
    } 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 = "";
      if (enumItem) {
        _pznamemx = enumItem.enum.find((item: any) => item.value == mxResult.list[0].fabrics2_mtrlid)?.label;
      }
      item.pznamemx = _pznamemx;
      ls_底面无纺布 = _pznamemx;
    } else {
      ls_底面无纺布 = "";
    }
    s_bednet_qingdan.push(item);

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

    //上垫层物料
    item = {
      pzname: "上垫层物料",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (data.list[0].mtrl_felt_name) {
      item.pznamemx = data.list[0].mtrl_felt_name;
      ls_上垫层物料 = data.list[0].mtrl_felt_name;
    } else {
      ls_上垫层物料 = "";
    }
    s_bednet_qingdan.push(item);

    //下垫层物料
    item = {
      pzname: "下垫层物料",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (data.list[0].mtrl_felt_x_name) {
      item.pznamemx = data.list[0].mtrl_felt_x_name;
      ls_下垫层物料 = data.list[0].mtrl_felt_x_name;
    } 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;
    } else {
      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;
    }
    s_bednet_qingdan.push(item);

    //海绵包边物料
    item = {
      pzname: "海绵包边物料",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (data.list[0].mtrl_sponge_name) {
      item.pznamemx = data.list[0].mtrl_sponge_name;
      ls_海绵包边物料 = data.list[0].sponge_thickness + "分" + data.list[0].sponge_height + "高" + data.list[0].mtrl_sponge_name;
    } else {
      ls_海绵包边物料 = "";
    }
    s_bednet_qingdan.push(item);

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

    //填充海绵物料
    item = {
      pzname: "填充海绵物料",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (data.list[0].mtrl_sponge_tc_name) {
      item.pznamemx = data.list[0].mtrl_sponge_tc_name;
      ls_填充海绵物料 =
        data.list[0].sponge_tc_thickness + "分" + data.list[0].sponge_tc_height + "高" + data.list[0].mtrl_sponge_tc_name;
    } else {
      ls_填充海绵物料 = "";
    }
    s_bednet_qingdan.push(item);

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

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

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

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

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

    //弹叉数量
    item = {
      pzname: "弹叉数量",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(data.list[0].fork_qty) > 0) {
      item.pznamemx = data.list[0].fork_qty + "只弹叉";
      ls_弹叉 = data.list[0].fork_qty + "只弹叉";
    }
    s_bednet_qingdan.push(item);

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

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

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

    //四周口袋弹簧线径/高度/口径/中心直径/圈数
    item = {
      pzname: "四周口袋弹簧线径/高度/口径/中心直径/圈数",
      pznamemx: "",
      amt: 0,
      useqty: 0
    };
    if (Number(mxResult.list[0].if_pocket_around) > 0) {
      item.pznamemx = mxResult.list[0].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(mxResult.list[0].if_part) > 0) {
      ls_temp_name += "丨" + data.list[0].duo_qv_str + "区";
    } else {
      if (s_bednet_qingdan[5].pznamemx != "") {
        ls_temp_name += "丨" + "单区";
      } else {
        ls_temp_name += "丨" + "多区";
      }
    }

    if (Number(mxResult.list[0].if_part) > 0) {
      ls_区区 = data.list[0].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;
    }

    ls_卷包 = Number(data.list[0].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 = data.list[0].nottax_factory_cost;
    s_bednet_qingdan[0].useqty = 0;

    return s_bednet_qingdan;
  };

  const f_get_bednet_qingdan = async (bednetid: any, data: any) => {
    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
    };

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

    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);

    //带上erpcode?
    return rtStr;
  };

  /**
   * @description 刷新报价清单
   */
  const wf_retrieve_qingdan = (params: wfQingdanProps) => {
    let { data, mxdata, fabricMx, formulakindenum, enumMap } = params;
    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("mxdata data:>> ", mxdata, data);
    let _mxitm = null;
    mxdata.map(item => {
      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 = {};
              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 = isFilterPrice(itm.costamt ?? 0);
                result.useqty = Number(itm.useqty ?? 0);
                result.price = isFilterPrice(itm.price ?? 0);
              }
              state.tableData.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 = {};
              result.label = itm.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 = isFilterPrice(itm.costamt ?? 0);
                result.useqty = Number(itm.useqty ?? 0);
                result.price = isFilterPrice(itm.price ?? 0);
              }
              state.tableData.push(result);
            }
          });
          break;
        case "cushions": // 垫层
          item.data.cushions.map(async itm => {
            if (Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0 || [999].includes(Number(itm.formulakind))) {
              let result: any = {};
              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 = isFilterPrice(itm.costamt ?? 0);
                  result.useqty = Number(itm.useqty ?? 0);
                  result.price = isFilterPrice(itm.price ?? 0);
                }
              } else {
                // 999是床网

                let ll_bednetid = 0;
                let ld_bednet_height = 0;
                let s_bednet_qingdan = [];
                // let arg_temp_msg;

                if (item.data.bednet.length == 1) {
                  //单床网
                  ll_bednetid = item.data.bednet[0].mtrlid;
                  let s_bednet_qingdan = await f_get_bednet_qingdan(ll_bednetid, data);
                  if (s_bednet_qingdan.length) {
                    result.dscrp = s_bednet_qingdan[1].pznamemx;
                    result.qty = 1;
                    if (userInfo.usermode == 0) {
                      result.costamt = isFilterPrice(s_bednet_qingdan[1].amt ?? 0);
                    }
                  }
                } else {
                  //多床网
                  item.data.bednet.map(async t => {
                    ll_bednetid = item.data.bednet[0].mtrlid;
                    let _params = {
                      dsname: "web_bednet_mx_add",
                      queryparams: {
                        arg_bednetid: ll_bednetid
                      }
                    };
                    let res = await CommonDynamicSelect(_params);
                    let bednetMxRs = {
                      list: res?.datatable,
                      tableinfo: res?.tableinfo
                    };

                    let s_bednet_qingdan = await f_get_bednet_qingdan(ll_bednetid, bednetMxRs);
                    if (s_bednet_qingdan.length) {
                      result.dscrp = s_bednet_qingdan[1].pznamemx;
                      result.qty = 1;
                      if (userInfo.usermode == 0) {
                        result.costamt = isFilterPrice(s_bednet_qingdan[1].amt ?? 0);
                      }
                    }
                  });
                }
              }

              state.tableData.push(result);
            }
          });
          break;
        case "accessories": // 辅料
          item.data.map(itm => {
            if (Number(itm.mtrlid ?? 0) > 0 || Number(itm.costamt ?? 0) != 0) {
              let result: any = {};
              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 = isFilterPrice(itm.costamt ?? 0);
                result.useqty = Number(itm.useqty ?? 0);
                result.price = isFilterPrice(itm.price ?? 0);
              }
              state.tableData.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 = {};
              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 = isFilterPrice(itm.costamt ?? 0);
                result.useqty = Number(itm.useqty ?? 0);
                result.price = isFilterPrice(itm.price ?? 0);
              }
              state.tableData.push(result);
            }
          });
          break;
      }
    });

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

    state.tableData.push({
      label: "地区",
      dscrp: data.area ?? "",
      qty: "",
      costamt: "",
      useqty: "",
      price: ""
    });
    state.tableData.push({
      label: "柜型",
      dscrp: data.cabinet_type ?? "",
      qty: "",
      costamt: "",
      useqty: "",
      price: ""
    });
  };

  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;
  };

  const toExcelQuote = (params: wfQingdanProps, fileName: string) => {
    const { data, mxdata } = params;
    console.log("mainData :>> ", data);

    let default_font = { size: 12, name: "宋体" };
    let default_alignment: any = {
      vertical: "middle", // 垂直居中
      horizontal: "left", // 水平居左
      wrapText: true // 自动换行
    };

    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: default_font,
      alignment: { ...default_alignment, vertical: "top" }
    };
    const CCol = worksheet.getColumn("C");
    CCol.width = 49.33;
    CCol.key = "dscrp";
    CCol.style = {
      font: default_font,
      alignment: default_alignment
    };
    const DCol = worksheet.getColumn("D");
    DCol.width = 5.69;
    DCol.key = "qty";
    DCol.style = {
      font: default_font,
      alignment: { ...default_alignment, horizontal: "center" }
    };
    const ECol = worksheet.getColumn("E");
    ECol.width = 10;
    ECol.key = "costamt";
    ECol.style = {
      font: default_font,
      alignment: { ...default_alignment, horizontal: "right" }
    };
    const FCol = worksheet.getColumn("F");
    FCol.width = 13;
    FCol.key = "useqty";
    FCol.style = {
      font: default_font,
      alignment: { ...default_alignment, horizontal: "right" }
    };
    const GCol = worksheet.getColumn("G");
    GCol.width = 12.48;
    GCol.key = "price";
    GCol.style = {
      font: default_font,
      alignment: { ...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 = 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 = default_font;
    cellB2.alignment = 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 = default_font;
    cellB3.alignment = 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 = default_font;
    cellB4.alignment = 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 = default_font;
    cellB5.alignment = 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 = default_font;
    cellB6.alignment = 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 = default_font;
    cellB7.alignment = default_alignment;
    worksheet.getRow(7).height = 18;

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

    wf_retrieve_qingdan(params);

    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"), 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;
      }
    });

    // 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");
    });
  };
  return {
    ...toRefs(state),
    wf_retrieve_qingdan,
    toExcelQuote
  };
};
