<template>
  <div class="table-box">
    <LjVxeTable
      ref="vxeTableRef"
      row-key="bednetid"
      :columns="columns"
      :init-param="initParams"
      :request-api="getData"
      :data-callback="dataCallback"
      :dwname="DwnameEnum.bednetInterface"
      :table-props="tableProps"
      :table-events="tableEvents"
      :auto-load-layout="false"
      :search-btn-size-extent="[]"
      pagination
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <LjHeaderMenu :update="dialogVisible" :action="action" />
      </template>
    </LjVxeTable>
  </div>
</template>

<script setup lang="ts" name="bednetInterface">
import { ref, onMounted, inject } from "vue";
import { useRouter } from "vue-router";
import { MattressYWAudit, MattressJSAudit, MattressJS2Audit } from "@/api/modules/quote";
import { CommonDynamicSelect } from "@/api/modules/common";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import LjDrawer from "@/components/LjDrawer/index.vue";
import { useHooks } from "./hooks/index";
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";

const { t } = useI18n();
const router = useRouter();
const globalStore = useGlobalStore();
const { initParams, columns, toCreateMtrl, toCreateORDelMtrlPf, JS2Audit } = useHooks(t);
// const { toExcelQuote } = useHooksCpQuote();
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const dialogVisible = ref(false);
const vxeTableRef = ref();
const enumMap = ref(new Map());

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.pageNum;
  delete params.pageSize;
  delete params.orderstr;
  let _params = cloneDeep(params);
  newParams.queryParams = _params;
  newParams.dsname = "web_bednet_interfacelist";

  return CommonDynamicSelect(newParams, DwnameEnum.bednetInterface);
};

const handleDBlClickTable = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
  if (globalStore.detailBlank) {
    // 打开新的窗口
    const routeUrl = router.resolve({
      path: `/erpapi/bednetInterface/detail`,
      query: {
        id: row.bednetid,
        code: row.bednetcode
      }
    });
    window.open(routeUrl.href, "_blank");
  } else {
    // 打开新的标签页
    // router.push(`/erpapi/bednetInterface/detail?id=${row.bednetid}&code=${row.bednetcode}`);

    router.push({
      path: `/erpapi/bednetInterface/detail/${row.bednetid}`,
      query: {
        code: row.bednetcode
      }
    });
  }
};

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

// 返回绑定的事件
const tableEvents = {
  "cell-dblclick": handleDBlClickTable
};

/**
 * @description 按钮展示
 */
const action: detailAction[] = [
  buttonDefault({
    label: t("common.redo"),
    clickFunc: item => {
      vxeTableRef.value.refresh();
    }
  }),
  buttonDefault({
    label: t("common.view"),
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);
      handleDBlClickTable({ row: curRecords[0] });
    }
  }),
  [
    buttonDefault({
      label: "清单补充",
      power: 85,
      clickFunc: item => {
        routeToEdit(3);
      }
    }),
    buttonDefault({
      label: "清单补充审核",
      power: 86,
      clickFunc: item => {
        const { curRecords } = getCurrentRecords(vxeTableRef.value);

        JS2Audit(1, curRecords, () => {
          vxeTableRef.value.refresh();
        });
      }
    }),
    buttonDefault({
      label: "清单补充撤审",
      power: 87,
      clickFunc: item => {
        const { curRecords } = getCurrentRecords(vxeTableRef.value);

        JS2Audit(0, curRecords, () => {
          vxeTableRef.value.refresh();
        });
      }
    })
  ],
  [
    buttonDefault({
      label: "生成/更新物料",
      power: 88,
      clickFunc: item => {
        const { curRecords } = getCurrentRecords(vxeTableRef.value);

        if (!curRecords.length) {
          ElMessage.warning(t("business.tips.mattress.records"));
          return;
        }
        let list = curRecords.map(item => item.bednetid);
        toCreateMtrl(1, list);
      }
    })
  ],
  [
    buttonDefault({
      label: "生成金蝶清单",
      power: 90,
      clickFunc: item => {
        const { curRecords } = getCurrentRecords(vxeTableRef.value);

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

        let list = curRecords.map(item => item.bednetid);
        toCreateORDelMtrlPf(1, list);
      }
    })
    // buttonDefault({
    //   label: "删除金蝶清单",
    //   power: 91,
    //   clickFunc: item => {
    //     const { curRecords } = getCurrentRecords(vxeTableRef.value);

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

    //     toCreateORDelMtrlPf(0, curRecords[curRecords.length - 1].bednetid);
    //   }
    // })
  ]
];

const dataCallback = (data: any) => {
  if (data.tableinfo?.columns) {
    data.tableinfo?.columns.map((item: any) => {
      if (item?.enum) {
        enumMap.value.set(item.field, item.enum);
      }
    });
  }
  return {
    list: data.datatable,
    tableinfo: data.tableinfo,
    total: data.totalcnt,
    pageNum: data.pageindex,
    pageSize: data.pagesize
  };
};

const routeToEdit = type => {
  const { $table, curRecords } = getCurrentRecords(vxeTableRef.value);

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

  const _cur = curRecords[curRecords.length - 1];
  // router.push(`/erpapi/bednetInterface/${type}/edit?id=${_cur.bednetid}&code=${_cur.bednetcode}&type=${type}`);

  try {
    if (type === 3) {
      if (_cur.js2_flag == 1) {
        throw new Error(_cur.bednetcode + "：已清单补充审核，无法修改");
      }
    }
  } catch (error) {
    ElMessage.error(error.message);
    return false;
  }

  router.push({
    path: `/erpapi/bednetInterface/edit/${_cur.bednetid}`,
    query: {
      code: _cur.bednetcode,
      type: type
    }
  });
};

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