<script setup lang="ts">
import { h, reactive, 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 { ElDropdown, ElMessage, ElMessageBox } from "element-plus";
import { writeFile, utils } from "xlsx";
import InvoiceModal from "./invoice-modal.vue"


import CompanyModal from "./components/company-modal.vue";
import PersonModal from "./components/person-modal.vue"
import { useCompany } from "/@/hooks/core/useCompany";
import { useUserStoreHook } from "/@/store/modules/user";

const { logina } = useUserStoreHook();
const {  token1, token2, timeError } = useUserInfo();
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)
};

const { currentCompany } = useCompany()

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

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

//导出模板
async function onDownloadOpenInv() {
  const { total } = instance.value.getPagination()

  if(total > 50){
    ElMessage.warning('导出发票申请不允许超过50条')
    return
  }

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

function downloadTemplate(){
  const workBook = utils.book_new();
  const workSheet = utils.json_to_sheet([{
    '分组': '1',
    '发票类型': '电子发票（增值税专用发票）',
    '电子邮箱': 'shangyu1@wanyuhengong.cn',
    '订单编号': 'FQR2410150940395002',
    '订单平台类型': 'toB',
    '开票金额': '100',
    '平台采购PO': 'PO-YL31-2024-1596'
  },{
    '分组': '2',
    '发票类型': '电子发票（增值税专用发票）',
    '电子邮箱': 'shangyu2@wanyuhengong.cn',
    '订单编号': 'FQR2410150940395001',
    '订单平台类型': 'toB',
    '开票金额': '300',
    '平台采购PO': 'PO-YL32-2024-1696'
  },{
    '分组': '3',
    '发票类型': '电子发票（增值税专用发票）',
    '电子邮箱': 'shangyu3@wanyuhengong.cn',
    '订单编号': 'FQR2410150940399002',
    '订单平台类型': 'toC',
    '开票金额': '900',
    '平台采购PO': 'PO-YL31-2024-1597'
  }]);

  utils.book_append_sheet(workBook, workSheet, "sheet");
  writeFile(workBook, `批量创建发票申请模板(通用订单元隆定制).xlsx`, { bookType: "xlsx" });
}


const visibles = reactive({
  company: false,
  person: false
})
function gotoPush(){
  const arr = token1.value.split(",");
  if (Number(token2.value) === 1 && Number(arr[3]) === 1) {
    ElMessage.warning(timeError.value + "");
      setTimeout(() => {
        logina("0");
      }, 30000);
    return;
  }else{
    push('/InvoiceSales/batchImportYunlong')
  }
  
}

function handleCompany(){

  const companies = ['GS2302231125079621', 'GS2304031312553746', 'GS2402020907088731', 'GS2401181650538135', 'GS2302231124114965']
  if (!companies.includes(currentCompany.value.companyNo)){
    ElMessageBox({
      type: 'warning',
      title: '该功能仅支持以下公司使用:',
      message:h('div', { style: { display: 'flex', flexDirection: 'column' } }, [
        h('p', null, '北京知事文化产业发展有限公司'),
        h('p', null, '北京锦兴弘昌科技有限公司'),
        h('p', null, '北京普润心堂商贸有限公司'),
        h('p', null, '北京泰文创供应链管理有限公司使用'),
        h('p', null, '北京锦兴弘昌科技有限公司'),
      ])
    })
    return
  }



  visibles.company = true
}
</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>
        <ElDropdown  v-if="hasPermissionWithCode('070') || hasPermissionWithCode('071')">
          <ElButton size="small" style="margin-right: 10px">
            发票申请订单明细导出
          </ElButton>

          <template #dropdown>
            <ElDropdownItem @click="handleCompany" v-if="hasPermissionWithCode('071')">
              业务公司
            </ElDropdownItem>
           
            <ElDropdownItem @click="visibles.person = true"  v-if="hasPermissionWithCode('070')">
              业务经理
            </ElDropdownItem>
          </template>
        </ElDropdown>

        <template v-if="hasPermissionWithCode('069')">
          <ElButton v-if="!isSuperUser" size="small" :icon="useRenderIcon('arrow-up-line')"
            @click="gotoPush()">
            批量创建发票申请(通用订单元隆定制)
          </ElButton>

          <ElButton size="small" :icon="useRenderIcon('arrow-down-line')" @click="downloadTemplate">
            下载批量创建发票申请模板(通用订单元隆定制)
          </ElButton>
        </template>


        <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" />

    <CompanyModal v-model:visible="visibles.company" />
    <PersonModal v-model:visible="visibles.person" />
  </PageAuth>
</template>
