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 { GetBedNetInterfaceList, RefreshBedNetInterface, RefreshBedNetInterfaceQd } 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 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";

interface defaultState {
  initParams: any;
  /**
   * @description 单据当前状态
   */
  orderStatus: string;
  /**
   * @description 列表Ref
   */
  VxeTableRef: any;
  /**
   * @description 详情页Ref
   */
  LjDetailRef: any;
  mainData: any;
  bednetYWList: any[];
  bednetQDList: 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;
}

/**
 * @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: [],
    bednetYWList: [],
    bednetQDList: [],
    editType: 0,
    MattressDialogRef: null,
    MattressDialogProps: {},
    MtrldefErpDialogRef: null,
    MtrldefErpDialogProps: {},
    workgrpEnum: [],
    workgrpEnum2: [],
    configureTypeEnum: []
  });

  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 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(() => {
          CreatPrdPf({ list }).then(() => {
            ElNotification({
              title: "金蝶清单",
              message: "生成成功！",
              type: "success"
            });
          });
        })
        .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(() => {
        CreatMtrlPf({ list }).then(res => {
          console.log("toCreateMtrl, res :>> ", res);
          if (state.LjDetailRef) {
            state.LjDetailRef._mainData.erp_mtrlid = res.bednet.erp_mtrlid;
            state.LjDetailRef._mainData.creatmtrl_flag = res.bednet.creatmtrl_flag;
            state.LjDetailRef._mainData.erp_mtrlcode = res.bednet.erp_mtrlcode;
          }
          ElNotification({
            title: "物料",
            message: "生成/更新成功！",
            type: "success"
          });
        });
      })
      .catch((e: TypeError) => {
        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 4: //待清单补充审
        state.initParams.js2_flag = 0;
        state.initParams.creatmtrl_flag = -1;
        state.initParams.creatmtrlqd_flag = -1;
        break;
      case 5: //待生成erp产品
        state.initParams.js2_flag = 1;
        state.initParams.creatmtrl_flag = 1;
        state.initParams.creatmtrlqd_flag = -1;
        break;
      case 6: //待生成erp清单
        state.initParams.js2_flag = 1;
        state.initParams.creatmtrl_flag = 1;
        state.initParams.creatmtrlqd_flag = 0;
        break;
      default:
        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) => {
    console.log("rModelSetMtrlErp item :>> ", item);
    if (item) {
      data.erp_mtrlid = item.mtrlid;
      data.erp_mtrlname = item.mtrlname;
      data.erp_mtrlmode = item.mtrlmode;
      data.erp_mtrlcode = item.mtrlcode;
      data.erp_unit = item.unit;
      data.erp_mtrlengname = item.mtrlengname;
    }
  };

  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: "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: "bednetcode",
      title: "报价唯一码"
    },
    {
      field: "bednetname",
      title: "核价名称",
      treeNode: true,
      render: scope => {
        return !scope.row?.child_count && !scope.row?.parentid ? (
          scope.row?.bednetname
        ) : scope.row?.parentid ? (
          <div class="flx-justify-between">
            <span class="mle">{scope.row?.bednetname}</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?.bednetname}</span>
            <el-tag type="primary" effect="light" disable-transitions size="small" round class="ml-4">
              主
            </el-tag>
          </div>
        );
      }
    },
    {
      field: "bednettypeid",
      title: "床网类别"
    },
    {
      field: "mattress_width",
      title: "床网宽/CM"
    },
    {
      field: "mattress_length",
      title: "床网长/CM"
    },
    {
      field: "mattress_height",
      title: "床网高/CM"
    },
    {
      field: "createby",
      title: "登记人"
    },
    {
      field: "createtime",
      title: "登记时间"
    },
    {
      field: "js2_auditingrep",
      title: "清单补充审核人"
    },
    {
      field: "js2_auditingdate",
      title: "清单补充审核时间"
    },
    {
      field: "creatmtrl_auditingrep",
      title: "生成L1产品人"
    },
    {
      field: "creatmtrl_auditingdate",
      title: "生成L1产品时间"
    },
    {
      field: "creatmtrlqd_auditingrep",
      title: "生成L1清单人"
    },
    {
      field: "creatmtrlqd_auditingdate",
      title: "生成L1清单时间"
    },
    {
      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",
        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
        }
      },
      enum: async () => {
        const data = await GetERPMtrlTypeList();
        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: "bednetcode",
      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="请选择配置"
              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"
      }
    }
  ];

  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: "项目"
    }
  ];

  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: "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: "erp_mtrlcode",
      title: "L1物料编码",
      editRender: {
        // name: "$select"
        autoFocus: "input"
      },
      editColRender: (scope: any) => {
        const { $table, column, row, status } = scope;
        let field = column.field;
        let _label = column.title;
        let params = {
          keyword: row.erp_mtrlcode
        };

        return (
          <MtrldefErpSelect
            value={row.erp_mtrlid}
            {...params}
            clearable
            placeholder={_label}
            onOpenModal={() => fModelChoseMtrlErp(row, params)}
            onSelect={val => rModelSetMtrlErp(row, val)}
            onClear={() => rModelClearMtrlErp(row, 2)}
          >
            {{
              label: () => row.erp_mtrlcode
            }}
          </MtrldefErpSelect>
        );
      }
    },
    {
      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;
        let field = column.field;
        let _label = column.title;

        return (
          <MtrldefErpSelect
            value={row.erp_mtrlid}
            searchKey="mtrlengname"
            clearable
            placeholder={_label}
            onOpenModal={() => fModelChoseMtrlErp(row, {})}
            onSelect={val => rModelSetMtrlErp(row, val)}
            onClear={() => rModelClearMtrlErp(row, 2)}
          >
            {{
              label: () => row.erp_mtrlengname
            }}
          </MtrldefErpSelect>
        );
      }
    },
    {
      field: "erp_mtrlname",
      title: "L1物料名称",
      limited: () => {
        return state.editType == 1 || state.editType == 2;
      }
    },
    {
      field: "erp_mtrlmode",
      title: "L1物料规格",
      limited: () => {
        return state.editType == 1 || state.editType == 2;
      }
    },
    {
      field: "qd_actual_size",
      title: "实际尺寸",
      editRender: {
        name: "$input"
      }
    },
    {
      field: "erp_unit",
      title: "L1物料单位",
      limited: () => {
        return state.editType == 1 || state.editType == 2;
      }
    },
    {
      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: "领用工组",
      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 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）",
      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 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 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 = () => {
    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);
        // });
      }
    });
  };
  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 GetBedNetInterfaceList({ mattressid, isEdit: Number(state.orderStatus != "") });
    if (res.ErrMsg) {
      ElNotification({
        title: "温馨提示",
        message: res.ErrMsg,
        type: "error"
      });
    }
    state.mainData = [res.bednet];
    state.bednetYWList = res.interfaceList;
    state.bednetQDList = res.qdList;

    resetMergeCells();
    resetMergeCellsQd();
  };
  /**
   * 获取产品配置，产品清单
   * @param mattressid 床网ID
   */
  const RefreshBedNetInterfaceList = async (mattressid: number, isPz: number, configcodetype: number = 0) => {
    let res = await RefreshBedNetInterface({ mattressid, isPz, configcodetype });
    state.bednetYWList = res.mxList;

    resetMergeCells();

    ElNotification({
      title: "刷新成功",
      type: "success"
    });
  };
  /**
   * 获取产品配置，产品清单
   * @param mattressid 床网ID
   */
  const RefreshBedNetInterfaceQdList = async (mattressid: number, isPz: number, isCheck?: number) => {
    isCheck = isCheck ?? 1;

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

    const interfaceMap = {};
    state.bednetYWList.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;
        }
      }
    });

    state.bednetQDList = res.mxList;

    resetMergeCellsQd();

    ElNotification({
      title: "刷新成功",
      type: "success"
    });
  };

  /**
   * @description 弹窗模块：床网选择
   * @param data 当前数据
   * @param status 当前订单状态
   * @returns Promise
   */
  const fModelChoseMattress = (label?: string) => {
    return new Promise((resolve, reject) => {
      let _params = {
        arg_deptid: state.mainData[0].deptid
      };
      state.MattressDialogProps = {
        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.bednetQDList;
    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 }];

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

  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: "操作取消"
        });
      });
  };

  return {
    ...toRefs(state),
    columns,
    columns_detail,
    columns_yw,
    columns_yw_qd,
    columns_qd,
    tableProps_mx,
    tableProps_qd,
    RetriveMattressInterface,
    RefreshBedNetInterfaceList,
    RefreshBedNetInterfaceQdList,
    fModelChoseMattress,
    toExcel,
    toCreateMtrl,
    toCreateORDelMtrlPf,
    JS2Audit,
    resetMergeCellsQd
  };
};
