<!-- 附件上传 -->
<template>
  <div class="flex-div uploaditem">
    <el-tooltip class="item" effect="dark" :content="tag.name" placement="top-start" v-for="(tag,index) in fileList" :key="index">
      <el-tag style="margin-right:10px;" :disable-transitions="false" @close="handleClose(index)" :closable="!disabled" @click="downloadFile(tag)"><i class="el-icon-paperclip"></i><span class="tagtext">{{tag.name}}</span></el-tag>
    </el-tooltip>
    <el-upload class="upload-demo" v-if="!isAddSp" action :http-request="uploadFile" :show-file-list="false" :headers="headers">
      <!-- action="/api/file/fileUpload" -->
      <div style="text-align: left;">
        <el-button class="btn" size="small" :disabled="disabled"><i class="el-icon-paperclip"></i>上传附件</el-button>
        <div v-if="!disabled">仅支持上传：pdf、word、excel、jpg、png、jpeg格式文件</div>
      </div>
    </el-upload>
    <!-- 文件在线预览 -->
    <FilePreview :previewFile="previewFile" :mode="mode" :fileUrl="fileUrl" @update="handleFileClose" />
    <!-- 图片类型预览 -->
    <el-image-viewer v-if="showViewer" :on-close="()=>{  showViewer = false }" :url-list="[fileUrl]" />
  </div>
</template>

<script>
import { uploadFileApi } from "@/api/common"
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import axios from 'axios'
export default {
  name: '',
  props: {
    files: Array,
    isAddSp: Boolean,
    propDisabled: {
      type: Boolean,
      default: () => {
        return true
      }
    }
  },
  computed: {
    disabled() {
      return !['add', 'edit'].includes(this.$route.query.flag) && this.propDisabled
    }
  },
  components: {
    FilePreview: () => import('@/components/FilePreview'),
    ElImageViewer,
  },
  watch: {
    files: {
      handler(list) {
        if (list && list.length) {
          this.fileList = list
        }
      },
      deep: true,
      immediate: true
    },
  },
  data() {
    return {
      fileUrl: null,
      showViewer: false,
      previewFile: false,
      mode: null,
      fileList: [],
      // 允许的文件类型
      fileType: ["pdf", "doc", "docx", "xls", "xlsx", "txt", "png", "jpg", "bmp", "jpeg"],
      // 运行上传文件大小，单位 M
      fileSize: 50,
      // 附件数量限制
      fileLimit: 5,
      //请求头
      headers: { "Content-Type": "multipart/form-data" },
      fileflag: false,
    }
  },
  methods: {
    handleFileClose() {
      this.previewFile = false
    },
    downloadFile(obj) {
      console.log('sss', this.isAddSp, obj);
      if (this.isAddSp) {
        const { url } = obj
        if (!url) return
        this.$modal.loading("正在下载附件，请稍候...");
        axios({
          url: url,
          method: 'GET',
          responseType: 'blob'
        }).then(response => {
          this.$modal.closeLoading();
          const blob = new Blob([response.data]);
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.setAttribute('download', 'file');  // 设置下载文件的文件名
          link.style.display = 'none';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        });
      } else {
        this.fileUrl = obj.url
        if (this.fileUrl.indexOf('png') > -1 || this.fileUrl.indexOf('jpg') > -1 || this.fileUrl.indexOf('jpeg') > -1) {
          this.showViewer = true
        } else {
          this.previewFile = true
        }
      }
    },
    //上传文件的事件
    uploadFile(item) {
      //上传文件的需要formdata类型;所以要转
      let FormDatas = new FormData()
      FormDatas.append('file', item.file);
      FormDatas.append('path', item.file.name);
      // 获取文件的后缀名
      const extension = item.file.name.split('.').pop().toLowerCase();

      // 允许的文件格式数组
      const allowedExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'jpg', 'png', 'jpeg'];

      // 检查文件格式是否符合要求
      if (allowedExtensions.indexOf(extension) === -1) {
        this.$modal.msgWarning(`只允许上传PDF、Word、Excel、JPG、PNG和JPEG格式的文件!`);
        return
      }
      this.$modal.loading("正在上传，请稍候...");
      uploadFileApi(FormDatas).then((res) => {
        this.fileList.push({ name: item.file.name, url: res.data });//成功过后手动将文件添加到展示列表里
        this.$emit('onUploadFile', this.fileList)
        this.$modal.closeLoading()
      })
    },
    //上传了的文件给移除的事件，由于我没有用到默认的展示，所以没有用到
    handleRemove() {
    },
    //这是我自定义的移除事件
    handleClose(i) {
      if (this.disabled) {
        return
      }
      this.fileList.splice(i, 1);//删除上传的文件
      this.$emit('onUploadFile', this.fileList)
    },
  }
}

</script>
<style lang='scss' scoped>
</style>