<template>
  <el-upload
    :action="uploadUrl"
    multiple
    :limit="limit"
    :on-success="handleUploadSuccess"
    :before-upload="handleBeforeUpload"
    :on-error="handleUploadError"
    :on-remove="handleUploadRemove"
    :on-preview="handleDownload"
    :on-exceed="handleUploadExceed"
    :before-remove="handleBeforeRemove"
    :file-list="fileList"
    :data="{ fileModule }"
    :headers="{ token }"
    :accept="accept"
    v-loading="loading"
  >
    <el-button slot="trigger" size="mini" type="primary"> 点击上传 </el-button>
    <div style="margin-top: 20px; line-height: 20px" slot="tip" class="el-upload__tip">
      <p v-if="whiteList.length > 0">只能上传 {{ whiteList.join(' / ') }} 文件</p>
      <p v-if="maxSize > 0">单个文件大小不超过 {{ maxSizeStr }}</p>
      <p v-if="limit > 0">文件总数不超过 {{ limit }} 个</p>
    </div>
  </el-upload>
</template>
<script>
import { getToken } from '@/utils/auth'
import { download } from '@/api/data'
import { downloadFile, formatSize } from '@/utils/index'

export default {
  name: 'UplaodAttachment',
  computed: {
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + '/file/uploadFile'
    },
    whiteList() {
      return this.accept ? this.accept.replace(/\./g, '').split(',') : []
    },
    maxSizeStr() {
      return formatSize(this.maxSize)
    },
    imgStyle() {
      return {
        height: this.previewHeight,
        width: this.previewWidth,
      }
    },
    errorStyle() {
      return {
        'line-height': this.previewHeight,
      }
    },
    fileList() {
      return this.value
        ? this.value.map((a) => {
            return { name: a.name, url: a.path }
          })
        : []
    },
  },
  props: {
    value: {
      type: Array,
      require: true,
      default: null,
    },
    maxSize: {
      type: Number,
      default: 0,
    },
    limit: {
      type: Number,
      default: 0,
    },
    accept: {
      type: String,
      default: '',
    },
    fileModule: {
      type: Number,
      default: 30,
    },
  },
  data() {
    return {
      token: getToken() ?? '',
      loading: false,
    }
  },
  methods: {
    handleBeforeUpload(file) {
      if (this.maxSize > 0) {
        if (file.size > this.maxSize) {
          this.$message.warning(
            `当前文件容量为${formatSize(file.size)} ，超出文件最大限制 ${this.maxSizeStr}`
          )
          return false
        }
      }
      if (this.whiteList.length > 0) {
        let fileName = file.name
        let fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
        let whiteListLowerCase = this.whiteList.map((a) => a.toLowerCase())
        if (!whiteListLowerCase.includes(fileExtension)) {
          this.$message.warning(
            `当前文件类型为 ${fileExtension} ，不是允许上传的文件类型，允许上传的文件类型为 ${this.whiteList.join(
              ' / '
            )}`
          )
          return false
        }
      }
      this.changeLoading(true)
    },
    handleUploadSuccess(res, file, fileList) {
      if (res.code === 20000) {
        let v = this.value ? this.value : []
        let files = v.concat(res.data)
        this.$emit('input', files)
      } else {
        this.$message.error(res.msg)
      }
      this.changeLoading(false)
    },
    handleUploadError(err, file, fileList) {
      console.log(err)
      this.$message.error('上传失败')
      this.changeLoading(false)
    },
    handleUploadRemove(file, fileList) {
      let files = this.value.filter((a) => a.path != file.url)
      this.$emit('input', files)
    },
    handleBeforeRemove(file, fileList) {
      if (file.status != 'success') return true
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleDownload(file) {
      this.changeLoading(true)
      download({ filePath: file.url })
        .then((res) => {
          downloadFile(res.data)
          this.changeLoading(false)
        })
        .catch((error) => {
          console.error(error)
          this.changeLoading(false)
        })
    },
    handleUploadExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
      this.changeLoading(false)
    },
    changeLoading(value) {
      this.loading = value
      this.$emit('update:loading', value)
    },
  },
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>