<script setup lang="ts">
import { ref, reactive } from "vue";
import { execlUpload as ExcelUpload } from "/@/components/execlUpload";
import { columns, initialColumns, getPropertyAsLabel, convertInvoiceTitle, convertInvoiceTitleData, statusOptions  } from "./columns";
import { isValidHeader, isImportDataValid  } from "./validator"
import { useCompany } from "/@/hooks/core/useCompany";
import { httpList } from "/@/api/parameter/finance";
import { useResponseHandle } from "/@/hooks";
import { ElMessage } from "element-plus";
import { utils, writeFile } from "xlsx";
import { xs_inv_type_list } from "/@/utils/status"


import { useRenderIcon } from "/@/components/ReIcon/src/hooks";

import InvoiceTitle from "./InvoiceTitle.vue"
import ProcessModal from "./ProcessModal.vue"

const emit = defineEmits(["onSuccess"]);

const startGroup = ref(0)
const isStop = ref(false)
const isProcessing = ref(false)



const tableData = ref([]);
const { currentCompany } = useCompany();
const responseHandle = useResponseHandle();

const currentInvoiceTypes = ref<Record<string, any>>([])

const sellerInvoiceTitle = ref<Record<string, string>>({});
const purchaserInvoiceTitle = ref<Record<string, string>>({});
  const state = reactive({ visible: false, loading: false })

const setSellerInvoiceTitle = handleInvoiceTitle.bind(null, true);
const setPurchaserInvoiceTitle = handleInvoiceTitle.bind(null, false);


function handleInvoiceTitle(_isSeller: boolean, invoiceTitle: Record<string, string>) {
  if (!invoiceTitle) { return _isSeller ? (sellerInvoiceTitle.value = {}) : (purchaserInvoiceTitle.value = {})}
  if (_isSeller) {
    //支持的开票方式
    const { invoiceType, denomination: _denomination } = invoiceTitle;
    const chunks = invoiceType.split(",");
    sellerInvoiceTitle.value = convertInvoiceTitleData(convertInvoiceTitle(invoiceTitle))
  } else {
    purchaserInvoiceTitle.value = convertInvoiceTitleData(convertInvoiceTitle(invoiceTitle));
  }
}

const importHeader = ref([])
const initialHeader = initialColumns.slice(0, 7).map(({ label }) => label)

function onUploadSuccess({ results, header }){
  isProcessing.value = false
  isStop.value = false
  startGroup.value = 0

  if(!isValidHeader(initialHeader, header)){ return }
  const list = []
  for(const index in results){
    const result = results[index]
    const item: Record<string, any> = {}
    Object.keys(result).forEach(label => {
      const property = getPropertyAsLabel(label)
      const value = String(result[label]).trim()
      item[property] = value
    })
    list.push({...item, rawIndex: Number(index) + 1, status: 0 })
  }
  list.sort((a, b) => a.group - b.group)
  if(isImportDataValid(list, currentInvoiceTypes.value)) {
    tableData.value = list.map((item, index) => ({ index: Number(index) + 1, ...item }))
  }
}

const handleProcess = () => {
  state.visible = true;
  isProcessing.value = true
}

const clearData = () => {
  tableData.value = [];
  isProcessing.value = true
}

async function setTitle(companyNo, isSeller = true) {
  state.loading = true
  const { code, data, message } = await httpList({ companyNo });
  state.loading = false
  if(code === 0){

    if(isSeller){ 
      const { invoiceType } = data.list[0]
      const invoices = invoiceType.split(',')
      currentInvoiceTypes.value = xs_inv_type_list.filter(({ value }) => invoices.includes(value))
      // console.log(currentInvoiceTypes.value, '~~🚀~~') 
    }

      isSeller ? setSellerInvoiceTitle(data.list[0]) : setPurchaserInvoiceTitle(data.list[0])
  } else {
    ElMessage.warning(message)
  }
}

async function initialData(){
  await (currentCompany.value.companyNo && setTitle(currentCompany.value.companyNo))
  await setTitle('GS2404151642335170', false)
}

function handleUpdateGroup(groupData){
  const { status, remark, group } = groupData
  tableData.value.forEach((item: any) => {
    if(item.group != group) return
    // 之前已经该过状态,不能改到成功状态去
    if(item.status == 3 && status != 0) return
    item.remark = remark; 
    item.status = status
  })
}


function handleUpdateSequenceNo(sequenceData){
  const { status, remark, sequenceNo, group } = sequenceData
  tableData.value.forEach((item: any) => {
    if(item.sequenceNo == sequenceNo && item.group == group){ item.remark = remark; item.status = status; }
  })
}

function download(){
  const data = tableData.value.map((item: any, index) => ({
    '序号': Number(index) + 1,
    '分组': item.group,
    '发票类型':  item.invtype,
    '电子邮箱': item.email,
    '订单编号': item.sequenceNo,
    '订单平台类型': item.platform_type,
    '开票金额': item.inv_fee,
    '平台采购PO': item.poCode,
    '状态': statusOptions.find(({ value }) => value == item.status)?.label,
    '备注': item.remark
  }))

  const workBook = utils.book_new();
  const workSheet = utils.json_to_sheet(data);
  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([{
    '分组': '',
    '发票类型': '',
    '电子邮箱': '',
    '订单编号': '',
    '订单平台类型': '',
    '开票金额': '',
    '平台采购PO': ''
  }]);

  utils.book_append_sheet(workBook, workSheet, "sheet");
  writeFile(workBook, `批量创建发票申请模板.xlsx`, { bookType: "xlsx" });
}

