<template>
  <el-upload
    class="ps-upload-image"
    :action="action"
    :limit="limit"
    list-type="picture-card"
    :headers="headers"
    :on-exceed="handleExceed"
    :on-success="handleSuccess"
    :on-error="handleError"
    :file-list="fileList"
    :on-progress="handleProgress"
    :on-remove="handleRemove"
    :before-upload="handleBeforeUpload"
    :style="`width: ${this.showWidth}`"
  >
    <i class="el-icon-plus"></i>
    <div
      class="el-upload__tip"
      slot="tip"
      v-if="isTip"
    >{{showFileType}}大小不超过{{this.fileSize}}M，最多可上传{{this.limit}}张</div>
  </el-upload>
</template>

<script>
export default {
  name: 'PsUploadFile',
  props: {
    limit: {
      type: Number,
      default: 6
    },
    fileSize: {
      type: Number,
      default: 50
    },
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg']
    },
    action: {
      type: String,
      default: ''
    },
    headers: {
      type: Object,
      default: () => {}
    },
    width: {
      type: [Number, String],
      default: 380
    },
    successCode: {
      type: String,
      default: '0000'
    },
    fileList: {
      type: Array,
      default: () => []
    },
    isTip: {
      type: Boolean,
      default: true
    }
  },

  computed: {
    // 宽度
    showWidth() {
      if (typeof this.width === 'number') {
        return `${this.width}px`
      }
      return this.width
    },
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize)
    },
    // 显示可上传的文件类型
    showFileType() {
      return this.fileType.length ? `支持${this.fileType.join('、')}格式，` : ''
    },
    currentFileList: {
      get: function () {
        return this.fileList
      },
      set: function () {}
    }
  },

  methods: {
    handleRemove(file, fileList) {
      this.$emit('remove', file, fileList)
    },
    handleSuccess(res, file, fileList) {
      if (res.code === this.successCode) {
        this.$emit('success', res.data, file, fileList)
      } else {
        this.currentFileList = fileList.findIndex(item => item.uid !== file.uid)
        if (res.msg) {
          this.showErrorMsg(res.msg)
        } else {
          this.showErrorMsg('上传失败')
        }
        this.$emit('error', res, file, this.currentFileList)
      }
    },

    handleError(err, file, fileList) {
      this.$emit('onError', err, file, fileList)
    },
    // 触发上传中
    handleProgress(event, file, fileList) {
      this.$emit('onProgress', file, fileList)
    },
    // 显示错误信息
    showErrorMsg(msg) {
      this.$message.error(msg)
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType && this.fileType.length) {
        // 获取文件后缀
        let fileExtension
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.substring(file.name.lastIndexOf('.') + 1)
        }
        const isTypeOk = this.fileType.some(type => {
          return type === fileExtension
        })
        if (!isTypeOk) {
          this.showErrorMsg(`图片格式不正确，请上传${this.fileType.join('/')}格式图片！`)
          return false
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        // KB
        const fileSize = file.size / 1024 / 1024
        const isLt = fileSize < this.fileSize
        if (!isLt) {
          this.showErrorMsg(`上传图片大小不能超过 ${this.fileSize} M!`)
          return false
        }
      }
      this.$emit('beforeUpload', file)
      return true
    },

    // 文件个数超出限制
    handleExceed() {
      this.showErrorMsg(`上传文件数量不能超过 ${this.limit} 个!`)
    }
  }
}
</script>

<style>
.ps-upload-image .el-upload-list--picture-card .el-progress {
  display: none;
}
</style>
