<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);
  console.log("111", query.value);
});
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;
    // 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[1].length == 6 &&
    //     (query.value.assessmentType == 0 || query.value.assessmentType == 1)
    //   ) {
    //     tableHeaders.value = jsonData[1];
    //     const arr = jsonData.slice(2).map(row => {
    //       if (row[0] && row[1] && row[2] && row[3]) {
    //         const rowData = {};
    //         tableHeaders.value.forEach((header, index) => {
    //           if (row[index]) {
    //             rowData[header] = row[index];
    //           }
    //         });
    //         return rowData;
    //       }
    //     });
    //     tableData.value = arr.filter(item => item);
    //     ElMessage.success("文件上传成功");
    //     uploadShow.value = false; // 隐藏上传区域，显示数据表
    //   } else if (query.value.assessmentType == 2) {
    //     tableHeaders.value = [
    //       "用户组",
    //       "用户组编号",
    //       "考核模板",
    //       "指标名称",
    //       "完成值",
    //       "得分"
    //     ]; // 表头
    //     const arr = jsonData.slice(2).map(row => {
    //       if (row[0] && row[1] && row[2] && row[3]) {
    //         const rowData = {};
    //         tableHeaders.value.forEach((header, index) => {
    //           if (row[index]) {
    //             rowData[header] = row[index];
    //           }
    //         });
    //         return rowData;
    //       }
    //     });
    //     tableData.value = arr.filter(item => item);
    //     ElMessage.success("文件上传成功");
    //     uploadShow.value = false; // 隐藏上传区域，显示数据表
    //   } else {
    //     ElMessage.error("文件为空或格式不正确");
    //   }
    // };
    console.log(data);
  } else {
    ElMessage.error(data.msg);
  }
  // } else {
  //   ElMessage.error("请上传xlsx文件");
  // }

  reader.readAsArrayBuffer(file); // 读取文件为 ArrayBuffer
};
// 上传
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(data.msg);
      // 重置上传状态
      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"
          ><el-icon> <Download /> </el-icon
          ><a
            v-if="query.assessmentType == 0 || query.assessmentType == 3"
            href="http://172.16.9.165:8765/download/考核数据导入模板-人员.xlsx"
            download="考核数据导入模板-人员.xlsx"
            >下载空的模板表格</a
          >
          <a
            v-if="query.assessmentType == 1"
            href="http://172.16.9.165:8765/download/考核数据导入模板-部门.xlsx"
            download="考核数据导入模板-部门.xlsx"
            >下载空的模板表格</a
          >
          <a
            v-if="query.assessmentType == 2"
            href="http://172.16.9.165:8765/download/考核数据导入模板-用户组.xlsx"
            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="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
            v-if="query.assessmentType == 0 || query.assessmentType == 3"
            :data="tableData"
            border
            style="width: 100%"
            max-height="250"
          >
            <el-table-column label="工号" prop="hospitalCode" />
            <el-table-column label="人员" prop="realName" />
            <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>
          <el-table
            v-if="query.assessmentType == 1"
            :data="tableData"
            border
            style="width: 100%"
            max-height="250"
          >
            <el-table-column 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>
          <el-table
            v-if="query.assessmentType == 2"
            :data="tableData"
            border
            style="width: 100%"
            max-height="250"
          >
            <el-table-column 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" />
            <el-table-column label="得分" prop="score" />
          </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>