function onStop(stop: boolean, stopGroup: number){
  isStop.value = stop
  startGroup.value = stopGroup ?? 0
}

initialData()
</script>

<template>
  <div 
    class="flex flex-col bg-white justify-start items-start" 
    style="height:calc(100vh - 48px);width: 100%"
    v-loading="state.loading"
  >
    <div class="flex w-full">
      <ElForm label-width="120px" style="width:100%">
        <ElRow>
          <ElCol :span="12">
            <ElFormItem label="销售方公司抬头">
              <div class="flex flex-col w-full">
                <ElInput 
                  :modelValue="(sellerInvoiceTitle || {}).invoice_title" 
                  class="mb-[10px]" 
                  disabled 
                />
                <InvoiceTitle :detail="sellerInvoiceTitle || {}" />
              </div>
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem label="购买方公司抬头">
              <div class="flex flex-col w-full">
                <ElInput
                  :modelValue="(purchaserInvoiceTitle || {}).invoice_title" 
                  class="mb-[10px]" 
                  disabled
                />
                <InvoiceTitle :detail="purchaserInvoiceTitle || {}" />
              </div>
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElForm>
    </div>

    <ExcelUpload 
      v-if="tableData.length === 0" 
      style="height:auto !important" 
      @onSuccess="onUploadSuccess" 
    />
    
    <div class="w-full flex items-center">
      <ElTag class="mb-[10px] mr-[5px]"> {{ tableData.length }} / 300 </ElTag>
      <span class="mb-[8px]" style="font-size: 14px">使用中遇到的问题</span>

      <ElPopover width="600px" placement="top">
        <div class="flex flex-col">
          <h1 class="font-bold">上传时验证:</h1>
          <p>1.分组必须为1开始的连续整数;</p>
          <p>2.单行数据只支持一个平台采购PO;</p>
          <p>3.同一分组平台类型、邮箱号、发票类型必须一致;</p>
          <p>4.同一分组订单编号+平台采购PO不能重复;</p>
          <p>5.同一分组数据不能超过10条;</p>
          <h1 class="font-bold">批量创建时验证:</h1>
          <p>1.按平台类型和销售订单编号查找必须找到订单;</p>
          <p>2.订单已开票金额+开票中金额+模板开票金额必须小于等于已认款总金额</p>
        </div>

        <template #reference>
          <ElButton class="mb-[10px]" link :icon="useRenderIcon('question-filled')" type="info" />
        </template>
      </ElPopover>
      
      <!-- <ElButton type="primary" size="small" @click="downloadTemplate">下载批量创建发票申请模板</ElButton> -->
    </div>

    <ElTable
      stripe
      border
      size="small"
      :data="tableData"
      max-height="500px"
      style="width: 100%"
    >
      <!-- v-bind="column"  -->
      <ElTableColumn 
        v-for="(column, index) in columns" 
        :type="column.type"
        :label="column.label"
        :minWidth="column.minWidth"
        :prop="column.prop"
        :fixed="column.fixed"
        :key="index" 
        show-overflow-tooltip
      >
        <template #header>
          <span v-if="!column?.required">{{ column.label }}</span>
          <p v-else>
            <span style="color: #f56c6c; font-size: 14px">* </span>
            {{ column.label }}
          </p>
        </template>


        <template #="{ row }">
          <ElTag v-if="column.prop === 'status'" :type="statusOptions.find(({ value }) => value === row.status)?.type || ''">
            {{ statusOptions.find(({ value }) => value === row.status)?.label || '--' }}
          </ElTag>
          <span v-else>{{ row[column.prop] }}</span>
        </template>
      </ElTableColumn>
    </ElTable>
    
    <div 
      class="w-full flex justify-end" 
      v-if="tableData.length !== 0" 
      style="padding: 10px 0 0 0"
    >
      <ElButton  @click="clearData">取消</ElButton>
      
      <ElButton
        v-if="!isProcessing"
        type="primary" 
        :loading="state.loading"
        @click="handleProcess"
        >批量创建</ElButton>


        <ElButton 
          v-else 
          type="primary"
          @click="download"
        >下载当前进度</ElButton>


        <ElButton v-if="isStop" @click="handleProcess">
          继续创建
        </ElButton>
    </div>

    <ProcessModal
      :data="tableData"
      v-model:visible="state.visible"
      :companyNo="currentCompany.companyNo"
      :sellerInvoiceTitle="sellerInvoiceTitle"
      :purchaserInvoiceTitle="purchaserInvoiceTitle"
      @updateGroup="handleUpdateGroup"
      @updateSequenceNo="handleUpdateSequenceNo"
      :startGroup="startGroup"
      @download="download"
      @refresh="clearData"
      @stop="onStop"
    />
  </div>
</template>

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