<template>
  <div class="table-box">
    <LjVxeTable
      ref="vxeTableRef"
      row-key="mattressid"
      :columns="columns"
      :init-param="initParams"
      :request-api="getData"
      :data-callback="dataCallback"
      :dwname="DwnameEnum.mattressQuote"
      :table-props="tableProps"
      :table-events="tableEvents"
      :auto-load-layout="false"
      :search-btn-size-extent="[]"
      pagination
      :page-change-call-back="autoUpdateTableCheckbox"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <LjHeaderMenu :update="dialogVisible" :action="action" />
      </template>
    </LjVxeTable>
  </div>
  <el-dialog v-model="dialogFormVisible" title="部门选择" width="500" draggable append-to-body>
    <el-form :model="formParam" label-width="80px">
      <el-form-item label="部门">
        <el-select v-model="formParam.deptid" placeholder="请选择部门" filterable @change="wf_get_moneyrate_discount">
          <el-option v-for="(col, index) in deptEnum" :key="index" :label="col.label" :value="col.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地区">
        <el-select v-model="formParam.area">
          <el-option label="维持原状" value="维持原状" />
          <el-option label="普通地区" value="普通地区" />
          <el-option label="特定地区" value="特定地区" />
        </el-select>
      </el-form-item>
      <el-form-item label="柜型">
        <el-select v-model="formParam.cabinet_type">
          <el-option label="维持原状" value="维持原状" />
          <el-option label="大柜" value="大柜" />
          <el-option label="小柜" value="小柜" />
        </el-select>
      </el-form-item>
      <el-form-item label="佣金点数">
        <el-input-number v-model="formParam.commission" />
      </el-form-item>
      <el-form-item label="税金">
        <el-select v-model="formParam.taxes" class="select-text-right">
          <template #prefix>
            <span>{{ formParam.taxes }}</span>
          </template>
          <el-option label="不含税" :value="1" />
          <el-option label="含税" :value="1.07" />
        </el-select>
      </el-form-item>
      <el-form-item label="额外点数">
        <el-input-number v-model="formParam.other_rate" />
      </el-form-item>
      <el-form-item label="额外费用">
        <el-input-number v-model="formParam.extras_cost" />
      </el-form-item>
      <el-form-item label="币种">
        <el-select v-model="formParam.moneytype" class="select-text-right" @change="wf_get_moneyrate_discount">
          <template #prefix>
            <span>{{ formParam.moneyrate }}</span>
          </template>
          <el-option label="人民币" :value="0" />
          <el-option label="美元" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="压包数量" v-if="formParam.packtype == 0">
        <el-input-number v-model="formParam.packqty" :min="0" :max="1000" />
      </el-form-item>
      <el-form-item label="复制到">
        <el-select v-model="formParam.createby" :placeholder="userInfo.username" filterable clearable>
          <el-option v-for="(col, index) in userListData" :key="index" :label="col.username" :value="col.username"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="loadingBtn" @click="BatchCopyMattressAudited">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <LjDrawerQuoteList
    ref="QuoteListDrawerRef"
    :iforigin="isShowOriginFormulaMattress"
    @closed="ifShowDrawer = false"
    @export="handleExportQuote"
  />
</template>

<script setup lang="ts" name="mattressQuote">
import { ref, onMounted, inject, reactive } from "vue";
import { useRouter } from "vue-router";
import {
  SaveMattressAuditing,
  DelMattress,
  CopyMattressAudited,
  ReCalculateNoAudit,
  ReCalculateERPCost,
  GetComputeMattressById
} from "@/api/modules/quote";
import { getUserList } from "@/api/modules/basicinfo";
import { CommonDynamicSelect } from "@/api/modules/common";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import LjDrawer from "@/components/LjDrawer/index.vue";
// import PriceListDetail from "./detail.vue";
import { useHooks } from "./hooks/index";
import { useHooksCpQuote } from "./hooks/cpQuote";
import LjDialog from "@/components/LjDialog/index.vue";
import LjHeaderMenu from "@/components/LjHeaderMenu/index.vue";
import { useI18n } from "vue-i18n";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { DwnameEnum } from "@/enums/dwnameEnum";
import { formatToDateTime, formatToDate } from "@/utils/dateUtil";
import { cloneDeep } from "lodash-es";
import { useGlobalStore } from "@/stores/modules/global";
import { ElMessage, ElMessageBox } from "element-plus";
import { detailAction } from "@/components/LjDetail/interface";
import mittBus from "@/utils/mittBus";
import { MittEnum } from "@/enums/mittEnum";
import { getCurrentRecords } from "@/utils/index";
import { useUserStore } from "@/stores/modules/user";
import LjDrawerQuoteList from "./components/QuoteListNew.vue";
import { storeToRefs } from "pinia";
import { formatTime } from "@/utils/index";
import { usePageRouter } from "@/hooks/usePageRouter";

