<template>
  <div class="table-box">
    <LjVxeTable
      ref="vxeTableRef"
      row-key="mattressid"
      :columns="columns"
      :init-param="initParams"
      :request-api="getData"
      :data-callback="dataCallback"
      :dwname="DwnameEnum.mattressInterface"
      :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="mattressQuote">
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, ElNotification } 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, YWAudit, JSAudit, 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_mattress_interfacelist";

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

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

    router.push({
      path: `/erpapi/mattressInterface/detail/${row.mattressid}`,
      query: {
        code: row.mattresscode
      }
    });
  }
};

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: "mattressid",
    parentField: "parentid"
  },
  checkboxConfig: {
    showHeader: true,
    checkStrictly: true
  },
  exportConfig: {
    filename: t("menu.rpMsttake") + formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss")
  }
};

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

/**
 * @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);
      // vxeTableRef.value.refresh();
      handleDBlClickTable({ row: curRecords[0] });
    }
  }),
  // [
  buttonDefault({
    label: "业务补充",
    power: 79,
    clickFunc: item => {
      routeToEdit(1);
    }
  }),
  buttonDefault({
    label: "业务审核",
    power: 80,
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);
      YWAudit(1, curRecords, () => {
        vxeTableRef.value.refresh();
      });
    }
  }),
  buttonDefault({
    label: "业务撤审",
    power: 81,
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);

      YWAudit(0, curRecords, () => {
        vxeTableRef.value.refresh();
      });
    }
  }),
  // ],
  // [
  buttonDefault({
    label: "产品补充",
    power: 82,
    clickFunc: item => {
      routeToEdit(2);
    }
  }),
  buttonDefault({
    label: "产品补充审核",
    power: 83,
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);

      JSAudit(1, curRecords, () => {
        vxeTableRef.value.refresh();
      });
    }
  }),
  buttonDefault({
    label: "产品补充撤审",
    power: 84,
    clickFunc: item => {
      const { curRecords } = getCurrentRecords(vxeTableRef.value);

      JSAudit(0, curRecords, () => {
        ElNotification({
          title: t("sys.api.operationSuccess"),
          message: "产品补充审核后，需重新生成L1物料",
          type: "warning"
        });
        vxeTableRef.value.refresh();
      });
    }
  }),
  // ],
  // [
  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.mattressid);
      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.mattressid);
      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].mattressid);
  //   }
  // })
  // ]
];

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/mattressInterface/${type}/edit?id=${_cur.mattressid}&code=${_cur.mattresscode}&type=${type}`);

  try {
    if (type === 1) {
      if (_cur.yw_flag == 1) {
        throw new Error(_cur.mattresscode + "：已业务补充审核，无法修改");
      }
    } else if (type === 2) {
      if (_cur.js1_flag == 1) {
        throw new Error(_cur.mattresscode + "：已产品补充审核，无法修改");
      }
    } else if (type === 3) {
      if (_cur.js2_flag == 1) {
        throw new Error(_cur.mattresscode + "：已清单补充审核，无法修改");
      }
    }
  } catch (error) {
    ElMessage.error(error.message);
    return false;
  }

  router.push({
    path: `/erpapi/mattressInterface/edit/${_cur.mattressid}`,
    query: {
      code: _cur.mattresscode,
      type: type
    }
  });
};

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