<script setup lang="ts">
import { ref, shallowReactive } from "vue";
import contentConfig from "./config/content.config";
import searchConfig from "./config/search.config";
import { usePageSearch, type PageHooks, type PageEvents } from "/@/hooks/page";
import InvoiceModal from "./components/invoice-modal.vue";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { useRouter } from "vue-router";
import { httpRequsetExport } from "/@/utils/export";
import { useCompany } from "/@/hooks/core/useCompany";
import { PageContent } from "/@/components/PageContent";
import { utils, writeFile } from "xlsx";
import { template } from "./config/xls-template";
import { usePermission } from "/@/hooks/core/usePermission";
import { useUserInfo } from "/@/hooks/core/useUser";
import { httpInvoiceDetail, httpPurchaseInvoice, httpDeleteInvoice } from "/@/api/invoice"
import ExcelUploadInv from "./components/execl-files-upload-inv/index.vue";
import { useAsync } from "/@/hooks/core/useAsync";
import { httpStatus } from "/@/api/purchase/invoiceRelation";
import { ElMessage } from "element-plus"

import CreateModal from "./create-modal.vue"
import ChooseModal from "./choose-modal.vue"

const PageName = "inputInvoicePool";
const baseUrl = "/purchase/inputInvoicePoolDetail";
const invStatus = ['2','3',"4",'6','7',"10","11","12", "13"];

const selected = ref([])
const { isSuperUser } = useUserInfo();
const { hasPermissionWithCode, permissions } = usePermission(PageName);
const pageContentRef = ref<InstanceType<typeof PageContent> | null>(null);

const loading = ref(false);
const { push } = useRouter();
const { currentCompany } = useCompany();

const invoiceModalRef = ref<InstanceType<typeof InvoiceModal>>(null);
const excelUploadInvRef = ref<InstanceType<typeof ExcelUploadInv>>(null);


const visible = ref(false)
const state = ref({ visible: false, current: {  companyNo: '', supplierNo: '', companyName: '', supplierName: ''  } })


const { run: approval, loading: approvalLoading } = useAsync({
  success: () => {
    ElMessage.success('撤销成功')
    pageContentRef.value?.onSearch()
  }
});


const { run: runDelete, loading: deleteLoading } = useAsync({ 
  success(){
    ElMessage.success('删除成功!')
    pageContentRef.value?.onSearch()
  }
 })


async function handleDownload() {
  await httpRequsetExport({
    url: "ile",
    name: "回票数据表",
    onStart: () => (loading.value = true),
    onSuccess: () => (loading.value = false),
    onFail: () => (loading.value = false),
    params: {
      companyNo: currentCompany.value.companyNo,
      ...(pageContentRef.value as any).getBasicParams()
    }
  });
}

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

const events: PageEvents = {
  content: {
    preview: ({ InvCode }) => push(`${baseUrl}?id=${InvCode}`),
    create: () => visible.value = true
  }
};

//导出模板
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 handleBindCompany(row){
  state.value.current = { ...row }
  state.value.visible = true
}

function handleRefresh(row){
  const params = { status: '8', hpNo: row.hpNo };
  approval(httpStatus(params));
}


function onDelete(row){
  runDelete(httpDeleteInvoice({InvCode: row.InvCode}))
}
</script>

<template>
  <PageAuth :pageName="PageName" v-loading="approvalLoading || deleteLoading">
    <PageContainer :hooks="hooks" :events="events" :contentConfig="contentConfig" :search-config="searchConfig"
      :get-content-ref="(ref: any) => (pageContentRef = ref)" @content-select-change="(value) => selected = value">
      <template #content_header>
        <ElButton size="small" :icon="useRenderIcon('arrow-down-line')" @click="onDownloadTemplate">下载发票信息模板</ElButton>

        <ElButton size="small" type="primary" v-if="hasPermissionWithCode('033')" :icon="useRenderIcon('arrow-up-line')"
          @click="() => excelUploadInvRef.onDisplay()">上传发票信息
        </ElButton>
      </template>

      <template #content_action="row">
        <!-- v-if="String(row.status) === '1' || String(row.status) === '2' || String(row.status) === '5'" -->
        <ElButton link type="primary" :icon="useRenderIcon('scaletooriginal')"
          @click="() => invoiceModalRef.onDisplay({ ...row, invoiceNumber: row.invoice_number })" />


        <ElTooltip content="绑定公司" v-if="hasPermissionWithCode('066') && !isSuperUser && String(row.status) === '1'">
          <ElButton link type='primary' :icon="useRenderIcon('home-filled')" @click="handleBindCompany(row)" />
        </ElTooltip>

        <ElPopconfirm title="是否确认删除?" @confirm="onDelete(row)" v-if="
                (String(row.status) === '1' || String(row.status) === '2' || String(row.status) === '5') && 
                hasPermissionWithCode('006') && 
                !isSuperUser
              ">
          <template #reference>
            <el-button class="reset-margin" link type="primary" :size="'mini'" :icon="useRenderIcon('delete')" />
          </template>
        </ElPopconfirm>
      </template>
    </PageContainer>

    <InvoiceModal ref="invoiceModalRef" />


    <ChooseModal :data="state.current" v-model:visible="state.visible" @refresh="pageContentRef?.onSearch()" />

    <CreateModal v-model:visible="visible" @refresh="pageContentRef?.onSearch()" />

    <ExcelUploadInv ref="excelUploadInvRef" @on-success="() => (pageContentRef as any).onSearch()" />
  </PageAuth>
</template>
