<script setup lang="ts">
import { ref } from "vue";
import { httpUpload } from "/@/api/InvoiceSales/invoiceApply";
import { responseHandle } from "/@/utils/responseHandle";
import { execlUpload } from "/@/components/execlUpload";
import { useNav } from "/@/layout/hooks/nav";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";


import { columns, isEmpty, isHeaderSame, generateTableData } from "./utils";


const loading = ref(false);
const tableData = ref([]);
const { logout } = useNav();
const emit = defineEmits(["onSuccess"]);

const Uploadsuccess = ({ results, header }) => {
  loading.value = true;

  if (isEmpty(results)) {
    ElMessage.error("表格无有效数据！");
    loading.value = false;
    return;
  }

  if(isHeaderSame(header)){
    ElMessage.error("表头与导入模板不匹配！");
    loading.value = false;
    return;

  }

  tableData.value = generateTableData(results)
  loading.value = false;
};


//提交
const handleSubmit = async () => {
  if (loading.value) return;
  loading.value = true;

  const data = ""

  const { code, message } = await httpUpload({ data });
  loading.value = false;
  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      ElMessage.success("数据导入成功！");
      emit("onSuccess");
    }
  });
};

const cancel = () => {
  tableData.value = [];
};
</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"
        :prop="(column.label === '序号' && index === 1) ? 'invNo' : column.prop"
        :label="(column.label === '序号' && index === 1) ? '发票申请编号' : column.label"
        :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="cancel">取消</el-button>
      <el-button size="small" type="primary" :loading="loading" @click="handleSubmit">保存</el-button
      >
    </div>
  </div>
</template>

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