<script setup lang="ts">
defineOptions({
  name: "IndexDefineImport"
});
import { ref } from "vue";
import { uploadData } from "@/api/indexData";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { da } from "element-plus/es/locale/index.mjs";
const $router = useRouter();
const emit = defineEmits(["handleImport"]);
const fileDocument = ref<File | null>(null); // 存储文件
const backupUrl = import.meta.env.VITE_BACKUP_URL + "/指标数据模板.xlsx";
// 上传文件函数
// 上传文件函数
const uploadFile = async () => {
  if (!fileDocument.value) {
    ElMessage.error("请先上传文件");
    return;
  }

  const formData = new FormData();
  // 将生成的文件添加到 FormData 中
  formData.append("file", fileDocument.value);
  // 调用 API 上传文件
  const { data } = await uploadData(formData);
  if (data.code === 200) {
    // 根据后端返回的 code 判断是否成功
    ElMessage.success("文件上传并导入成功");
    // 重置上传状态
    backDefine("success");
  } else {
    ElMessage.error(data.msg);
  }
};

const backDefine = (type = "") => {
  emit("handleImport", type);
};

// 处理文件上传并解析 Excel 内容
const handleUploadChange = async (file: File) => {
  fileDocument.value = file; // 保存文件
  let fileType = file.name.slice(-4);
  if (fileType !== "xlsx") {
    ElMessage.error("请上传xlsx文件");
  }
  return false;
};
</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 :href="backupUrl" 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>
          <el-upload
            class="upload-demo"
            drag
            multiple
            :before-upload="file => handleUploadChange(file)"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              点击<em>图标选择上传</em>或者将文件拖拽到此区域
            </div>
          </el-upload>
          <div v-if="fileDocument && fileDocument.name">
            {{ fileDocument.name }}
          </div>
        </div>
        <div class="float-right">
          <el-button @click="backDefine('close')">取消</el-button>
          <el-button type="primary" @click="uploadFile">确认</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;
}

.float-right {
  margin-top: 10px;
}
</style>
