<!-- 附件上传 -->
<template>
    <el-upload  ref="fileUpload" multiple 
              accept=".xlsx, .xls, .doc, .docx, .ppt, .pptx, .pdf, .txt, .png, .jpg, .jpeg"
              :headers="upload.headers"
              :action="upload.url" 
              :limit="upload.limit"
              :before-upload="handleBeforeUpload"
              :on-progress="fileFileUploadProgress"
              :on-success="fileFileSuccess"
               :on-error="handleUploadError"
              :on-exceed="fileExceed" 
              :auto-upload="true" 
              :file-list.sync="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传"doc","docx", "xls","xlsx", "ppt", "pptx", "txt", "pdf", "png","jpeg","jpg"文件，最多10个文件，且每个不超过10M</div>
              <template #file="{ file }">
          <div style="display: flex; justify-content: space-between; align-items: center; padding-right: 10px;">
            <el-link  @click="handleDownload(file)" :underline="false" type="info" >
              {{ file.name }}
            </el-link>
            <div style="cursor: pointer;" @click="handleRemove(file)"> 
              <i class="el-icon-close"></i> 
            </div>
          </div>
        </template>   
    </el-upload>
</template>

<script>
  import { getToken } from "@/utils/auth";
  export default {
    name: "commonUpload",
    props: {
        fileList: {
            type: Array, 
        }, 
    },
    data() {
      return {
        // 附件上传
        upload: {  
          // 是否禁用上传
          isUploading: false, 
          fileType: ["doc","docx", "xls","xlsx", "ppt", "pptx", "txt", "pdf", "png","jpeg","jpg"],
          limit: 10,
          maxSize: 10, // 附件大小10M
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/busUploadFiles"
        }, 
      }
    },  
    methods: {
       // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.upload.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1].toLowerCase();
        const isTypeOk = this.upload.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.upload.maxSize) {
        const isLt = file.size / 1024 / 1024 < this.upload.maxSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.upload.maxSize} MB!`);
          return false;
        }
      }
      this.number++;
      return true;
    },

      // 附件上传
      fileExceed() {
        this.$modal.msgError(`上传文件数量不能超过 ${this.upload.limit} 个!`);
      },
      // 文件上传中处理
      fileFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true; 
      },
      // 上传失败
      handleUploadError(err) {
        this.upload.isUploading = false;  
        this.$modal.msgError("上传文件失败，请重试");
        this.$modal.closeLoading();
      },
      // 文件上传成功处理
      fileFileSuccess(response, file, fileList) {
        this.upload.isUploading = false;  
        if (response.code != 200) { 
          this.$modal.msgError(response.msg);
          this.$refs.fileUpload.handleRemove(file); 
        }  
      },

      //删除
      handleRemove(file) {
          let uploadList = this.$refs.fileUpload.uploadFiles; 
          let index = uploadList.indexOf(file);
          uploadList.splice(index, 1); 
      },

      // 提交表单时，获取附件列表
      getFileList(){
        let uploadList = this.$refs.fileUpload.uploadFiles; 
        var files = [];
        for (let index = 0; index < uploadList.length; index++) {
               const f = uploadList[index];
              if(f.response){
                files.push({name: f.response.data[0].name, url:f.response.data[0].url, fileName: f.response.data[0].fileName});
              } else {
                files.push({name: f.name, url:f.url, fileName: f.fileName});
              }
        }
        return files;
      },
      // 清空上传文件
      clearFile(){
        this.$refs.fileUpload.clearFiles();
      },
      //下载
      handleDownload(file) {
          this.downFile(file.url, file.name)
      },
      downFile(url, linkDownload) {
          fetch(url)  //使用fetch函数发送一个GET请求到指定的URL，获取文件的响应对象。
              .then(response => response.blob())  //通过.then方法链，将响应对象转换为Blob数据（文件的二进制数据）。
              .then(blob => { //再次使用.then方法链，处理获取到的Blob数据。
                  const link = document.createElement('a'); //使用document.createElement创建一个<a>节点。
                  link.href = URL.createObjectURL(blob);  //通过URL.createObjectURL方法，将Blob数据转换成URL对象，然后将该URL赋值给link的href属性。这一步相当于生成了一个临时URL，供下载使用。
                  link.download = linkDownload; // 替换为你要保存的文件名和扩展名(设置用户下载文件时使用的文件名和扩展名)
                  link.click();   //调用click方法模拟用户点击链接，从而触发浏览器的文件下载行为。
                  URL.revokeObjectURL(link.href); // 释放URL对象资源(使用URL.revokeObjectURL方法释放之前创建的URL对象资源，避免内存泄漏)
              })
              .catch(error => {
                  console.error('下载失败:', error);
              });
      },      

      //预览
      handlePreview(file) {
          this.dialogImageUrl = file.url;
          this.dialogVisible = true;
      },

    }
}
</script>