<template>
  <div class="multi-file-upload">
    <el-upload
      class="upload-demo"
      :action="uploadFileUrl"
      multiple
      :on-change="handleChange"
      :on-success="handleSuccess"
      :headers="headers"
      :data="{ customPath: customPath }"
      :file-list="fileList"
      :before-upload="beforeUpload"
    >
    <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <el-message
      v-if="errorTip"
      type="error"
      :show-close="true"
    >
      文件后缀不正确，请上传[bmp, gif, jpg, jpeg, png, doc, docx, xls, xlsx, ppt, pptx, html, htm, txt, csv, rar, zip, gz, bz2, mp4, avi, rmvb, pdf]格式
    </el-message>
  </div>
</template>

<script>
import { getToken, Message } from '@/utils/auth' // 假设你用了Element的Message组件

export default {
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/customUpload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      errorTip: false // 错误提示状态
    };
  },
  props: {
    customPath: {
      type: String,
      default: 'E:\\home',
    },
  },
  methods: {
    // 新增文件上传前校验
    beforeUpload(file) {
      const allowedSuffix = ['bmp', 'gif', 'jpg', 'jpeg', 'png',
        'doc', 'docx', 'xls', 'xlsx', 'ppt',
        'pptx', 'html', 'htm', 'txt', 'csv',
        'rar', 'zip', 'gz', 'bz2', 'mp4',
        'avi', 'rmvb', 'pdf','mat'];

      const fileName = file.name.toLowerCase(); // 转小写避免大小写问题
      const fileSuffix = fileName.split('.').pop(); // 获取后缀名

      if (!allowedSuffix.includes(fileSuffix)) {
        this.errorTip = true;
        setTimeout(() => this.errorTip = false, 3000); // 3秒后隐藏提示
        Message.error('文件后缀不正确，请检查文件类型'); // 弹出错误提示
        return false; // 阻止上传
      }
      return true; // 允许上传
    },

    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3); // 保持最多3个文件
    },

    handleSuccess(response, file, fileList) {
      this.$emit('upload-success', response);
      console.log('上传成功数据传递给父组件:', response);
    }
  }
}
</script>
