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

import { useUserInfo } from "/@/hooks/core/useUser";

import { httpRequsetExport } from "/@/utils/export";



const PageName = "sendOrderRecord";
const pageContentRef = ref<any>(null);

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

const { isSuperUser } = useUserInfo();

const { hasPermissionWithCode } = usePermission("sendOrderRecord");

const events: PageEvents = {
  content: {
    preview: row => push(`/postSupplierOrder/sendOrderRecordDetail?id=${row.payNo}`),
    create: () => push('/postSupplierOrder/sendOrderRecordDetail')
  }
};

const handleRevoke = payNo => {
  revoke(
    httpOldStatus({
      payNo,
      status: "4"
    })
  );
};


const { run: revoke } = useAsync({
  success: () => pageContentRef.value.onSearch()
});


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

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

  const _data: any = [];
  for (const { status, payNo, supplierNo, supplierName,companyNo,companyName } of selectlist.value) {
    if (String(status) !== "2") {
      ElMessage.error(`对账单 ${payNo},未通过审核`);
      return;
    } else {
      _data.push({
        ...template,
        ["对账编号"]: payNo,
        ['买方公司编码']: companyNo,
        ["卖方公司编码"]: supplierNo,
        ['买方公司名称']: companyName,
        ['卖方公司名称']: supplierName
      });
    }
  }
  //创建数据表
  const workBook = utils.book_new();
  const workSheet = utils.json_to_sheet(_data);
  utils.book_append_sheet(workBook, workSheet, "sheet");

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


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

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

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

<template>
  <PageAuth :pageName="PageName">
    <PageContainer 
      @content-select-change="items => (selectlist = items)"
      :hooks="hooks"
      :events="events" 
      :content-config="contentConfig" 
      :searchConfig="searchConfig"
      :get-content-ref="ref => pageContentRef = ref"
    >
    <template #content_header>
        <ElButton
         :loading="loading"
           @click="() => onDownloadPayInfo()"
          size="small"
          v-if="hasPermissionWithCode('038')"
        >
          对账单明细导出
        </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') && String(row.is_comon) === '0' && !isSuperUser
            "
            type="primary"
            link
            text
            :icon="useRenderIcon('refresh-right')"
            @click="() => handleRevoke(row.payNo)"
          />
        </ElTooltip>
      </template>
  </PageContainer>
  </PageAuth>
</template>