const { t } = useI18n();
const router = useRouter();
const globalStore = useGlobalStore();
const {
  vxeTableRef,
  columns,
  initParams,
  dataCallback,
  gotoErpapi,
  getFormulakindEnum,
  formulaKindEnum,
  fabricMxTabList,
  funcChaifenTabPro,
  getQuoteListMxData,
  gotoHisprice
} = useHooks();
const { toExcelQuote, toExcelQuoteNew } = useHooksCpQuote();
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);
const { userInfo } = useUserStore();
const { pageCheckRefresh, pageCheckOpen } = usePageRouter();

// const initParams = ref({});
const dialogVisible = ref(false);
// const vxeTableRef = ref();
const dialogFormVisible = ref(false);
const loadingBtn = ref(false);
const deptEnum = ref([]);
const userListData = ref([]);
const QuoteListDrawerRef = ref(null);
const ifShowDrawer = ref(false);
const ifShowHisprice = ref(false);

const { isShowOriginFormulaMattress } = storeToRefs(globalStore);
const loadingStatus = reactive({
  showQd: false,
  download: false
});

const formParam = ref({
  deptid: 0,
  area: "维持原状",
  cabinet_type: "维持原状",
  packtype: 0,
  packqty: 0,
  createby: "",
  commission: 0,
  taxes: 1,
  other_rate: 0,
  extras_cost: 0,
  moneytype: 0,
  moneyrate: 1,
  discount: 0
});

const getData = (params: any) => {
  console.log("getData mattress params :>> ", params);
  let newParams: any = {};
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);
  params.orderstr && (newParams.orderstr = params.orderstr);
  delete params.arg_mattressid;
  delete params.pageNum;
  delete params.pageSize;
  delete params.orderstr;
  let _params = cloneDeep(params);
  switch (_params.status_flag) {
    case "1": // 待下单
      _params.arg_xd_flag = 0;
      break;
    case "2": // 已下单
      _params.arg_xd_flag = 1;
      break;
    case "3": // 待财务审核
      _params.arg_cp_flag = 1;
      _params.arg_flag = 0;
      break;
    case "4": // 已财务审核
      _params.arg_flag = 1;
      break;
    default:
      break;
  }
  newParams.queryParams = _params;
  newParams.dsname = "web_mattress";

  return CommonDynamicSelect(newParams, DwnameEnum.mattressQuote);
  // return [];
};

const handleDBlClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  if (globalStore.detailBlank) {
    // 打开新的窗口
    const routeUrl = router.resolve({
      path: `/mattressQuote/detail`,
      query: {
        id: row.mattressid,
        code: row.mattresscode
      }
    });
    window.open(routeUrl.href, "_blank");
  } else {
    // if (currentLayout.value.right.hidden && globalStore.mxFloat?.includes("custCrmDetail")) {
    //   // 弹窗
    //   mainData.value = row;
    //   LjDrawerRef.value.show();
    // } else {
    // 打开新的标签页
    router.push(`/mattressQuote/detail?id=${row.mattressid}&code=${row.mattresscode}`);
    // }
  }
};

const handleClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  if (ifShowDrawer.value) {
    funcShowQuoteList(row);
  }
  if (ifShowHisprice.value) {
    gotoHisprice(row.mattresscode, 0, { id: row.mattressid, typeid: 1 }, () => {
      ifShowHisprice.value = false;
    });
  }
};

/**
 * @description 记录当前行数据
 */
const currentRecord = reactive<any>({});

