<script setup lang="ts">
import { ref } 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 InvoiceModal from "./components/invoice-modal.vue";
import { useRouter } from "vue-router";
import { httpRequsetExport } from "/@/utils/export";
import { useCompany } from "/@/hooks/core/useCompany";
import { PageContent } from "/@/components/PageContent";
import ExeclUpoad from "./components/execl-files-upload/index.vue";
import { usePermission } from "/@/hooks/core/usePermission";
import { useUserInfo } from "/@/hooks/core/useUser";
import { utils, writeFile } from "xlsx";
import { template } from "./config/xls-template";
import ExcelUploadRelation from "./components/excel-files-upload-relation/index.vue"
import { httpStatus } from "/@/api/purchase/ticketReturn";
import { useAsync } from "/@/hooks/core/useAsync";
import { ElMessage } from "element-plus"

import { division, subtraction } from "/@/utils/calc";
import { httpInvoiceDetail, httpPurchaseInvoice } from "/@/api/invoice"
import { invoiceTypeList } from "/@/utils/status";

const pageName = "supplyTicketReturn";
const baseUrl = "/supply/supplyTicketReturnDetail";
const invStatus = ['2','3',"4", '6','7', "10", "11", "12", "13"];
const loading = ref(false);

// { code: "032", name: "导出对账开票数据" },
// { code: "033", name: "批量创建开票数据" }
const { hasPermissionWithCode } = usePermission(pageName);
const excelUploadRelationRef = ref<InstanceType<typeof ExcelUploadRelation> | null>(null)
const { isSuperUser } = useUserInfo();
const selected = ref([])

const { push } = useRouter();
const invoiceModalRef = ref<InstanceType<typeof InvoiceModal>>(null);
const execelUploadRef = ref<InstanceType<typeof ExeclUpoad>>(null);
const pageContentRef = ref<InstanceType<typeof PageContent>>(null);

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

const { currentCompany } = useCompany();

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

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

//导出模板
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"
  });
}

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


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

  if (selected.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: selected.value[0].payNo
    }
  });
}

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

async function handleExportInvoice(){
  if(selected.value.length === 0){
    ElMessage.warning("请选择一条对账回票申请")
    return
  }

  if(selected.value.length > 1){
    ElMessage.warning('只能选择一条对账回票申请')
    return
  }

  const labels = ['待关联订单','订单关联完毕待财务审核','待买方公司认证','认证成功','认证失败','回票已退', '财务审核驳回']
  const [ row ] = selected.value

  if(!invStatus.includes(String(row.status))){
    ElMessage.warning('请选择状态为:' + labels.join('、') + '的采购单')
    return
  }


  const result = await httpInvoiceDetail({ code: row.hpNo })
  const result2 = await httpPurchaseInvoice({ number: row.invoiceNumber })
  const { data = [] } = (result || {})
  const { buyer_name,  buyer_id, seller_name,  seller_id, number: invoiceNumber, issue_date, type } = ((result2 || {}).data || {})

  const template = data.map((item) => {
    const { total_amount, tax_amount, num } = item
    const beforeTaxTotalAmount = Number(subtraction(total_amount, tax_amount)).toFixed(2)
    const beforeTaxPrice = (!Number(beforeTaxTotalAmount) || !Number(num)) ? '' : Number(division(beforeTaxTotalAmount, num)).toFixed(2)
    const afterTaxPrice = (!Number(total_amount) || !Number(num)) ? '' :  Number(division(total_amount, num)).toFixed(2)

    return {
      '发票明细ID': item.id,
      "对账回票编号":item.invoiceCode,
      '发票类型': invoiceTypeList.find(item => item.value === type)?.label || '--',
      '发票号码': invoiceNumber,
      '开票日期': issue_date,
      '购买方名称': buyer_name,
      '购买方纳税人识别号': buyer_id,
      '销售方名称': seller_name,
      '销售方纳税人识别号': seller_id,
      '类目编号': item.cat_code,
      '货物或应税劳务、服务名称': item.good_name,
      '单位': item.unit,
      '数量': num,
      '单价': beforeTaxPrice,
      '金额': beforeTaxTotalAmount,
      '税率': item.tax,
      '税额': tax_amount,
      '税后单价': afterTaxPrice,
      '税后金额': total_amount,
      '采购单关联金额': '',
      '对账单号': '',
      '采购单编号': '',
      '销售单编号': '',
      '供货商': '',
      '业务公司': '',
      '订单单位': '',
      '商品数量': '',
      '商品单价': '',
      '总货款': '',
      '销售主单号': '',
      '商品编码': '',
      '商品名称':  '',
      '货物和劳务名称': '',
      '商品开票类目': '',
      '商品和服务分类简称': '',
      '开票税率': '',
      '开票商品名称': '',
      '开票类型': '',
      '采购单可关联金额': ''
    }
  })

  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" v-loading="approvalLoading">
    <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-up-line')"
          @click="() => execelUploadRef.onDisplay()"
          v-if="hasPermissionWithCode('033') && !isSuperUser"
          >批量创建开票数据</ElButton
        >
        
        <ElButton
          size="small"
          v-if="!isSuperUser && hasPermissionWithCode('064')"
          :icon="useRenderIcon('arrow-up-line')"
          @click="() => excelUploadRelationRef.onDisplay()"
          >批量导入票与订单关联数据
        </ElButton>
        
        <ElButton
          size="small"
          :loading="loading"
          :icon="useRenderIcon('arrow-down-line')"
          @click="() => onDownloadPayInfo()"
        >
          对账单明细导出
        </ElButton>


        <ElButton
          size="small"
          type="primary"
          v-if="hasPermissionWithCode('033') && !isSuperUser"
          :icon="useRenderIcon('arrow-down-line')"
          @click="handleExportInvoice"
          >导出发票明细
        </ElButton>
      </template>

      <template #content_action="row">
        <ElButton
          link
          type="primary"
          :icon="useRenderIcon('scaletooriginal')"
          @click="() => invoiceModalRef.onDisplay(row)"
          v-if="invStatus.includes(String(row.status))"
        />

        <ElTooltip  v-if="(row.status == '11' || row.status == '9') && hasPermissionWithCode('010')"  content="撤销发票申请" placement="top">
          <ElButton link type="primary" :icon="useRenderIcon('refresh')" @click="handleRefresh(row)" />
        </ElTooltip>
      </template>
    </PageContainer>

    <InvoiceModal ref="invoiceModalRef" />

    <ExeclUpoad
      ref="execelUploadRef"
      @on-success="() => (pageContentRef as any).onSearch()"
    />

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

<style lang="scss" scoped>
:deep(.el-upload-list__item) {
  display: none !important;
}
</style>
