<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import * as XLSX from "xlsx";
import {
  assessmentDownloadDataRosterTemplateApi,
  importAssessmentQuotaDisplayBackData,
  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); // 存储文件
const assessmentType = ref();
onMounted(() => {
  // assessmentType
  Object.assign(query.value, route.query);
  assessmentType.value = Number(query.value.assessmentType);
});
const uploadFile = () => {};
const tableHeaders = ref<any>([]);
const tableData = ref<any>([]);
const handleUploadChange = async (file: File) => {
  fileDocument.value = file; // 保存文件
  const formData = new FormData();
  formData.append("file", fileDocument.value);
  const fileToSend = formData.get("file");
  const { code, data, msg } = await importAssessmentQuotaDisplayBackData({
    file: fileToSend,
    type: route.query.assessmentType,
    assessmentId: route.query.id
  });
  const reader = new FileReader();
  let fileType = file.name.slice(-4);
  // if (fileType == "xlsx") {
  if (data.code == 200) {
    uploadShow.value = false; // 隐藏上传区域，显示数据表
    tableData.value = data.data;
    ElMessage.success("导入成功");
  } else {
    ElMessage.error(data.msg);
  }
  reader.readAsArrayBuffer(file); // 读取文件为 ArrayBuffer
  return false; // 阻止默认上传行为
};
// 上传
const postImportAssessmentTemplateApi = async data => {
  if (!fileDocument.value) {
    ElMessage.error("请先上传文件");
    return;
  }
  try {
    const formData = new FormData();

    // 将 tableData 转换为 XLSX 格式
    // const ws = XLSX.utils.json_to_sheet(tableData.value); // 将表格数据转为工作表
    // const wb = XLSX.utils.book_new(); // 创建一个新的工作簿
    // XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 将工作表添加到工作簿
    // // 将工作簿转换为二进制的 XLSX 文件数据
    // const xlsxData = XLSX.write(wb, { bookType: "xlsx", type: "array" });

    // // 创建一个 Blob 对象，指定 MIME 类型为 XLSX 格式
    // const blob = new Blob([xlsxData], {
    //   type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    // });

    // // 创建一个文件对象
    // const file = new File([blob], "tableData.xlsx", {
    //   type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    // });

    // 将生成的文件添加到 FormData 中
    formData.append("file", fileDocument.value);

    // 获取文件并执行上传
    const fileToSend = formData.get("file");
    // 调用 API 上传文件
    const { data } = await postImportAssessmentTemplate({
      file: fileToSend,
      type: route.query.assessmentType,
      assessmentId: route.query.id
    });

    if (data.code === 200) {
      // 根据后端返回的 code 判断是否成功
      ElMessage.success("导入成功");
      // 重置上传状态
      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();
};
const backupUrl1 =
  import.meta.env.VITE_BACKUP_URL + "/考核数据导入模板-人员.xlsx";
const backupUrl2 =
  import.meta.env.VITE_BACKUP_URL + "/考核数据导入模板-部门.xlsx";
const backupUrl3 =
  import.meta.env.VITE_BACKUP_URL + "/考核数据导入模板-用户组.xlsx";
</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"
          ><el-icon> <Download /> </el-icon
          ><a
            v-if="query.assessmentType == 0 || query.assessmentType == 3"
            :href="backupUrl1"
            download="考核数据导入模板-人员.xlsx"
            >下载空的模板表格</a
          >
          <a
            v-if="query.assessmentType == 1"
            :href="backupUrl2"
            download="考核数据导入模板-部门.xlsx"
            >下载空的模板表格</a
          >
          <a
            v-if="query.assessmentType == 2"
            :href="backupUrl3"
            download="考核数据导入模板-用户组.xlsx"
            >下载空的模板表格</a
          ></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="#"
            :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
            v-if="query.assessmentType == 0 || query.assessmentType == 3"
            :data="tableData"
            border
            style="width: 100%"
            max-height="250"
          >
            <el-table-column fixed label="工号" prop="hospitalCode" />
            <el-table-column label="人员" prop="realName" />
            <el-table-column label="考核模板" prop="tpName" width="120" />
            <el-table-column label="指标名称" prop="quotaName" width="120" />
            <el-table-column label="完成值" prop="finalValue" width="120" />
            <el-table-column label="得分" prop="score" width="120" />
            <el-table-column label="目标值" prop="targetValue" width="120" />
            <el-table-column label="上期完成值" prop="upperValue" width="120" />
            <el-table-column
              label="上上期完成值"
              prop="agupperValue"
              width="120"
            />
            <el-table-column label="增幅" prop="addValue" width="120" />
            <el-table-column label="降幅" prop="decValue" width="120" />
            <el-table-column label="门槛值" prop="startValue" width="120" />
            <el-table-column label="挑战值" prop="challengeValue" width="120" />
          </el-table>
          <el-table
            v-if="query.assessmentType == 1"
            :data="tableData"
            border
            style="width: 100%"
            max-height="250"
          >
            <el-table-column fixed label="部门" prop="deptName" />
            <el-table-column label="部门编号" prop="hospitalCode" />
            <el-table-column label="考核模板" prop="tpName" />
            <el-table-column label="指标名称" prop="quotaName" />
            <el-table-column label="完成值" prop="finalValue" />
            <el-table-column label="得分" prop="score" />
            <el-table-column label="目标值" prop="targetValue" />
            <el-table-column label="上期完成值" prop="upperValue" />
            <el-table-column label="上上期完成值" prop="agupperValue" />
            <el-table-column label="增幅" prop="addValue" />
            <el-table-column label="降幅" prop="decValue" />
            <el-table-column label="门槛值" prop="startValue" />
            <el-table-column label="挑战值" prop="challengeValue" />
          </el-table>
          <el-table
            v-if="query.assessmentType == 2"
            :data="tableData"
            border
            style="width: 100%"
            max-height="250"
          >
            <el-table-column fixed label="用户组" prop="groupName" />
            <el-table-column label="用户组编号" prop="hospitalCode" />
            <el-table-column label="考核模板" prop="tpName" />
            <el-table-column label="指标名称" prop="quotaName" />
            <el-table-column label="完成值" prop="finalValue" width="120" />
            <el-table-column label="得分" prop="score" />
            <el-table-column label="目标值" prop="targetValue" />
            <el-table-column label="上期完成值" prop="upperValue" />
            <el-table-column label="上上期完成值" prop="agupperValue" />
            <el-table-column label="增幅" prop="addValue" />
            <el-table-column label="降幅" prop="decValue" />
            <el-table-column label="门槛值" prop="startValue" />
            <el-table-column label="挑战值" prop="challengeValue" />
          </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>
