<template>
  <div class="file-upload-container">
    <!-- 上传按钮 -->
    <div>
      <input
        type="file"
        ref="uploadInput"
        @change="handleFileChange"
        accept=".xlsx, .xls"
        class="custom-file-input"
      />
      <el-button size="small" :icon="icon" @click="triggerUpload">
        {{ uploadButtonText }}
      </el-button>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import { getToken } from "@/utils/auth";

export default {
  name: "FileUploader",
  props: {
    uploadUrl: {
      type: String,
      required: true, // 上传文件的 API 接口
    },
    downloadTemplateUrl: {
      type: String,
      required: false, // 模板下载 API（可选）
    },
    headers: {
      type: Object,
      default: () => ({
        Authorization: "Bearer " + getToken(),
      }),
    },
    uploadButtonText: {
      type: String,
      default: "导入", // 上传按钮的文本
    },
    downloadButtonText: {
      type: String,
      default: "下载模板", // 下载按钮的文本
    },
    showDownloadTemplate: {
      type: Boolean,
      default: true, // 是否显示模板下载按钮
    },
    icon: {
      type: String,
      default: 'el-icon-upload2'
    }
  },
  data() {
    return {
      selectedFile: null, // 用户选择的文件
      openvVsible: false,
      prompTotal: 0,
      errorFileBlob: null, // 错误文件的 Blob 数据
    };
  },
  methods: {
    formatter(row, column, cellValue) {
      return cellValue ? cellValue : "- - - -";

    },
    clocsePromp() {
      this.openvVsible = false;
    },

    // 触发文件选择框
    triggerUpload() {
      this.$refs.uploadInput.click();
    },

    // 处理文件选择
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        const isExcel =
          file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        if (!isExcel) {
          this.$modal.msgError("只能上传 Excel 文件！");
          this.$refs.uploadInput.value = null;
          return;
        }
        const isLt10M = file.size / 1024 / 1024 < 10; // 文件大小限制 10MB
        if (!isLt10M) {
          this.$modal.msgError("文件大小不能超过 10MB!");
          this.$refs.uploadInput.value = null;
          return;
        }

        // 设置选中的文件
        this.selectedFile = file;
        this.uploadFile();
        // this.$emit("refreshTable");
      }
    },

    // 上传文件到后端
    uploadFile() {
      if (!this.selectedFile) {
        this.$modal.msgError("请选择一个文件！");
        return;
      }

      const formData = new FormData();
      formData.append("file", this.selectedFile);

      request({
        url: this.uploadUrl,
        data: formData, 
        method: 'post',
        headers: {
          ...this.headers,
          "Content-Type": "multipart/form-data", // 必须设置为 multipart/form-data
        },
        responseType: "blob", // 确保返回的是文件流
      })
        .then((response) => {
          console.log(response);
          this.openvVsible = true;
          this.$emit("refreshTable");
        })
        .catch((error) => {
          console.error("文件上传失败", error);
          this.$emit("upload-error", error);
        })
        .finally(() => {
          // 重置文件输入框
          this.$refs.uploadInput.value = null;
          this.selectedFile = null;
          this.$emit("refreshTable");
        });
    },
  },
};
</script>

  
  
<style scoped lang="scss">
.custom-file-input {
  display: none;
  /* 隐藏原生文件选择框 */
}

::v-deep .el-button--small {
  padding: 7px 15px;
}

.prompTotal {
  width: 100%;
  text-align: center;
  .prompSure {
    display: inline-block;
    padding: 5px 15px;
    border-radius: 10px;
    color: white;
    margin-top: 50px;
  }
  .prompTotalNum {
    margin-top: 20px;
    color: #999;
    margin-bottom: 20px;
  }
  .prompTotalTitle {
    font-size: 20px;
    color: black;
  }
}
</style>
