<script setup lang="ts">
import { ref } from "vue";
import { httpBatchUploadInvoice } from "/@/api/InvoiceSales/invoiceApply";
import { execlUpload } from "/@/components/execlUpload";
import { useTask } from "/@/hooks/core"
import { ElMessage } from "element-plus";


import { columns,isEmpty, isHeaderSame, generateTableData, validate, translateData } from "./utils";
const emit = defineEmits(["onSuccess"]);
const tableData = ref<Record<string,any>[]>([])

const uploadTask = useTask({ success(){
  tableData.value = []
  ElMessage.success("数据导入成功！");
  emit("onSuccess");
} })

const Uploadsuccess = ({ results, header }) => {
  uploadTask.loading = true;
  if (isEmpty(results)) {
    ElMessage.error("表格无有效数据！");
    uploadTask.loading = false;
    return;
  }
  if(!isHeaderSame(header)){
    ElMessage.error("表头与导入模板不匹配！");
    uploadTask.loading = false;
    return;
  }
  const data = generateTableData(results)
  if(validate(data)){ tableData.value = data }
  uploadTask.loading = false;
};

function onSubmit() { 
  if (uploadTask.loading) return;
  if(!validate(tableData.value)){ return }
  const data = translateData(tableData.value)
  uploadTask.run(httpBatchUploadInvoice({ data }))
}
</script>

<template>
  <div class="flex flex-col bg-white">
    <execlUpload class="mb-[10px]" @on-success="Uploadsuccess" v-if="tableData.length === 0" />
    <el-table
      :data="tableData"
      stripe
      border
      max-height="500px"
      size="small"
      style="width: 100%"
    >
      <el-table-column
        v-for="(column, index) in columns"
        v-bind="column"
        :key="index"
        show-overflow-tooltip
      />
    </el-table>
    <div
      flex
      justify-end
      gap-2
      v-if="tableData.length !== 0"
      style="padding: 10px 0 0 0"
    >
      <el-button size="small" @click="tableData = []">取消</el-button>
      <el-button size="small" type="primary" :loading="uploadTask.loading" @click="onSubmit">保存</el-button
      >
    </div>
  </div>
</template>

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