<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { utils, writeFile } from "xlsx";
import { template } from "./config/xls-template";
import contentConfig from "./config/content.config";
import searchConfig from "./config/search.config";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { usePageSearch, type PageHooks, type PageEvents } from "/@/hooks/page";
import { ElMessage } from "element-plus";

const PageName = "supplyOrderRecord";
const baseUrl = "/supply/supplyOrderRecordDetail";

const { push } = useRouter();
const selectlist = ref<any[]>([]);

const hooks: PageHooks = {
  pageSearchHook: () => usePageSearch(undefined, undefined, searchConfig)
};

const events: PageEvents = {
  content: {
    preview: ({ payNo }) => push(`${baseUrl}?id=${payNo}`),
    create: () => push(baseUrl)
  }
};

//导出模板
function onDownloadTemplate() {
  if (selectlist.value.length === 0) {
    ElMessage.error("至少勾选一条对账单");
    return;
  }

  const _data: any = [];
  for (const { status, payNo, supplierNo } of selectlist.value) {
    if (String(status) !== "2") {
      ElMessage.error(`对账单 ${payNo},未通过审核`);
      return;
    } else {
      _data.push({
        ...template,
        ["卖方公司编码"]: supplierNo,
        ["对账编号"]: payNo
      });
    }
  }

  //创建数据表
  const workBook = utils.book_new();
  const workSheet = utils.json_to_sheet(_data);
  utils.book_append_sheet(workBook, workSheet, "sheet");

  //导出模板
  writeFile(workBook, "批量开票申请模板.xlsx", {
    bookType: "xlsx"
  });
}
</script>

<template>
  <PageAuth :pageName="PageName">
    <PageContainer
      :hooks="hooks"
      :events="events"
      :contentConfig="contentConfig"
      :search-config="searchConfig"
      @content-select-change="items => (selectlist = items)"
    >
      <template #content_header>
        <ElButton
          size="small"
          :icon="useRenderIcon('arrow-down-line')"
          @click="() => onDownloadTemplate()"
          >下载批量开票模板</ElButton
        >
      </template>
    </PageContainer>
  </PageAuth>
</template>
