import { ref, reactive, computed, toRefs, nextTick, inject } from "vue";
import { Table } from "@/hooks/interface";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { ALLOW_EDIT_STATE } from "@/config/index";
import { GetMattressInterfaceList, RefreshMattressInterface, RefreshMattressInterfaceQd } from "@/api/modules/quote";
import { getConfigureTypeList, getConfigureCodeList, getConfigureCodeMxList } from "@/api/modules/basicinfo";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import {
  CommonDynamicSelect,
  GetERPMtrldefList,
  GetERPWrkGrpList,
  GetERPMtrlTypeList,
  CreatMtrlPf,
  CreatPrdPf,
  DelMtrlPf
} from "@/api/modules/common";
import { transformTreeData, autoMergeCells, isFilterPrice } from "@/utils/index";
import { floatSub, floatAdd, floatMul, floatDiv, formatFixedNumber } from "@/utils/index";
import MtrldefErpSelect from "@/views/system/selector/mtrldefErp/select.vue";
import MtrldefErpInput from "@/views/system/selector/mtrldefErp/Input.vue";
import CodemxSelect from "@/views/system/selector/codemx/select.vue";
import { isFixedColumn } from "element-plus/es/components/table/src/util";
import * as Exceljs from "exceljs";
import { saveAs } from "file-saver";
import { MattressYWAudit, MattressJSAudit, MattressJS2Audit } from "@/api/modules/quote";
import { useRouter } from "vue-router";
import { cloneDeep } from "lodash-es";

interface defaultState {
  initParams: any;
  /**
   * @description 单据当前状态
   */
  orderStatus: string;
  /**
   * @description 列表Ref
   */
  VxeTableRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailRef: any;
  mainData: any;
  mattressYWList: any[];
  mattressQDList: any[];
  /**
   * @description //1   业务补充   2--技术1    3--技术2
   */
  editType: number;
  MattressDialogRef: any;
  MattressDialogProps: any;
  MtrldefErpDialogRef: any;
  MtrldefErpDialogProps: any;
  workgrpEnum: any;
  workgrpEnum2: any;
  configureTypeEnum: any;
  VxeTableMxRef: any;
  YwTableRef: any;
  QdTableRef: any;
  CodeMxDialogProps: any;
  CodeMxDialogRef: any;
  loadingStatus: any;
}