const funcShowQuoteList = (curRecord: any) => {
  loadingStatus.showQd = !loadingStatus.showQd;
  GetComputeMattressById({
    mattressid: curRecord.mattressid,
    check_original: Number(isShowOriginFormulaMattress.value)
  })
    .then(res => {
      const isQuoteListMxData = getQuoteListMxData(funcChaifenTabPro(res.mattress, res.mattressMx));
      currentRecord.data = res.mattress;
      currentRecord.mxdata = isQuoteListMxData;
      currentRecord.enumMap = vxeTableRef.value.enumMap;
      currentRecord.fabricMx = fabricMxTabList.value;
      currentRecord.formulakindenum = formulaKindEnum.value;
      currentRecord.dannum_type = res.mattress.dannum_type;
      currentRecord.formula = res.formulas;
      currentRecord.replace = res.replace;
      currentRecord.formula_ori = res.formulas_origin;
      currentRecord.formula_bednet = res.formulas_bednet;
      currentRecord.differ = res.differ;

      QuoteListDrawerRef.value.show(currentRecord);
      ifShowDrawer.value = true;

      loadingStatus.showQd = !loadingStatus.showQd;
    })
    .catch(err => {
      loadingStatus.showQd = !loadingStatus.showQd;
    });
};

const handleExportQuote = async (ifExpandAll: any, ifShowOrigin: any, fields: any) => {
  console.log("handleExportQuote ifExpandAll :>> ", ifExpandAll, ifShowOrigin);
  if (ifShowOrigin) {
    loadingStatus.download = true;
    await toExcelQuote(currentRecord, "床垫报价单_" + currentRecord.data.mattresscode);
    loadingStatus.download = false;
  } else {
    loadingStatus.download = true;

    currentRecord.fields = fields;
    await toExcelQuoteNew(currentRecord, "床垫报价单_" + currentRecord.data.mattresscode, ifExpandAll);
    loadingStatus.download = false;
  }
};

const rowClsNameFunc = (data: any) => {
  const { row, rowIndex, $rowIndex } = data;
  if (Number(row.flag) == 0) {
    if (Number(row.xd_flag) == 0) {
      return "vxecol-danger";
    }
    if (Number(row.xd_flag) == 1) {
      return "vxecol-blue";
    }
  }
  return "";
};
const tableProps = {
  height: "auto",
  editConfig: { trigger: "click", mode: "cell" },
  rowClassName: rowClsNameFunc,
  exportConfig: {
    filename: t("menu.rpMsttake") + formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss")
  },
  treeConfig: {
    expandAll: true,
    transform: true,
    rowField: "mattressid",
    parentField: "parentid"
  },
  checkboxConfig: {
    showHeader: true,
    checkStrictly: true
  }
};

// 返回绑定的事件
const tableEvents = {
  // "checkbox-change": handleCheckboxChange,
  // "checkbox-all": handleCheckboxChange,
  // "checkbox-range-change": handleCheckboxChange,
  // "current-change": handleCurrentChanged
  "cell-dblclick": handleDBlClickTable,
  "cell-click": handleClickTable
};

onMounted(() => {
  dialogVisible.value = true;

  getFormulakindEnum();
});

/**
 * @description 业务下单或财务审核操作
 * @param params 对象，入参
 */
