<script setup lang="ts">
import { ref, shallowRef } from "vue";
import contentConfig from "./config/content.config";
import searchConfig from "./config/search.config";
import { usePageSearch, type PageHooks, type PageEvents } from "/@/hooks/page";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import PostModal from "./components/post-modal.vue";
import { useUserInfo } from "/@/hooks/core/useUser";
import { useRouter } from "vue-router";
import { httpSetPost, httpStatus } from "/@/api/InvoiceSales/invoiceApply";
import { useAsync } from "/@/hooks/core/useAsync";
import ExeclUpload from "./components/execl-files-upload/index.vue";
import { httpRequsetExport } from "/@/utils/export";
import { template } from "./config/xls-template";
import { usePermission } from "/@/hooks/core/usePermission";
import ApprovalModal from "./components/approval-modal.vue";
import BackModal from "./components/back-modal.vue";
import { ElMessage } from "element-plus";
import { writeFile, utils } from "xlsx";
import InvoiceModal from "./invoice-modal.vue"

const PageName = "invoiceApply";

//   { code: "040", name: "批量审核" },
//   { code: "026", name: "导出发票申请信息" },
//   { code: "027", name: "下载发票信息导入模板" },
//   { code: "028", name: "批量导入财务开票结果（发票申请）" },

const { hasPermissionWithCode } = usePermission(PageName);
const loading = ref(false);
const baseUrl = "/InvoiceSales/invoiceApplyDetail";
const postModalRef = ref<InstanceType<typeof PostModal> | null>(null);
const invModalRef = ref<InstanceType<typeof InvoiceModal> | null>(null);
const execlUploadRef = ref<InstanceType<typeof ExeclUpload> | null>(null);
const approvalModalRef = ref<InstanceType<typeof ApprovalModal> | null>(null);
const backModalRef = ref<InstanceType<typeof BackModal> | null>(null);
const { isSuperUser } = useUserInfo();
const instance = ref(null);

const { run } = useAsync({ success: () => instance.value.onSearch() });
const { run: approval } = useAsync({ success: () => instance.value.onSearch() });

const handleApproval = ({ invNo }) => approval(httpStatus({ invNo, status: "7" }));
const { push } = useRouter();
const selected = ref<any[]>([]);

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

function handleSetPost(data) {
  run(httpSetPost(data));
}

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

//导出模板
async function onDownloadOpenInv() {
  await httpRequsetExport({
    url: "/ipe",
    name: "开票信息",
    onStart: () => (loading.value = true),
    onSuccess: () => (loading.value = false),
    onFail: () => (loading.value = false),
    params: {  ...instance.value.getBasicParams() }
  });
}

function handleBatchApproval() {
  if (selected.value.length === 0) {
    ElMessage.warning('请选择至少一条"待财务审核"的发票申请');
    return;
  }

  if (!selected.value.every(({ status }) => String(status) === "1")) {
    ElMessage.warning('请选择状态为"待财务审核"的发票申请');
    return;
  }

  approvalModalRef.value.onDisplay(selected.value);
}

function onDownloadTemplate() {
  //创建数据表
  const workBook = utils.book_new();
  const workSheet = utils.json_to_sheet([template]);
  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 => (instance = ref)"
      @content-select-change="val => (selected = val)"
    >
      <template #content_header>
        <ElButton
          v-if="hasPermissionWithCode('040') && !isSuperUser"
          size="small"
          @click="handleBatchApproval"
        >
          财务批量审核(勾选)
        </ElButton>
        <ElButton
          v-if="hasPermissionWithCode('026')"
          :icon="useRenderIcon('arrow-up-line')"
          size="small"
          :loading="loading"
          @click="() => onDownloadOpenInv()"
          >开票信息导出</ElButton
        >
        <ElButton
          v-if="hasPermissionWithCode('027')"
          :icon="useRenderIcon('arrow-down-line')"
          size="small"
          @click="() => onDownloadTemplate()"
          >下载发票信息导入模板</ElButton
        >

        <!-- v-if="!isSuperUser && hasPermissionWithCode('028')" -->
        <ElButton
          @click="() => execlUploadRef.onDisplay()"
          size="small"
          >批量导入财务开票结果（发票申请）</ElButton
        >
      </template>

      <template #content_action="{ status, post_code, invNo, inv_type, inv_number }">
        <ElTooltip
          content="填写物流"
          placement="top"
          v-if="!isSuperUser && String(status) === '3' && !post_code"
        >
          <ElButton
            text
            type="primary"
            style="margin-left: 0px"
            :icon="useRenderIcon('promotion')"
            @click="() => postModalRef.onDisplay(invNo)"
          />
        </ElTooltip>

        <ElPopconfirm
          v-if="
            (String(status) === '1' || String(status) === '5') &&
            hasPermissionWithCode('010') &&
            !isSuperUser
          "
          placement="top"
          title="是否确认撤销开票申请?"
          @confirm="() => handleApproval({ invNo })"
        >
          <template #reference>
            <ElButton
              text
              type="primary"
              style="margin-left: 0px"
              :icon="useRenderIcon('refresh-right')"
            />
          </template>
        </ElPopconfirm>

        <ElTooltip content="修改发票信息" placement="top">
          <ElButton
            v-if="
              String(status) === '5' &&
              hasPermissionWithCode('005') &&
              !isSuperUser
            "
            text
            style="margin-left: 0px"
            :icon="useRenderIcon('edit')"
            type="primary"
            @click="() => backModalRef.onDisplay(inv_type, invNo)"
          />
        </ElTooltip>

        <ElButton
          v-if="String(status) === '4' || String(status) === '6'"
          link
          type="primary"
          :icon="useRenderIcon('scaletooriginal')"
          @click="() => invModalRef.open(inv_number)"
        />
      </template>
    </PageContainer>

    <PostModal ref="postModalRef" @post-save="handleSetPost" />
    <ApprovalModal
      ref="approvalModalRef"
      @onBatchApprovalComplete="() => instance.onSearch()"
    />
    <ExeclUpload ref="execlUploadRef" @on-success="() => instance.onSearch()" />
    <back-modal ref="backModalRef" @refresh="() => instance.onSearch()" />
      
    <InvoiceModal ref="invModalRef" />
  </PageAuth>
</template>
