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


import { PURCHASE_OLD_APPLY_DATE } from "/@/utils/constants"

const pageName = "orderRecord";
const baseUrl = "/purchase/orderRecordDetail";

const loading = ref(false);
const selectlist = ref<any[]>([]);

const { isSuperUser } = useUserInfo();
const { push } = useRouter();
const contentRef = ref<any>(null);

const { run: revoke } = useAsync({
  success: () => {
    ElMessage.success("撤销对账成功");
    contentRef.value.onSearch();
  }
});

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

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

const handleRevoke = (props: any = {}) => {
  const { payNo } = props;
  if('pay_tag_id' in props && Number(props.pay_tag_id) !== 0){
    ElMessage.warning('请先解除付款标签再撤销对账单')
    return;
  }
  const date = payNo.slice(3, 9)
  const isOld = Number(date) < PURCHASE_OLD_APPLY_DATE
  revoke(isOld ? httpOldStatus({ payNo, status: "4" }) : httpStatus({ payNo, status: '4' }));
};

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

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
    }
  });
}

//导出模板
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"
  });
}
</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
          size="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('022') && String(row.is_comon) !== '1') && !isSuperUser
            "
            type="primary"
            link
            text
            :icon="useRenderIcon('refresh-right')"
            @click="() => handleRevoke(row)"
          />
        </ElTooltip>
      </template>
    </PageContainer>
  </PageAuth>
</template>