const toAuditing = (params: any, message: string) => {
  const { curRecords } = getCurrentRecords(vxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  curRecords.map(o => {
    if (params.hasOwnProperty("xd_flag")) {
      if (o.js1_flag == 1) {
        ElMessage.warning("已产品补充审核，无法修改");
        return;
      }
    }
  });

  let _mattressids = curRecords.map((item: any) => Number(item.mattressid));

  ElMessageBox.confirm(`是否确定要对${curRecords.length}张床垫报价单进行操作`, "询问", {
    confirmButtonText: message,
    cancelButtonText: "否",
    type: "warning"
  })
    .then(() => {
      let _params = {
        ...params,
        mattressids: _mattressids
      };
      SaveMattressAuditing(_params).then(() => {
        ElMessage.success(t("sys.api.operationSuccess"));

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

/**
 * @description 按钮展示
 */
const action: detailAction[] = [
  buttonDefault({
    label: t("common.redo"),
    clickFunc: item => {
      vxeTableRef.value.refresh();
    }
  }),
  buttonDefault({
    label: t("common.add"),
    power: 72,
    clickFunc: item => {
      console.log("inewss   nitParams.value :>> ", vxeTableRef.value.searchParam);
      let _deptid = 0;
      if (Object.keys(vxeTableRef.value.searchParam).includes("arg_deptid")) {
        _deptid = vxeTableRef.value.searchParam.arg_deptid ?? 0;
      }
      if (_deptid == 0) {
        let enumMap = vxeTableRef.value.enumMap;
        let enumdata = enumMap.get("deptid");
        if (enumdata && enumdata.length > 0) {
          _deptid = enumdata[0].value;
        }
      }
      router.push(`/mattressQuote/new?id=0&deptid=${_deptid}`);
    }
  }),
  buttonDefault({
    label: t("common.editText"),
    power: 72,
    clickFunc: item => {
      const { $table, curRecords } = getCurrentRecords(vxeTableRef.value);

      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }
      const _cur = curRecords[curRecords.length - 1];
      console.log("修改 _cur :>> ", _cur);
      if (_cur.parentid > 0) {
        ElMessage.warning("副规格无法编辑");
        return;
      }
      if (_cur.xd_flag == 1) {
        ElMessage.warning("已业务下单，不能修改");
        return;
      }
      if (_cur.flag == 1) {
        ElMessage.warning("单据已财核，不能修改");
        return;
      }

      pageCheckOpen(
        `/mattressQuote/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}`,
        "MattressQuote",
        _cur.mattressid,
        _cur.mattresscode
      );
      // router.push(`/mattressQuote/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}`);
    }
  }),
  buttonDefault({
    label: t("common.delText"),
    power: 77,
    disabledTextCallBack: (data: any) => {
      if (!CheckPower(77)) {
        return "你没有【报价单-删除】的使用权限";
      }

      return "";
    },
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);

      console.log("curRecords :>> ", curRecords);
      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      try {
        curRecords.map(item => {
          if (item.createby !== userInfo.username && userInfo.empid != 0) {
            throw new Error("只能删除自己创建的报价单");
          }
          if (item.xd_flag == 1) {
            throw new Error("已业务下单，不能删除");
          }
          if (item.flag == 1) {
            throw new Error("单据已财核，不能删除");
          }
        });
      } catch (error) {
        ElMessage.error(error.message);
        return false;
      }

      let _mattressids = curRecords.map((item: any) => Number(item.mattressid));

      ElMessageBox.confirm(`是否确定要删除${curRecords.length}张床垫报价单（及其副规格报价单）吗?`, "询问", {
        confirmButtonText: t("common.delText"),
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          DelMattress({ mattressids: _mattressids }).then(() => {
            ElMessage.success("删除成功！");

            vxeTableRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          console.log("e :>> ", e);
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  buttonDefault({
    label: t("common.copyQuote"),
    power: 75,
    clickFunc: item => {
      const { $table, curRecords } = getCurrentRecords(vxeTableRef.value);

      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      let _cur = $table.getCurrentRecord() ?? null;
      if (!_cur) {
        _cur = curRecords[curRecords.length - 1];
      }
      router.push(`/mattressQuote/copy?id=${_cur.mattressid}&code=${_cur.mattresscode}`);
    }
  }),
  // [
  buttonDefault({
    label: t("common.businessOrder"),
    power: 94,
    clickFunc: item => {
      toAuditing({ xd_flag: 1 }, t("common.businessOrder"));
    }
  }),
  buttonDefault({
    label: t("common.businessOrderCancel"),
    power: 95,
    clickFunc: item => {
      toAuditing({ xd_flag: 0 }, t("common.businessOrderCancel"));
    }
  }),
  // ],
  // [
  buttonDefault({
    label: t("common.auditFinance"),
    power: 73,
    clickFunc: item => {
      toAuditing({ flag: 1 }, t("common.auditFinance"));
    }
  }),
  buttonDefault({
    label: t("common.withdrawAuditFinance"),
    power: 74,
    clickFunc: item => {
      toAuditing({ flag: 0 }, t("common.withdrawAuditFinance"));
    }
  }),
  // ],
  buttonDefault({
    label: t("common.copyFromMulitFlag"),
    power: 75,
    clickFunc: async item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);

      console.log("curRecords :>> ", curRecords);
      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      await openDeptChoosen(curRecords);
    }
  }),
  // buttonDefault({
  //   label: t("common.recalculateFromNotFlag"),
  //   power: 72,
  //   clickFunc: item => {
  //     const { curRecords } = getCurrentRecords(vxeTableRef.value);

  //     console.log("curRecords :>> ", curRecords);
  //     if (!curRecords.length) {
  //       ElMessage.warning(t("business.tips.mattress.records"));
  //       return;
  //     }

  //     let list = curRecords.map((item: any) => {
  //       return { mattressid: Number(item.mattressid) };
  //     });

  //     ElMessageBox.confirm(`是否确定要批重算${curRecords.length}张床垫报价单吗?`, "询问", {
  //       confirmButtonText: t("common.okText"),
  //       cancelButtonText: "否",
  //       type: "warning"
  //     })
  //       .then(() => {
  //         ReCalculateNoAudit({ list }).then(() => {
  //           ElMessage.success("批重算成功！");

  //           vxeTableRef.value.refresh();
  //         });
  //       })
  //       .catch((e: TypeError) => {
  //         console.log("e :>> ", e);
  //         ElMessage({
  //           type: "info",
  //           message: "操作取消"
  //         });
  //       });
  //   }
  // }),
  buttonDefault({
    label: t("common.viewHistoricalQuotes"),
    power: 72,
    clickFunc: item => {
      const curRecord = vxeTableRef.value.element.getCurrentRecord() ?? null;

      // console.log("curRecords :>> ", curRecords);
      if (!curRecord) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
        // } else if (curRecords.length > 1) {
        //   ElMessage.warning(`无法进行多单${t("common.showQuoteList")}`);
        //   return;
      }
      ifShowHisprice.value = true;

      gotoHisprice(curRecord.mattresscode, 0, { id: curRecord.mattressid, typeid: 1 }, () => {
        ifShowHisprice.value = false;
      });
    }
  }),
  buttonDefault({
    label: t("common.showQuoteList"),
    loading: () => loadingStatus.showQd,
    power: 72,
    clickFunc: async item => {
      // const { curRecords } = getCurrentRecords(vxeTableRef.value);

      const curRecord = vxeTableRef.value.element.getCurrentRecord() ?? null;

      // console.log("curRecords :>> ", curRecords);
      if (!curRecord) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
        // } else if (curRecords.length > 1) {
        //   ElMessage.warning(`无法进行多单${t("common.showQuoteList")}`);
        //   return;
      }

      funcShowQuoteList(curRecord);
    }
  }),
  buttonDefault({
    label: t("common.dataTransmission"),
    power: 72,
    clickFunc: item => {
      // alert("功能维护中!");
      const { $table } = getCurrentRecords(vxeTableRef.value);
      const now = new Date();
      $table?.openExport({ filename: `床垫报价_${formatTime(now, "{y}-{m}-{d}", false)}` });
    }
  }),
  buttonDefault({
    label: t("common.businessSupplement"),
    power: 72,
    clickFunc: item => {
      const { $table, curRecords } = getCurrentRecords(vxeTableRef.value);

      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }
      let _cur = $table.getCurrentRecord() ?? curRecords[curRecords.length - 1];
      let type = 1;
      // router.push(`/erpapi/mattressInterface/${type}/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}&type=${type}`);

      gotoErpapi(_cur, type);
    }
  }),
  buttonDefault({
    label: t("common.recalculateERPCost"),
    power: 72,
    clickFunc: async item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);

      console.log("curRecords :>> ", curRecords);
      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }

      let list = curRecords.map((item: any) => {
        return { mattressid: Number(item.mattressid) };
      });

      ElMessageBox.confirm(`是否确定要批重算${curRecords.length}张床垫报价单吗?`, "询问", {
        confirmButtonText: t("common.okText"),
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          ReCalculateERPCost({ list }).then((res: any) => {
            ElMessage.success(res.logMsg);
            vxeTableRef.value.refresh();
          });
        })
        .catch((e: TypeError) => {
          ElMessage({
            type: "info",
            message: "操作取消"
          });
        });
    }
  }),
  buttonDefault({
    label: t("common.viewBusinessSupplement"),
    power: 72,
    clickFunc: item => {
      const { $table, curRecords } = getCurrentRecords(vxeTableRef.value);

      if (!curRecords.length) {
        ElMessage.warning(t("business.tips.mattress.records"));
        return;
      }
      let _cur = $table.getCurrentRecord() ?? curRecords[curRecords.length - 1];

      router.push({
        name: "mattressInterfaceDetail",
        params: {
          id: _cur.mattressid
        },
        query: {
          code: _cur.mattresscode
        },
        replace: true
      });
    }
  })
];

const openDeptChoosen = async curRecords => {
  try {
    // let newParams = {
    //   dsname: "_Mapper_deptid",
    //   queryparams: {}
    // };
    // let res = await CommonDynamicSelect(newParams);
    // if (res.datatable) {
    //   deptEnum.value = res.datatable?.map((item: any) => {
    //     return { label: item.deptname, value: item.deptid };
    //   });
    // }

    let res = await getUserList({ simple: 1 });
    console.log("pricelist res :>> ", res);
    userListData.value = res.userList;

    let enumMap = vxeTableRef.value.enumMap;
    deptEnum.value = enumMap.get("deptid");
    console.log("openDeptChoosen deptEnum.value :>> ", deptEnum.value);
    console.log("openDeptChoosen curRecords.value :>> ", curRecords);

    if (deptEnum.value.length > 0) {
      formParam.value.deptid = curRecords[0].deptid;
      formParam.value.packtype = curRecords[0].packtype;
      formParam.value.packqty = curRecords[0].packqty;
      formParam.value.commission = curRecords[0].commission;
      formParam.value.other_rate = curRecords[0].other_rate;
      formParam.value.extras_cost = curRecords[0].extras_cost;
      formParam.value.moneytype = curRecords[0].moneyrate > 1 ? 1 : 0;

      dialogFormVisible.value = true;
    } else {
      console.error("获取部门列表为空");
    }
  } catch (error) {
    console.error("获取部门列表失败", error);
  }
};

const BatchCopyMattressAudited = () => {
  const { curRecords } = getCurrentRecords(vxeTableRef.value);

  console.log("curRecords :>> ", curRecords);
  if (!curRecords.length) {
    ElMessage.warning(t("business.tips.mattress.records"));
    return;
  }

  loadingBtn.value = true;

  let list = curRecords.map((item: any) => {
    const result = {
      mattressid: Number(item.mattressid),
      deptid: formParam.value.deptid,
      area: formParam.value.area,
      cabinet_type: formParam.value.cabinet_type,
      packtype: formParam.value.packtype,
      packqty: formParam.value.packqty,
      createby: formParam.value.createby,
      commission: formParam.value.commission,
      taxes: formParam.value.taxes,
      other_rate: formParam.value.other_rate,
      extras_cost: formParam.value.extras_cost,
      moneyrate: formParam.value.moneyrate,
      discount: formParam.value.discount
    };
    return result;
  });
  ElMessageBox.confirm(`是否确定要批复制${curRecords.length}张床垫报价单吗?`, "询问", {
    confirmButtonText: t("common.okText"),
    cancelButtonText: "否",
    type: "warning"
  })
    .then(() => {
      CopyMattressAudited({ list }).then(() => {
        ElMessage.success("复制成功！");
        dialogFormVisible.value = false;
        vxeTableRef.value.refresh();
        loadingBtn.value = false;
      });
    })
    .catch((e: TypeError) => {
      console.log("e :>> ", e);
      ElMessage({
        type: "info",
        message: "操作取消"
      });
      loadingBtn.value = false;
    });
};

/**
 * @description 监听框架属性变化
 */
mittBus.on(MittEnum.MattressList, () => {
  vxeTableRef.value.refresh();
});

const autoUpdateTableCheckbox = () => {
  const $table = vxeTableRef.value.element;
  if ($table) {
    $table.setAllTreeExpand(true);
  }
};

const wf_get_moneyrate_discount = val => {
  let depItem = deptEnum.value.find((item: any) => item.value == formParam.value.deptid);
  if (depItem) {
    let _moneyrate = !depItem.moneyrate || Number(depItem.moneyrate) == 0 ? 1 : depItem.moneyrate;
    if (formParam.value.moneytype == 0) {
      formParam.value.moneyrate = 1;
    } else {
      formParam.value.moneyrate = _moneyrate;
    }
    formParam.value.discount = depItem.discount;
  }
};
</script>

<style lang="scss">
.select-text-right {
  .el-select__wrapper {
    text-align: right;
  }
}
</style>