/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useHooks = (t?: any) => {
  const state = reactive<defaultState>({
    initParams: {},
    orderStatus: "",
    VxeTableRef: null,
    VxeTableMxRef: null,
    YwTableRef: null,
    QdTableRef: null,
    LjDetailRef: null,
    mainData: [],
    mattressYWList: [],
    mattressQDList: [],
    editType: 0,
    MattressDialogRef: null,
    MattressDialogProps: {},
    MtrldefErpDialogRef: null,
    MtrldefErpDialogProps: {},
    workgrpEnum: [],
    workgrpEnum2: [],
    configureTypeEnum: [],
    CodeMxDialogProps: null,
    CodeMxDialogRef: null,
    loadingStatus: {
      save: false,
      synchsL1: false,
      mtrldef: false,
      prdpf: false
    }
  });

  const QdAddRowList = [
    {
      itemname: "补充物料",
      bj_pzname: "边带",
      bj_pzname_mx: ""
    },
    {
      itemname: "补充物料",
      bj_pzname: "海绵芯",
      bj_pzname_mx: ""
    },
    {
      itemname: "补充物料",
      bj_pzname: "裥棉面线",
      bj_pzname_mx: ""
    },
    {
      itemname: "补充物料",
      bj_pzname: "裥棉底线",
      bj_pzname_mx: ""
    },
    {
      itemname: "补充物料",
      bj_pzname: "车位面线",
      bj_pzname_mx: ""
    },
    {
      itemname: "补充物料",
      bj_pzname: "车位底线",
      bj_pzname_mx: ""
    },
    {
      itemname: "补充物料",
      bj_pzname: "打底枪钉",
      bj_pzname_mx: ""
    },
    {
      itemname: "补充物料",
      bj_pzname: "胶水",
      bj_pzname_mx: ""
    },
    {
      itemname: "补充物料",
      bj_pzname: "围边用线",
      bj_pzname_mx: ""
    }
  ];

  const funcAddRowQd = async () => {
    const $table = state.QdTableRef?.element;

    if ($table) {
      $table.insertAt(QdAddRowList, -1);
      const { visibleData } = $table.getTableData();
      visibleData.map((o, idx) => {
        o.printid = idx + 1;
        return o;
      });

      $table.reloadData(visibleData);
      resetMergeCellsQd();
    }
  };

  const funcCmpCC = async () => {
    const $table = state.VxeTableMxRef?.element;

    if ($table) {
      $table.clearEdit();

      const mainData = state.LjDetailRef._mainData;

      const { visibleData } = $table.getTableData();
      console.log("visibleData :>> ", visibleData);
      visibleData.map((o, idx) => {
        if (["面层裥棉", "底层裥棉"].includes(o.bj_pzname)) {
          //生产尺寸：（(规格长)+2）*（(规格宽)+2）
          //锁边尺寸：（(规格长)-1）*（(规格宽)-1）
          o.actual_size = mainData.mattress_width + 2 + "*" + (mainData.mattress_length + 2);
          o.sb_craft = mainData.mattress_width - 1 + "*" + (mainData.mattress_length - 1);
        }
      });

      await $table.reloadData(visibleData);
      resetMergeCells();

      ElMessage.success("操作成功！");
    }
  };

  const toCreateORDelMtrlPf = (type: number, list: any) => {
    if (type === 1) {
      if (state.QdTableRef) {
        const $table = state.QdTableRef.element;
        if ($table) {
          $table.clearEdit();

          const { visibleData } = $table.getTableData();
          console.log("visibleData :>> ", visibleData);
          try {
            visibleData.map((o, idx) => {
              if (!o.erp_mtrlid && o.actual_useqty > 0) {
                state.QdTableRef.scrollTo(o, "erp_mtrlid");
                throw new Error(`第${idx + 1}行：产品补充未填入L1物料信息，请先选择L1物料修改`);
              }
            });
          } catch (error) {
            ElMessage.error(error.message);
            return false;
          }
        }
      }

      ElMessageBox.confirm(`是否确定要生成金蝶清单?`, "询问", {
        confirmButtonText: t("common.okText"),
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          state.loadingStatus.prdpf = true;
          CreatPrdPf({ list })
            .then(() => {
              ElNotification({
                title: "金蝶清单",
                message: "生成成功！",
                type: "success"
              });
              state.loadingStatus.prdpf = false;
            })
            .catch(error => {
              state.loadingStatus.prdpf = false;
            });
        })
        .catch((e: TypeError) => {
          console.log("e :>> ", e);
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    } else {
      ElMessageBox.confirm(`是否确定要删除金蝶清单?`, "询问", {
        confirmButtonText: t("common.delText"),
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          DelMtrlPf({ list }).then(() => {
            ElMessage.success("删除成功！");
          });
        })
        .catch((e: TypeError) => {
          console.log("e :>> ", e);
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  };
  const toCreateMtrl = (type: number, list: any) => {
    ElMessageBox.confirm(`是否确定要生成/更新物料?`, "询问", {
      confirmButtonText: t("common.okText"),
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        state.loadingStatus.mtrldef = true;
        CreatMtrlPf({ list })
          .then(res => {
            console.log("toCreateMtrl, res :>> ", res);
            if (state.LjDetailRef) {
              state.LjDetailRef._mainData.erp_mtrlid = res.mattress.erp_mtrlid;
              state.LjDetailRef._mainData.creatmtrl_flag = res.mattress.creatmtrl_flag;
              state.LjDetailRef._mainData.erp_mtrlcode = res.mattress.erp_mtrlcode;
            }
            ElNotification({
              title: "物料",
              message: "生成/更新成功！",
              type: "success"
            });

            state.loadingStatus.mtrldef = false;
          })
          .catch(error => {
            state.loadingStatus.mtrldef = false;
          });
      })
      .catch((e: TypeError) => {
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };

  // const toUpdateL1Planprice = (mattressid: number) => {
  //   ElMessageBox.confirm(`是否确定要更新计划价?`, "询问", {
  //     confirmButtonText: t("common.okText"),
  //     cancelButtonText: "否",
  //     type: "warning"
  //   })
  //     .then(() => {
  //       CreatMtrlPf({ mattressid }).then(() => {
  //         ElNotification({
  //           title: "更新计划价",
  //           message: "更新成功！",
  //           type: "success"
  //         });
  //       });
  //     })
  //     .catch((e: TypeError) => {
  //       console.log("e :>> ", e);
  //       ElMessage({
  //         type: "info",
  //         message: "操作取消"
  //       });
  //     });
  // };

  const ywFlagChange = (value: any) => {
    console.log("value :>> ", value);
    // console.log("Lj :>> ", state.LjDetailRef._mainData);
    value = parseInt(value ?? 0);
    // handleSelMxData(value);
    // fChangeBedNetType(value);
    switch (value) {
      case 2: // 待业务审
        state.initParams.yw_flag = 0;
        state.initParams.js1_flag = 0;
        state.initParams.js2_flag = 0;
        state.initParams.creatmtrl_flag = 0;
        state.initParams.creatmtrlqd_flag = 0;
        break;
      case 3: //待产品补充审
        state.initParams.yw_flag = 1;
        state.initParams.js1_flag = 0;
        state.initParams.js2_flag = 0;
        state.initParams.creatmtrl_flag = 0;
        state.initParams.creatmtrlqd_flag = 0;
        break;
      case 4: //待清单补充审
        state.initParams.yw_flag = 1;
        state.initParams.js1_flag = 1;
        state.initParams.js2_flag = 0;
        state.initParams.creatmtrl_flag = -1;
        state.initParams.creatmtrlqd_flag = -1;
        break;
      case 5: //待生成erp产品
        state.initParams.yw_flag = 1;
        state.initParams.js1_flag = 1;
        state.initParams.js2_flag = 1;
        state.initParams.creatmtrl_flag = 1;
        state.initParams.creatmtrlqd_flag = -1;
        break;
      case 6: //待生成erp清单
        state.initParams.yw_flag = 1;
        state.initParams.js1_flag = 1;
        state.initParams.js2_flag = 1;
        state.initParams.creatmtrl_flag = 1;
        state.initParams.creatmtrlqd_flag = 0;
        break;
      default:
        state.initParams.yw_flag = -1;
        state.initParams.js1_flag = -1;
        state.initParams.js2_flag = -1;
        state.initParams.creatmtrl_flag = -1;
        state.initParams.creatmtrlqd_flag = -1;
        break;
    }
  };

  /**
   * @description 选择物料弹窗
   */
  const fModelChoseMtrlErp = (data: any, params: any) => {
    return new Promise((resolve, reject) => {
      // if (!ALLOW_EDIT_STATE.includes(status)) return;
      console.log("fModelChoseMtrl fModelChoseMtrl params :>> ", params);
      let _params = {
        keyword: "",
        ...params
        // arg_mtrltype: params.mtrltype,
        // arg_pricelistid: _pricelistid
      };
      state.MtrldefErpDialogProps = {
        onSubmit: (res: any) => {
          // submit
          console.log("openCustDialog res", res);
          nextTick(() => {
            // cb(data, res.value[0]);
            rModelSetMtrlErp(data, res.value[0]);
            resolve(1);
          });
        },
        onCancel: (error: any) => {
          // cancel 回调
          console.log("openCustDialog error", error);
        }
      };
      state.MtrldefErpDialogRef.show(_params);
    });
  };

  const rModelSetMtrlErp = (data: any, item: any, attrStr: string = "") => {
    console.log("rModelSetMtrlErp item :>> ", item);
    if (item) {
      data.erp_mtrlid = item.mtrlid;
      data.erp_mtrlname = item.mtrlname;
      data.erp_mtrlmode = item.mtrlmode;
      attrStr != "erp_mtrlcode" && (data.erp_mtrlcode = item.mtrlcode);
      data.erp_unit = item.unit;
      attrStr != "erp_mtrlengname" && (data.erp_mtrlengname = item.zxmtrlmode);
    }
  };

  const rModelClearMtrlErp = (data: any, type: number) => {
    if (type == 1) {
      // 清空配置选项
      if (Number(data.erp_inputtype) != 2) {
        data.bj_namemx = "";
      }
    } else if (type == 2) {
      // 清空配置选项
      // if (Number(data.erp_inputtype) == 2) {
      data.erp_mtrlid = 0;
      data.erp_mtrlcode = "";
      data.erp_mtrlname = "";
      data.erp_mtrlmode = "";
      data.erp_unit = "";
      data.erp_mtrlengname = "";
      // }
    }
  };

  const rModelSetCodemx = (data: any, item: any, $table?: any) => {
    if (item) {
      data.bj_namemx = item.namemx;
    } else {
      data.bj_namemx = "";
    }

    // cb && cb();
    if ($table) {
      $table.clearEdit();
      nextTick(() => {
        $table.setActiveRow(data);
      });
    }
  };
  const rModelClearCodemx = (data: any, $table?: any) => {
    data.bj_namemx = "";

    if ($table) {
      $table.clearEdit();
    }
  };

  // 表格配置项
  const columns: ColumnProps<any>[] = [
    { type: "checkbox", width: 40, fixed: "left" },
    { title: "#", type: "seq", fixed: "left", width: 80 },
    {
      field: "yw_flag",
      title: "业务审核",
      search: {
        // el: "select",
        render: scope => {
          // let _keys = Object.keys(scope);
          // let _data = _keys.includes("row") ? scope.row : _keys.includes("searchParam") ? scope.searchParam : scope;
          return (
            <el-select v-model={scope.searchParam.status_flag} placeholder="全部" clearable onChange={ywFlagChange}>
              <el-option label="待业务审" value="2" />
              <el-option label="待产品补充审" value="3" />
              <el-option label="待清单补充审" value="4" />
              <el-option label="待生成erp产品" value="5" />
              <el-option label="待生成erp清单" value="6" />
            </el-select>
          );
        }
      }
    },
    {
      field: "js1_flag",
      title: "产品补充审核"
    },
    {
      field: "js2_flag",
      title: "清单补充审核"
    },
    {
      field: "creatmtrl_flag",
      title: "生成L1产品"
    },
    {
      field: "creatmtrlqd_flag",
      title: "生成L1清单"
    },
    {
      field: "erp_mtrlcode",
      title: "L1物料编码",
      search: {
        el: "input",
        key: "arg_search"
      }
    },
    {
      field: "deptid",
      title: "部门",
      width: 120,
      search: {
        el: "select",
        key: "arg_deptid",
        props: {
          filterable: true,
          onChange: (value: any) => {
            state.initParams.arg_deptid = value;
          }
        },
        order: 1
      }
    },
    {
      field: "mattresscode",
      title: "报价唯一码"
    },
    {
      field: "mattressrelcode",
      title: "核价编码"
    },
    {
      field: "mattressname",
      title: "核价名称",
      treeNode: true,
      render: scope => {
        return !scope.row?.child_count && !scope.row?.parentid ? (
          scope.row?.mattressname
        ) : scope.row?.parentid ? (
          <div class="flx-justify-between">
            <span class="mle">{scope.row?.mattressname}</span>
            <el-tag type="warning" effect="light" disable-transitions size="small" round class="ml-4">
              副
            </el-tag>
          </div>
        ) : (
          <div class="flx-justify-between">
            <span class="mle">{scope.row?.mattressname}</span>
            <el-tag type="primary" effect="light" disable-transitions size="small" round class="ml-4">
              主
            </el-tag>
          </div>
        );
      }
    },
    {
      field: "mattresstypeid",
      title: "床垫类别"
    },
    {
      field: "mattress_width",
      title: "床垫宽/CM"
    },
    {
      field: "mattress_length",
      title: "床垫长/CM"
    },
    {
      field: "mattress_height",
      title: "床垫高/CM"
    },
    {
      field: "createby",
      title: "登记人"
    },
    {
      field: "createtime",
      title: "登记时间"
    },
    {
      field: "yw_auditingrep",
      title: "业务审核人"
    },
    {
      field: "yw_auditingdate",
      title: "业务审核时间"
      // table: "u_mattress_interface",
      // enum: [
      //   { label: "业务审核时间", value: 0 },
      //   { label: "产品补充审核时间", value: 1 },
      //   { label: "清单补充审核时间", value: 2 }
      // ],
      // search: {
      //   el: "select",
      //   key: "arg_datetype",
      //   props: {
      //     filterable: true,
      //     defaultFirstOption: true
      //   }
      // }
    },
    {
      field: "js1_auditingrep",
      title: "产品补充审核人"
    },
    {
      field: "js1_auditingdate",
      title: "产品补充审核时间"
      // table: "u_mattress_interface",
      // search: {
      //   el: "date-picker",
      //   key: "arg_firstdate",
      //   props: {
      //     type: "date"
      //   }
      // }
    },
    {
      field: "js2_auditingrep",
      title: "清单补充审核人"
    },
    {
      field: "js2_auditingdate",
      title: "清单补充审核时间"
      // table: "u_mattress_interface",
      // search: {
      //   el: "date-picker",
      //   key: "arg_enddate",
      //   props: {
      //     type: "date"
      //   }
      // }
    },
    {
      field: "creatmtrl_auditingrep",
      title: "生成L1产品人"
    },
    {
      field: "creatmtrl_auditingdate",
      title: "生成L1产品时间"
    },
    {
      field: "creatmtrlqd_auditingrep",
      title: "生成L1清单人"
    },
    {
      field: "creatmtrlqd_auditingdate",
      title: "生成L1清单时间"
    },
    {
      field: "dijia_cost",
      title: "底价"
    },
    {
      field: "yongjin",
      title: "佣金",
      render: (scope: any) => {
        let result = floatSub(floatDiv(scope.row.dijia_cost, floatSub(1, scope.row.commission - 1)), scope.row.dijia_cost);
        result = formatFixedNumber({ val: result });
        return result;
      }
    },
    {
      field: "taxrate",
      title: "税率"
    },
    {
      field: "fob",
      title: "FOB"
    },
    {
      field: "taxes",
      title: "税金"
    },
    {
      field: "erp_mtrlengname",
      title: "原物料编码"
    },
    {
      field: "erp_configcodetype",
      title: "ERP配置类型"
    }
  ];

  const columns_detail: ColumnProps<any>[] = [
    {
      field: "erp_mtrlcode",
      title: "系统物料编码",
      basicinfo: {
        el: "input",
        // props: {
        //   clearable: true,
        //   onClick: (scope: any) => {
        //     console.log("columns_detail scope :>> ", scope);
        //     // fModelChoseMtrl()
        //   }
        // },
        // editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 1,
        span: 1
      }
    },
    {
      field: "erp_mtrlname",
      title: "系统物料名称",
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 4,
        span: 1
      }
    },
    {
      field: "erp_mtrlmode",
      title: "物料规格",
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 2,
        span: 1
      }
    },
    {
      field: "erp_mtrlunit",
      title: "物料单位",
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 5,
        span: 1,
        rules: [{ required: true, message: "物料单位不能为空" }]
      }
    },
    {
      field: "erp_mtrltypeid",
      title: "物料类别",
      basicinfo: {
        el: "tree-select",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 3,
        span: 1,
        props: {
          filterable: true
          // onChange: ()=> {

          // },
          // renderContent: data => {
          //   console.log("erp_mtrltypeid value data :>> ", data);
          //   return <div>321</div>;
          // }
        }
      },
      enum: async () => {
        const data = await GetERPMtrlTypeList();
        console.log("GetERPMtrlTypeList data :>> ", data?.reList);
        return transformTreeData(data.reList);
      },
      fieldNames: {
        label: "mtrltype",
        value: "mtrltypeid",
        children: "children"
      }
    },
    {
      field: "erp_configcodetype",
      title: "配置类型",
      basicinfo: {
        el: "select",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 6,
        span: 1
      },
      enum: async () => {
        const data = await getConfigureTypeList({});

        console.log("data configureTypeEnum:>> ", data);

        // let dataEnum = data.datatable.map(item => {
        //   return {
        //     label: item.configuretypename,
        //     value: item.configuretypeid
        //   };
        // });
        return data.datatable;
      },
      fieldNames: {
        label: "contfigtypename",
        value: "contfigtypeid"
      }
    },
    {
      field: "mattresscode",
      title: "图号(床垫唯一码)",
      basicinfo: {
        el: "input",
        editable: () => {
          return false;
        },
        group: "单据信息",
        order: 9,
        span: 1
      }
    },
    {
      field: "erp_mtrlengname",
      title: "旧床垫编码",
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 7,
        span: 1
      }
    },
    {
      field: "old_mtrlname",
      title: "旧物料名称",
      basicinfo: {
        el: "input",
        editable: ALLOW_EDIT_STATE,
        group: "单据信息",
        order: 8,
        span: 1
      }
    }
  ];

  const columns_yw: ColumnProps<any>[] = [
    {
      field: "printid",
      title: "排序",
      width: 80
    },
    {
      field: "itemname",
      title: "项目",
      width: 120
    },
    {
      field: "bj_pzname",
      title: "核价_配置名称"
    },
    {
      field: "erp_pzcode",
      title: "ERP配置编码",
      width: 100
    },
    {
      field: "erp_pzname",
      title: "ERP配置名称",
      width: 120
    },
    {
      field: "bj_inputtype",
      title: "录入类型",
      width: 80,
      enum: [
        {
          value: 0,
          label: "选择"
        },
        {
          value: 1,
          label: "录入"
        },
        {
          value: 2,
          label: "带出"
        }
      ],
      editRender: {
        name: "$select",
        options: [
          {
            value: 0,
            label: "选择"
          },
          {
            value: 1,
            label: "录入"
          },
          {
            value: 2,
            label: "带出"
          }
        ]
      }
    },
    {
      field: "bj_namemx",
      title: "明细名称",
      width: 280,
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;

        // console.log("bj_namemx scope :>> ", scope);
        let params = {
          pzid: row.erp_pzid
        };

        if (row.bj_inputtype == 0) {
          return (
            <CodemxSelect
              value={scope.row.bj_namemx}
              {...params}
              clearable
              placeholder="请选择配置"
              onOpenModal={() => fModelChoseCodeMx(row, params, rModelSetCodemx, scope.row.bj_namemx, $table)}
              onSelect={val => rModelSetCodemx(scope.row, val, $table)}
              onClear={() => rModelClearCodemx(scope.row, $table)}
            ></CodemxSelect>
          );
        } else if (row.bj_inputtype == 1) {
          return <el-input v-model={scope.row.bj_namemx} />;
        } else {
          return <span>{row.bj_namemx}</span>;
        }
      }
    },
    {
      field: "actual_size",
      title: "生产尺寸",
      limited: () => {
        return state.editType == 1;
      },
      editRender: {
        name: "$input"
      }
    },
    {
      field: "sb_craft",
      title: "锁边工艺",
      limited: () => {
        return state.editType == 1;
      },
      editRender: {
        name: "$input"
      }
    },
    {
      field: "actual_size_sb",
      title: "锁边后尺寸",
      limited: () => {
        return state.editType == 1;
      },
      editRender: {
        name: "$input"
      }
    },
    {
      field: "ss_rate",
      title: "收缩率",
      limited: () => {
        return state.editType == 1;
      },
      datatype: "number",
      editRender: {
        name: "$input"
      }
    },
    {
      field: "ls_rate",
      title: "拉伸率",
      limited: () => {
        return state.editType == 1;
      },
      datatype: "number",
      editRender: {
        name: "$input"
      }
    }
  ];

  const columns_yw_qd: ColumnProps<any>[] = [
    {
      field: "bj_pzname",
      title: "核价_配置名称"
    },
    {
      field: "bj_namemx",
      title: "明细名称"
    },
    {
      field: "actual_size",
      title: "生产尺寸",
      limited: () => {
        return state.editType == 1;
      }
    },
    {
      field: "printid",
      title: "排序",
      width: 80
    },
    {
      field: "erp_pzcode",
      title: "ERP配置编码"
    },
    {
      field: "erp_pzname",
      title: "ERP配置名称"
    },
    {
      field: "bj_inputtype",
      title: "录入类型",
      width: 80,
      enum: [
        {
          value: "0",
          label: "选择"
        },
        {
          value: "1",
          label: "录入"
        },
        {
          value: "2",
          label: "带出"
        }
      ]
    },
    {
      field: "itemname",
      title: "项目"
    },
    {
      field: "sb_craft",
      title: "锁边工艺",
      limited: () => {
        return state.editType == 1;
      }
    },
    {
      field: "actual_size_sb",
      title: "锁边后尺寸",
      limited: () => {
        return state.editType == 1;
      }
    },
    {
      field: "ss_rate",
      title: "收缩率",
      limited: () => {
        return state.editType == 1;
      },
      datatype: "number"
    },
    {
      field: "ls_rate",
      title: "拉伸率",
      limited: () => {
        return state.editType == 1;
      },
      datatype: "number"
    }
  ];

  const enumMap = inject("enumMap", ref(new Map()));
  const workgrpEnum = computed(() => {
    console.log('领用工组领用工组领用工组领用工组 enumMap.value.get("wrkgrpid") :>> ', enumMap.value.get("wrkgrpid"));
    return enumMap.value.get("wrkgrpid");
  });

  const wipTypeEnum = [
    {
      label: "面裥绵",
      value: "面裥绵"
    },
    {
      label: "底裥绵",
      value: "底裥绵"
    },
    {
      label: "大侧裥绵",
      value: "大侧裥绵"
    },
    {
      label: "小侧裥绵1",
      value: "小侧裥绵1"
    },
    {
      label: "小侧裥棉2",
      value: "小侧裥棉2"
    },
    {
      label: "V侧裥绵1",
      value: "V侧裥绵1"
    },
    {
      label: "V侧裥绵2",
      value: "V侧裥绵2"
    },
    {
      label: "顶布1",
      value: "顶布1"
    },
    {
      label: "顶布2",
      value: "顶布2"
    },
    {
      label: "顶布3",
      value: "顶布3"
    }
  ];

  const columns_qd = ref<ColumnProps<any>[]>([
    { title: "#", type: "seq", fixed: "left", width: 60, dragSort: true },
    // {
    //   field: "printid",
    //   title: "排序",
    //   width: 80,
    //   fixed: "left",
    //   dragSort: true
    // },
    {
      field: "itemname",
      title: "项目",
      width: 100,
      fixed: "left"
    },
    {
      field: "bj_pzname",
      title: "二级项目",
      fixed: "left",
      width: 120
    },
    {
      field: "bj_pzname_mx",
      title: "明细项目",
      width: 100,
      fixed: "left"
    },
    {
      field: "bj_pzname_mx_mx",
      title: "二级明细项目",
      fixed: "left"
    },
    {
      field: "wip_type",
      title: "半成品归属",
      width: 120,
      editRender: {
        autoFocus: true
      },
      editColRender: (scope: any) => {
        // console.log("formulakind editColRender scope :>> ", scope);
        return (
          <el-select v-model={scope.row.wip_type} filterable clearable>
            {{
              default: () => {
                let rs = [];
                wipTypeEnum.map((t: any) => {
                  rs.push(<el-option label={t.label} value={t.value} />);
                });
                return rs;
              }
              // label: ({ label, value }) => label
            }}
          </el-select>
        );
      }
    },
    {
      field: "erp_mtrlcode",
      title: "L1物料编码",
      // limited: () => {
      //   return state.editType == 1 || state.editType == 2;
      // },
      // editRender: {
      //   name: "$input"
      // }
      editRender: {
        // name: "$select"
        autoFocus: "input"
      },
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;

        let params = {
          keyword: row.erp_mtrlcode
        };

        return (
          <MtrldefErpInput
            v-model={row.erp_mtrlcode}
            valueKey="erp_mtrlcode"
            row={row}
            setMtrlerp={rModelSetMtrlErp}
            onOpenModal={() => fModelChoseMtrlErp(row, params)}
            onClear={() => rModelClearMtrlErp(row, 2)}
          ></MtrldefErpInput>
        );
      }
    },
    {
      field: "dscrp",
      title: "备注",
      editRender: {
        name: "$input"
      }
    },
    {
      field: "erp_mtrlengname",
      title: "旧物料名称",
      limited: () => {
        return state.editType == 1 || state.editType == 2;
      },
      editRender: {},
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;

        return (
          <MtrldefErpInput
            v-model={row.erp_mtrlengname}
            valueKey="erp_mtrlengname"
            row={row}
            setMtrlerp={rModelSetMtrlErp}
            onOpenModal={() => fModelChoseMtrlErp(row, {})}
            onClear={() => rModelClearMtrlErp(row, 2)}
          ></MtrldefErpInput>
        );
      }
    },
    {
      field: "erp_mtrlname",
      title: "L1物料名称",
      limited: () => {
        return state.editType == 1 || state.editType == 2;
      }
    },
    {
      field: "ss_rate",
      title: "收缩率",
      datatype: "number",
      editRender: {
        name: "$input"
      }
    },
    {
      field: "erp_mtrlmode",
      title: "L1物料规格",
      limited: () => {
        return state.editType == 1 || state.editType == 2;
      }
    },
    {
      field: "qd_actual_size",
      title: "实际尺寸",
      editRender: {
        name: "$input"
      }
    },
    {
      field: "qd_pfgroupqty",
      title: "条数",
      width: 80,
      editRender: {
        name: "$input"
      }
    },
    {
      field: "ls_rate",
      title: "拉伸率",
      datatype: "number",
      editRender: {
        name: "$input"
      }
    },
    {
      field: "erp_unit",
      title: "L1物料单位",
      limited: () => {
        return state.editType == 1 || state.editType == 2;
      }
    },
    {
      field: "sh_rate",
      title: "损耗率",
      datatype: "number",
      editRender: {
        name: "$input"
      }
    },
    {
      field: "useqty",
      title: "参考用料量",
      datatype: "number",
      limited: () => {
        return state.editType == 1 || state.editType == 2;
      }
    },
    {
      field: "actual_useqty",
      title: "实际用量",
      datatype: "number",
      editRender: {
        name: "$input"
      },
      limited: () => {
        return state.editType == 1 || state.editType == 2;
      }
    },
    {
      field: "wrkgrpid",
      title: "领用工组",
      // enum: async () => {
      //   const data = await GetERPWrkGrpList();
      //   console.log("领用工组领用工组领用工组领用工组 data :>> ", data);
      //   return { data: data.workgroupList };
      // },
      // fieldNames: { label: "wrkgrpname", value: "wrkgrpid" },
      // enum: async () => {
      //   console.log("领用工组领用工组领用工组领用工组 state.workgrpEnum :>> ", state.workgrpEnum);
      //   return { data: state.workgrpEnum };
      // },
      isFilterEnum: true,
      editRender: {
        // name: "$select"
        autoFocus: true
      },
      editColRender: (scope: any) => {
        // console.log("formulakind editColRender scope :>> ", scope);
        return (
          <el-select v-model={scope.row.wrkgrpid} filterable clearable onChange={val => rModelSetWrkgrp1(val, scope.row)}>
            {{
              default: () => {
                let rs = [];
                if (state.workgrpEnum.length) {
                  state.workgrpEnum.map((t: any) => {
                    rs.push(<el-option label={`${t.code} - ${t.label}`} value={t.value} />);
                  });
                }
                return rs;
              },
              label: ({ label, value }) => label
            }}
          </el-select>
        );
      },
      render: scope => {
        let item = state.workgrpEnum.find(t => t.value == scope.row.wrkgrpid);
        if (item) {
          return item.code + " - " + item.label;
        } else {
          return "";
        }
      }
    },
    {
      field: "wrkgrpid2",
      title: "领用工组（新L1）",
      // enum: async () => {
      //   const data = await GetERPWrkGrpList();
      //   console.log("领用工组领用工组领用工组领用工组 data :>> ", data);
      //   return { data: data.workgroupList };
      // },
      // fieldNames: { label: "wrkgrpname", value: "wrkgrpid" },
      // enum: async () => {
      //   console.log("领用工组领用工组领用工组领用工组 state.workgrpEnum :>> ", state.workgrpEnum);
      //   return { data: state.workgrpEnum };
      // },
      isFilterEnum: true,
      editRender: {
        // name: "$select"
        autoFocus: "input"
      },
      editColRender: (scope: any) => {
        // console.log("formulakind editColRender scope :>> ", scope);
        return (
          <el-select v-model={scope.row.wrkgrpid2} filterable clearable onChange={val => rModelSetWrkgrp2(val, scope.row)}>
            {{
              default: () => {
                let rs = [];
                if (state.workgrpEnum2.length) {
                  state.workgrpEnum2.map((t: any) => {
                    rs.push(<el-option label={`${t.code} - ${t.label}`} value={t.value} />);
                  });
                }
                return rs;
              },
              label: ({ label, value }) => label
            }}
          </el-select>
        );
      },
      render: scope => {
        let item = state.workgrpEnum2.find(t => t.value == scope.row.wrkgrpid2);
        if (item) {
          return item.code + " - " + item.label;
        } else {
          return "";
        }
      }
    }
  ]);

  const rModelSetWrkgrp1 = (value: any, data: any) => {
    let item = state.workgrpEnum.find(t => t.value == value);
    if (item) {
      data.wrkgrpcode1 = item.code;
    }
  };

  const rModelSetWrkgrp2 = (value: any, data: any) => {
    let item = state.workgrpEnum2.find(t => t.value == value);
    if (item) {
      data.wrkgrpcode2 = item.code;
    }
  };

  // const columns_export = [
  //   {
  //     name: "行号",
  //     field: "pid",
  //   },
  //   {
  //     name: "层",
  //     field: "lp",
  //   },
  //   {
  //     name: "",
  //     field: "lp_tree",
  //   },
  //   {
  //     name: "序",
  //     field: "u_prdpf_printid",
  //   },
  //   {
  //     name: "工艺模板编码",
  //     field: "mb_mtrlcode",
  //   },
  //   {
  //     name: "物料编码",
  //     field: "u_mtrldef_mtrlcode",
  //   },
  //   {
  //     name: "来源",
  //     field: "u_mtrldef_mtrlorigin",
  //   },
  //   {
  //     name: "物料属性",
  //     field: "u_mtrldef_mtrlprp",
  //   },
  //   {
  //     name: "物料名称",
  //     field: "u_mtrldef_mtrlname",
  //   },
  //   {
  //     name: "物料规格",
  //     field: "u_mtrldef_mtrlmode",
  //   },
  //   {
  //     name: "库存 单位",
  //     field: "u_mtrldef_unit",
  //   },
  //   {
  //     name: "物料类别",
  //     field: "u_mtrldef_mtrltypeid",
  //   },
  //   {
  //     name: "弹簧数",
  //     field: "u_mtrldef_mtrlsectype",
  //   },
  //   {
  //     name: "旧编码",
  //     field: "u_mtrldef_zxmtrlmode",
  //   },
  //   {
  //     name: "旧产品名称",
  //     field: "u_mtrldef_usermtrlmode",
  //   },
  //   {
  //     name: "图号",
  //     field: "u_mtrldef_piccode",
  //   },
  //   {
  //     name: "排产属性",
  //     field: "u_mtrldef_ifselforder",
  //   },
  //   {
  //     name: "计划属性",
  //     field: "u_mtrldef_ordertype",
  //   },
  //   {
  //     name: "默认 制造分部",
  //     field: "u_mtrldef_scid",
  //   },
  //   {
  //     name: "默认 制造车间",
  //     field: "u_mtrldef_dftwrkgrpid",
  //   },
  //   {
  //     name: "板件属性",
  //     field: "u_mtrldef_bantype",
  //   },
  //   {
  //     name: "安装序号",
  //     field: "u_prdpf_azcode",
  //   },
  //   {
  //     name: "部件名称",
  //     field: "u_prdpf_pfgroup",
  //   },
  //   {
  //     name: "部件 数",
  //     field: "u_prdpf_pfgroupqty",
  //   },
  //   {
  //     name: "部件规格",
  //     field: "u_prdpf_pfgroupmode",
  //   },
  //   {
  //     name: "部件代号",
  //     field: "u_prdpf_promode",
  //   },
  //   {
  //     name: "开料规格",
  //     field: "u_prdpf_pfklmode",
  //   },
  //   {
  //     name: "领料组",
  //     field: "u_prdpf_wrkgrpid",
  //   },
  //   {
  //     name: "用料量",
  //     field: "u_prdpf_sonscale",
  //   },
  //   {
  //     name: "损耗率",
  //     field: "u_prdpf_sonloss",
  //   },
  //   {
  //     name: "损附加",
  //     field: "u_prdpf_sondecloss",
  //   },
  //   {
  //     name: "配置",
  //     field: "u_prdpf_status",
  //   },
  //   {
  //     name: "配置1",
  //     field: "u_prdpf_woodcode",
  //   },
  //   {
  //     name: "配置2",
  //     field: "u_prdpf_pcode",
  //   },
  //   {
  //     name: "生产 提前期(天)",
  //     field: "u_prdpf_sonahead",
  //   },
  //   {
  //     name: "清单",
  //     field: "u_prdpf_sonpfcode",
  //   },
  //   {
  //     name: "说明",
  //     field: "u_prdpf_dscrp",
  //   },
  //   {
  //     name: "发料用 损耗率",
  //     field: "u_prdpf_scllloss",
  //   },
  //   {
  //     name: "发料用 损耗附加",
  //     field: "u_prdpf_sclldecloss",
  //   },
  //   {
  //     name: "按配置 拆装",
  //     field: "u_prdpf_ifover",
  //   },
  //   {
  //     name: "拆装 运算配置",
  //     field: "u_prdpf_dipztype",
  //   },
  //   {
  //     name: "采购 参数",
  //     field: "u_prdpf_buyarg",
  //   },
  //   {
  //     name: "生产 保险期(天)",
  //     field: "u_mtrldef_orderdays",
  //   },
  //   {
  //     name: "采购 周期(天)",
  //     field: "u_mtrldef_buydays",
  //   },
  //   {
  //     name: "外协 周期(天)",
  //     field: "u_mtrldef_wfjgdays",
  //   },
  //   {
  //     name: "出仓类型",
  //     field: "u_mtrldef_outtype",
  //   },
  //   {
  //     name: "密度(kg/m³)",
  //     field: "u_mtrldef_midu",
  //   },
  //   {
  //     name: "物料备注",
  //     field: "u_mtrldef_dscrp",
  //   },
  //   {
  //     name: "单件体积(m³)",
  //     field: "cubage",
  //   },
  //   {
  //     name: "长度(mm)",
  //     field: "length",
  //   },
  //   {
  //     name: "宽度(mm)",
  //     field: "width",
  //   },
  //   {
  //     name: "工艺路线模板(双击选择)",
  //     field: "u_prdpf_modlename",
  //   },
  //   {
  //     name: "清单-纹理方向",
  //     field: "u_prdpf_wenli",
  //   },
  //   {
  //     name: "清单-封边信息",
  //     field: "u_prdpf_fengbian",
  //   },
  //   {
  //     name: "清单-排孔信息",
  //     field: "u_prdpf_paikong",
  //   },
  //   {
  //     name: "清单-锣机信息",
  //     field: "u_prdpf_luoji",
  //   },
  //   {
  //     name: "清单-喷油（吸塑）信",
  //     field: "u_prdpf_penyou",
  //   },
  //   {
  //     name: "包件",
  //     field: "u_mtrldef_ifpack",
  //   },
  //   {
  //     name: "物料-部件代号",
  //     field: "u_mtrldef_ban_promode",
  //   },
  //   {
  //     name: "物料-开料规格",
  //     field: "u_mtrldef_ban_pfklmode",
  //   },
  //   {
  //     name: "物料-纹理方向",
  //     field: "u_mtrldef_ban_wenli",
  //   },
  //   {
  //     name: "物料-封边信息",
  //     field: "u_mtrldef_ban_fengbian",
  //   },
  //   {
  //     name: "物料-排孔信息",
  //     field: "u_mtrldef_ban_paikong",
  //   },
  //   {
  //     name: "物料-锣机信息",
  //     field: "u_mtrldef_ban_luoji",
  //   },
  //   {
  //     name: "物料-喷油（吸塑）信息",
  //     field: "u_mtrldef_ban_penyou",
  //   },
  //   {
  //     name: "物料-工艺备注",
  //     field: "u_mtrldef_ban_gydscrp",
  //   },
  //   {
  //     name: "摆放方向",
  //     field: "u_mtrldef_ban_direction",
  //   },
  //   {
  //     name: "物料ID",
  //     field: "u_mtrldef_mtrlid",
  //   },
  //   {
  //     name: "虚拟进出",
  //     field: "u_mtrldef_xninoutflag",
  //   },
  //   {
  //     name: "产品选配值",
  //     field: "config_val",
  //   },
  //   {
  //     name: "当前物料开料规格",
  //     field: "u_mtrldef_pfklmode_son",
  //   },
  //   {
  //     name: "上级物料开料规格",
  //     field: "u_mtrldef_pfklmode_p",
  //   },
  // ];

  const tableProps_mx = ref<any>({
    height: "auto",
    align: "left",
    // height: "",
    sortConfig: {
      trigger: "manual"
    },
    editConfig: {
      trigger: "click",
      mode: "cell",
      enabled: false
      // afterEditMethod: ({ row, rowIndex, column, columnIndex }) => {
      //   console.log("afterEditMethod :>> ", row);
      // }
      // beforeEditMethod: ({ row, rowIndex, column, columnIndex }) => {
      //   console.log("state.editType == 1 :>> ", state.editType, column.field);
      //   if (state.editType == 1) {
      //     if (["bj_inputtype"].includes(column.field)) {
      //       return false;
      //     }
      //   }
      //   return true;
      // }
    },
    showOverflow: false,
    // exportConfig: {
    //   filename: t("menu.saleTaskCrmDetail") + formatToDate(new Date(), "YYYY-MM-DDHH:mm:ss")
    // }
    keyboardConfig: {
      isEdit: true,
      isArrow: true,
      isEnter: true,
      isTab: true,
      isDel: true,
      isBack: true,
      isEsc: true,
      editMethod({ $table, row, column }) {
        // 先清空原先的值
        row[column.field] = "";
        // 再激活编辑状态并输入新值
        $table.setEditCell(row, column);
      }
    },
    mouseConfig: {
      selected: true
    }
  });

  const tableProps_qd = ref<any>({
    height: "auto",
    align: "left",
    // height: "",
    sortConfig: {
      trigger: "manual"
    },
    editConfig: {
      trigger: "click",
      mode: "cell",
      enabled: false,
      // afterEditMethod: ({ row, rowIndex, column, columnIndex }) => {
      //   console.log("afterEditMethod :>> ", row);
      // }
      beforeEditMethod: ({ row, rowIndex, column, columnIndex }) => {
        console.log("state.editType == 1 :>> ", state.editType, column.field);
        if (state.editType == 1) {
          if (["bj_inputtype"].includes(column.field)) {
            return false;
          }
        }
        return true;
      }
    },
    showOverflow: false,
    // exportConfig: {
    //   filename: t("menu.saleTaskCrmDetail") + formatToDate(new Date(), "YYYY-MM-DDHH:mm:ss")
    // }
    keyboardConfig: {
      isEdit: true,
      isArrow: true,
      isEnter: true,
      isTab: true,
      isDel: true,
      isBack: true,
      isEsc: true,
      editMethod({ $table, row, column }) {
        // 先清空原先的值
        row[column.field] = "";
        // 再激活编辑状态并输入新值
        $table.setEditCell(row, column);
      }
    },
    mouseConfig: {
      selected: true
    },
    rowConfig: {
      drag: true
    },
    rowDragConfig: {
      trigger: "cell",
      showGuidesStatus: true
    }
  });

  const resetMergeCells = (cb?: any) => {
    nextTick(() => {
      const $table = state.YwTableRef.element;
      const $table2 = state.VxeTableMxRef.element;
      if ($table) {
        let mergeCells = autoMergeCells($table, ["itemname"]);
        $table.setMergeCells(mergeCells);
      }
      if ($table2) {
        let mergeCells = autoMergeCells($table2, ["itemname"]);
        $table2.setMergeCells(mergeCells);

        cb && cb();
      }
    });
  };
  const resetMergeCellsQd = (cb?: any) => {
    setTimeout(() => {
      nextTick(() => {
        const $table = state.QdTableRef?.element;
        if ($table) {
          let mergeCells = autoMergeCells($table, ["itemname", "bj_pzname", "bj_pzname_mx_mx"]);
          // console.log("autoMergeCells mergeCells :>> ", mergeCells);
          $table.setMergeCells(mergeCells);

          cb && cb();
        }
      });
    }, 200);
  };

  /**
   * 获取产品配置，产品清单
   * @param mattressid 床垫ID
   */
  const RetriveMattressInterface = async (mattressid: number) => {
    let res = await GetMattressInterfaceList({ mattressid, isEdit: Number(state.orderStatus != "") });
    if (res.ErrMsg) {
      ElNotification({
        title: "温馨提示",
        message: res.ErrMsg,
        type: "error"
      });
    }
    state.mainData = [res.mattress];
    state.mattressYWList = res.interfaceList;
    state.mattressQDList = res.qdList;

    resetMergeCells();
    resetMergeCellsQd();
  };
  /**
   * 刷新产品配置
   * @param mattressid 床垫ID
   * @param isPz 类型 0 - 刷新 1 - 复制 2 - 重新生成
   */
  const RefreshMattressInterfaceList = async (mattressid: number, isPz: number, configcodetype: number = 0) => {
    let res = await RefreshMattressInterface({ mattressid, isPz: isPz, configcodetype });

    const $table = state.YwTableRef?.element;
    let { visibleData } = $table.getTableData();
    const copyMap = new Map();
    let matchQty = 0;

    const COMMON_PRESERVED_PROPS = ["bj_inputtype", "erp_pzname", "erp_pzcode", "bj_pzname", "bj_namemx", "itemname"];
    const SPECIAL_PRESERVED_PROPS = ["actual_size", "sb_craft", "actual_size_sb", "ss_rate", "ls_rate"];
    const FULL_PRESERVED_PROPS = [...COMMON_PRESERVED_PROPS, ...SPECIAL_PRESERVED_PROPS];
    //  inputtype 0 - 选择 1 - 录入 2 - 带出
    if (isPz === 0) {
      // 刷新配置 FEAT: 只刷新【带出】类型的配置，只刷新明细名称列，并检查核价是否有新增的【带出】类型资料，添加到配置
      visibleData.forEach(mx => {
        copyMap.set(`${mx.erp_pzid}`, mx);
      });

      state.mattressYWList = res.mxList.map(mx => {
        const key = `${mx.erp_pzid}`;
        if (copyMap.has(key)) {
          matchQty++;
          const mx2 = copyMap.get(key);
          if (mx2.bj_inputtype === 2) {
            SPECIAL_PRESERVED_PROPS.forEach(prop => {
              mx[prop] = mx2[prop];
            });
          } else {
            FULL_PRESERVED_PROPS.forEach(prop => {
              mx[prop] = mx2[prop];
            });
          }
        }
        return mx;
      });
    } else if (isPz === 1) {
      // 复制配置 FEAT:只复制录入和选择类型的配置，生产信息不覆盖
      const NEED_PROPS = ["bj_inputtype", "bj_namemx"];
      res.mxList.forEach(mx => copyMap.set(`${mx.erp_pzid}`, mx));

      state.mattressYWList = visibleData.map(mx => {
        const key = `${mx.erp_pzid}`;
        if (copyMap.has(key) && (mx.bj_inputtype === 1 || mx.bj_inputtype === 0)) {
          matchQty++;
          NEED_PROPS.forEach(prop => {
            mx[prop] = copyMap.get(key)[prop];
          });
        }
        return mx;
      });

      // state.mattressYWList = visibleData.map((mx: any) => mx);
    } else {
      // 重新生成：  FEAT: 删除所有已经填写的【录入】和【选择)项目，根据核价资料，重新生成所有的【带出】资料
      visibleData.forEach(mx => copyMap.set(`${mx.erp_pzid}`, mx));
      state.mattressYWList = res.mxList.map(mx => {
        const key = `${mx.erp_pzid}`;
        if (copyMap.has(key)) {
          matchQty++;
          SPECIAL_PRESERVED_PROPS.forEach(prop => {
            mx[prop] = copyMap.get(key)[prop];
          });
        }
        return mx;
      });
    }

    if (res.mxList.length > 0) {
      await $table.reloadData(state.mattressYWList);
      resetMergeCells();

      ElNotification({
        title: "刷新成功",
        message: `成功匹配${matchQty}条数据`,
        type: "success"
      });
    } else {
      ElNotification({
        title: "刷新失败",
        message: "暂无配置数据(mattressid: " + mattressid + ")",
        type: "warning"
      });
    }
  };
  /**
   * 刷新产品清单
   * @param mattressid 床垫ID
   * @param isPz 类型 0 - 刷新 1 - 复制 2 - 重新生成
   */
  const RefreshMattressInterfaceQdList = async (mattressid: number, isPz: number, isCheck?: number) => {
    isCheck = isCheck ?? 1;

    let res = await RefreshMattressInterfaceQd({ mattressid, isPz, isCheck });

    let matchQty = 0;

    const interfaceMap = {};
    state.mattressYWList.forEach(mb => {
      interfaceMap[mb.bj_pzname] = mb;
    });

    // 遍历 qdList 并使用哈希表来查找和赋值
    res.mxList.forEach(mx => {
      const mb = interfaceMap[mx.bj_pzname];
      if (mb) {
        mx.bj_pzname_mx_mx = mb.bj_namemx;

        if (mx.ss_rate === 0) {
          mx.ss_rate = mb.ss_rate;
        }

        if (mx.ls_rate === 0) {
          mx.ls_rate = mb.ls_rate;
        }
      }
    });

    const $table = state.QdTableRef?.element;
    let { visibleData } = $table.getTableData();
    const copyMap = new Map();
    // qd_actual_size字段不修改
    const PRESERVE_PROPS = ["qd_actual_size"];

    if (isPz === 0) {
      // 刷新清单
      visibleData.forEach(mx => copyMap.set(`${mx.itemname}|${mx.bj_pzname}|${mx.bj_pzname_mx}`, mx));

      state.mattressQDList = res.mxList.map(mx => {
        const key = `${mx.itemname}|${mx.bj_pzname}|${mx.bj_pzname_mx}`;
        if (copyMap.has(key)) {
          matchQty++;
          PRESERVE_PROPS.forEach(prop => {
            mx[prop] = copyMap.get(key)[prop];
          });
        }
        return mx;
      });
    } else if (isPz === 1) {
      // 复制清单
      const NEED_PROPS = [
        "erp_mtrlid",
        "erp_mtrlcode",
        "erp_mtrlname",
        "erp_mtrlmode",
        "erp_mtrlengname",
        "erp_unit",
        "useqty",
        "actual_useqty",
        "wrkgrpid",
        "qd_pfgroupqty",
        "dscrp"
      ];
      res.mxList.forEach(mx => copyMap.set(`${mx.itemname}|${mx.bj_pzname}|${mx.bj_pzname_mx}`, mx));

      state.mattressQDList = visibleData.map(mx => {
        const key = `${mx.itemname}|${mx.bj_pzname}|${mx.bj_pzname_mx}`;
        if (copyMap.has(key)) {
          matchQty++;
          NEED_PROPS.forEach(prop => {
            mx[prop] = copyMap.get(key)[prop];
          });
        }
        return mx;
      });

      // state.mattressQDList = visibleData.map((mx: any) => mx);
    } else {
      // 重新刷新清单
      visibleData.forEach(mx => copyMap.set(`${mx.itemname}|${mx.bj_pzname}|${mx.bj_pzname_mx}`, mx));

      state.mattressQDList = res.mxList.map(mx => {
        const key = `${mx.itemname}|${mx.bj_pzname}|${mx.bj_pzname_mx}`;
        if (copyMap.has(key)) {
          matchQty++;
          PRESERVE_PROPS.forEach(prop => {
            mx[prop] = copyMap.get(key)[prop];
          });
        }
        return mx;
      });
    }

    if (res.mxList.length > 0) {
      await $table.reloadData(state.mattressQDList);
      resetMergeCellsQd();

      ElNotification({
        title: "刷新成功",
        message: `成功匹配${matchQty}条数据`,
        type: "success"
      });
    } else {
      ElNotification({
        title: "刷新失败",
        message: "暂无清单数据(mattressid: " + mattressid + ")",
        type: "warning"
      });
    }
  };

  /**
   * @description 弹窗模块：床垫选择
   * @param data 当前数据
   * @param status 当前订单状态
   * @returns Promise
   */
  const fModelChoseMattress = (label?: string, params?: any, multipleLimit: number = 1) => {
    return new Promise((resolve, reject) => {
      let _params = {
        arg_deptid: state.mainData[0].deptid,
        ...params
      };
      state.MattressDialogProps = {
        multipleLimit: multipleLimit,
        onSubmit: (res: any) => {
          // submit
          console.log("openCustDialog res", res);
          nextTick(() => {
            resolve(res.value[0]);
          });
        },
        onCancel: (error: any) => {
          // cancel 回调
          console.log("openCustDialog error", error);
        }
      };
      state.MattressDialogRef.show(_params, label);
    });
  };

  const toExcel = (fileName: string) => {
    // const { data, mxdata } = params;
    const data = state.mattressQDList;
    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 workST = workbook.addWorksheet("沙头工厂清单"); // 创建工作表（sheet1）
    // 冻结前7行
    workST.views = [{ state: "frozen", xSplit: 0, ySplit: 1 }];

    // let _columns = columns_qd.map((itm: any) => {
    //   return {
    //     name: itm.label
    //   };
    // });
    // _columns.unshift({
    //   name: ""
    // });
    // _columns.unshift({
    //   name: "层"
    // });

    // let _rows = [];
    // // 第一层
    // let firstRow = [];
    // firstRow.push(0);
    // firstRow.push("--------------------");
    // _columns.map((col: any) => {
    //   firstRow.push(col.);
    // });
    // _rows.push(firstRow);

    // 第二层
    // state.mattressQDList.map((itm: any) => {
    //   let _row = [];
    //   _row.push(1);
    //   _row.push("├--------------------");

    //   _columns.map((col: any) => {
    //     _row.push(itm[col.field]);
    //   });
    //   _rows.push(_row);
    // });
    // console.log('toExcel _rows :>> ', _rows);

    // workST.addTable({
    //   name: "workSTTable",
    //   ref: "A1",
    //   headerRow: true,
    //   totalsRow: true,
    //   // style: {
    //   //   theme: 'TableStyleDark3',
    //   //   showRowStripes: true,
    //   // },
    //   columns: _columns,
    //   rows: _rows
    // });

    const worksLJ = workbook.addWorksheet("龙江总部清单"); // 创建工作表（sheet1）

    // // // 设置整个工作表的背景颜色为白色
    // // 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;
    //   }
    // });

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

  const YWAudit = (type: any, curRecords: any, cb?: any) => {
    if (!curRecords.length) {
      ElMessage.warning(t("business.tips.mattress.records"));
      return;
    }

    let list = curRecords.map((item: any) => {
      return {
        mattressid: Number(item.mattressid)
      };
    });
    ElMessageBox.confirm(`是否确定要${type ? "审核" : "撤审"}${curRecords.length}张床垫报价单吗?`, "询问", {
      confirmButtonText: t("common.okText"),
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        MattressYWAudit({ list, type }).then(() => {
          ElMessage.success(`业务${type ? "审核" : "撤审"}成功！`);

          cb && cb();
          // vxeTableRef.value.refresh();
        });
      })
      .catch((e: TypeError) => {
        console.log("e :>> ", e);
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };

  const JSAudit = (type: any, curRecords: any, cb?: any) => {
    if (!curRecords.length) {
      ElMessage.warning(t("business.tips.mattress.records"));
      return;
    }

    let list = curRecords.map((item: any) => {
      return {
        mattressid: Number(item.mattressid)
      };
    });
    ElMessageBox.confirm(`是否确定要${type ? "审核" : "撤审"}${curRecords.length}张床垫报价单吗?`, "询问", {
      confirmButtonText: t("common.okText"),
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        MattressJSAudit({ list, type }).then(() => {
          ElMessage.success(`产品补充${type ? "审核" : "撤审"}成功！`);

          cb && cb();
          // vxeTableRef.value.refresh();
        });
      })
      .catch((e: TypeError) => {
        console.log("e :>> ", e);
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };

  const JS2Audit = (type: any, curRecords: any, cb?: any) => {
    if (!curRecords.length) {
      ElMessage.warning(t("business.tips.mattress.records"));
      return;
    }

    let list = curRecords.map((item: any) => {
      return {
        mattressid: Number(item.mattressid)
      };
    });
    ElMessageBox.confirm(`是否确定要${type ? "审核" : "撤审"}${curRecords.length}张床垫报价单吗?`, "询问", {
      confirmButtonText: t("common.okText"),
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        MattressJS2Audit({ list, type }).then(() => {
          ElMessage.success(`清单补充${type ? "审核" : "撤审"}成功！`);

          cb && cb();
          // vxeTableRef.value.refresh();
        });
      })
      .catch((e: TypeError) => {
        console.log("e :>> ", e);
        ElMessage({
          type: "info",
          message: "操作取消"
        });
      });
  };

  /**
   * @description 弹窗模块：物料选择
   * @param data 当前数据
   * @param status 当前订单状态
   * @returns Promise
   */
  const fModelChoseCodeMx = (data: any, params: any, cb: any, label?: string, $table?: any) => {
    return new Promise((resolve, reject) => {
      // if (!ALLOW_EDIT_STATE.includes(status)) return;

      let _params = {
        keyword: "",
        pzid: params.pzid
      };
      state.CodeMxDialogProps = {
        onSubmit: (res: any) => {
          // submit
          console.log("openCustDialog res", res);
          nextTick(() => {
            cb(data, res.value[0], $table);
            resolve(1);
          });
        },
        onCancel: (error: any) => {
          // cancel 回调
          console.log("openCustDialog error", error);
        }
      };
      state.CodeMxDialogRef.show(_params, label);
    });
  };

  const dynamicRef = name => {
    return state[name]; // 获取ref的值
  };

  const wf_fine_erp_pz = () => {};

  return {
    ...toRefs(state),
    columns,
    columns_detail,
    columns_yw,
    columns_yw_qd,
    columns_qd,
    tableProps_mx,
    tableProps_qd,
    RetriveMattressInterface,
    RefreshMattressInterfaceList,
    RefreshMattressInterfaceQdList,
    fModelChoseMattress,
    toExcel,
    toCreateMtrl,
    toCreateORDelMtrlPf,
    // toUpdateL1Planprice,
    YWAudit,
    JSAudit,
    JS2Audit,
    resetMergeCellsQd,
    resetMergeCells,
    funcAddRowQd,
    funcCmpCC,
    dynamicRef
  };
};
