<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import * as XLSX from "xlsx";
import {
  assessmentDownloadDataRosterTemplateApi,
  postImportAssessmentTemplate
} from "@/api/download";
import { ElMessage } from "element-plus";
defineOptions({
  name: "IndexDefineImport"
});
const route = useRoute();
const router = useRouter();
const emit = defineEmits(["handleImport"]);
const uploadShow = ref(true);
const query = ref({});
const fileDocument = ref<File | null>(null); // 存储文件

onMounted(() => {
  // assessmentType
  Object.assign(query.value, route.query);
  console.log("111", query.value);
});
const uploadFile = () => {};
const tableHeaders = ref<any>([]);
const tableData = ref<any>([
  { name: "" },
  { defin: "" },
  { caliber: "" },
  { type: "" },
  { from: "" }
]);
const handleUploadChange = (file: File) => {
  fileDocument.value = file; // 保存文件
  const reader = new FileReader();
  let fileType = file.name.slice(-4);
  console.log("文件", file.name.slice(-4));
  if (fileType == "xlsx") {
    reader.onload = e => {
      const data = new Uint8Array(e.target?.result as ArrayBuffer);
      const workbook = XLSX.read(data, { type: "array" }); // 读取 Excel 文件
      const firstSheetName = workbook.SheetNames[0]; // 获取第一个工作表名
      const worksheet = workbook.Sheets[firstSheetName]; // 获取第一个工作表
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); // 将工作表转为 JSON

      if (jsonData.length > 0) {
        tableHeaders.value = jsonData[0]; // 表头
        tableData.value = jsonData.slice(1).map(row => {
          const rowData = {};
          tableHeaders.value.forEach((header, index) => {
            rowData[header] = row[index] !== undefined ? row[index] : null; // 填充缺失值
          });
          return rowData;
        });
        console.log("表头", tableHeaders.value);
        ElMessage.success("文件上传成功");
        uploadShow.value = false; // 隐藏上传区域，显示数据表
      } else {
        ElMessage.error("文件为空或格式不正确");
      }
    };
  } else {
    ElMessage.error("请上传xlsx文件");
  }

  reader.readAsArrayBuffer(file); // 读取文件为 ArrayBuffer
};
// 上传
const postImportAssessmentTemplateApi = async data => {
  if (!fileDocument.value) {
    ElMessage.error("请先上传文件");
    return;
  }
  try {
    const formData = new FormData();
    formData.append("file", fileDocument.value); // 将文件添加到表单数据

    // 调用 API 上传文件
    const { data } = await postImportAssessmentTemplate({
      formData,
      type: route.query.assessmentType,
      assessmentId: route.query.id
    });
    console.log("dsada", data);
    if (data.code === 200) {
      // 根据后端返回的 code 判断是否成功
      ElMessage.success("文件上传并导入成功");
      // 重置上传状态
      // uploadShow.value = true;
      // $router.push("/IndexDefine/children/define");
      router.back();
      uploadShow.value = !uploadShow.value;
      tableHeaders.value = []; // 清空表头
      tableData.value = [
        { name: "" },
        { defin: "" },
        { caliber: "" },
        { type: "" },
        { from: "" }
      ]; // 清空表格数据
    } else {
      ElMessage.error(data.msg);
    }
  } catch (error) {
    ElMessage.error("上传失败，请重试");
    console.error(error);
  }
};
const backDefine = () => {
  router.back();
};
</script>

<template>
  <div>
    <div class="w-3/4 m-auto mt-4">
      <div class="w-full bg p-3">
        <h5>1.下载导入模板</h5>
        <p class="text-xs mt-2 text">根据提升信息完善表格内容</p>
        <el-button
          class="mt-2"
          @click="
            assessmentDownloadDataRosterTemplateApi(route.query.assessmentType)
          "
          ><el-icon><Download /></el-icon>下载空的模板表格</el-button
        >
      </div>
      <div class="w-full mt-4 bg p-3">
        <h5>2.上传完善后的模板</h5>
        <p class="text-xs mt-2 text mb-2">
          更新信息的模板中，如有空的数据列，则相应字段信息会被清空，请谨慎填写
        </p>
        <div v-if="uploadShow">
          <el-upload
            class="upload-demo"
            drag
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :before-upload="file => handleUploadChange(file)"
            :show-file-list="false"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              点击<em>图标选择上传</em>或者将文件拖拽到此区域
            </div>
          </el-upload>
        </div>
        <div v-else class="mb-2">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            max-height="250"
          >
            <el-table-column
              v-for="header in tableHeaders"
              :key="header"
              :label="header"
              :prop="header"
            />
          </el-table>
        </div>
        <div class="float-right">
          <el-button @click="backDefine">取消</el-button>
          <el-button type="primary" @click="postImportAssessmentTemplateApi"
            >确认</el-button
          >
        </div>
        <p class="h-11 no-select">.</p>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.bg {
  background-color: #f8f9fa;
}

.text {
  color: #999;
}

.upoload {
  float: right;
}

.no-select {
  color: rgb(255 255 255 / 0%);
  user-select: none;
}
</style>
