<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";
import { usePermission } from "/@/hooks/core/usePermission";
import { httpRequsetExport } from "/@/utils/export";
import { useAsync } from "/@/hooks/core/useAsync";
import { httpStatus } from "/@/api/purchase/orderRecord";

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

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

//{ code: "031", name: "下载批量开票模板" }
const { hasPermissionWithCode } = usePermission(PageName);

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

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

const contentRef = ref<any>(null);
const { run: revoke } = useAsync({
  success: () => contentRef.value.onSearch()
});

//导出模板
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"
  });
}

async function onDownloadPayInfo() {
  if (selectlist.value.length === 0) {
    ElMessage.warning("请选择一条对账单");
    return;
  }

  if (selectlist.value.length > 1) {
    ElMessage.warning("只能选择一条对账单");
    return;
  }

  await httpRequsetExport({
    url: "paycgdexport",
    name: "对账单明细表",
    onStart: () => (loading.value = true),
    onSuccess: () => (loading.value = false),
    onFail: () => (loading.value = false),
    params: {
      payNo: selectlist.value[0].payNo
    }
  });
}

const handleRevoke = payNo => {
  revoke(
    httpStatus({
      payNo,
      status: "4"
    })
  );
};
</script>

<template>
  <PageAuth :pageName="PageName">
    <PageContainer
      :hooks="hooks"
      :events="events"
      :contentConfig="contentConfig"
      :search-config="searchConfig"
      :get-content-ref="ref => (contentRef = ref)"
      @content-select-change="items => (selectlist = items)"
    >
      <template #content_header>
        <ElButton
          type="small"
          :loading="loading"
          v-if="hasPermissionWithCode('038')"
          @click="() => onDownloadPayInfo()"
        >
          对账单明细导出
        </ElButton>

        <ElButton
          size="small"
          v-if="hasPermissionWithCode('031')"
          :icon="useRenderIcon('arrow-down-line')"
          @click="() => onDownloadTemplate()"
          >下载批量开票模板</ElButton
        >
      </template>

      <template #content_action="row">
        <ElTooltip placement="top" content="撤销对账申请">
          <ElButton
            v-if="
              (String(row.status) === '1' || String(row.status) === '2') &&
              hasPermissionWithCode('006')
            "
            type="primary"
            link
            text
            :icon="useRenderIcon('refresh-right')"
            @click="() => handleRevoke(row.payNo)"
          />
        </ElTooltip>
      </template>
    </PageContainer>
  </PageAuth>
</template>
