<template>
  <el-upload
    class="upload-demo"
    :action="action"
    :file-list="fileList"
    show-file-list
    drag
    multiple
    :limit="limit"
    :on-remove="handleRemove"
    :on-exceed="handleExceed"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <!-- <el-button size="small" type="primary">点击上传</el-button> -->
    <img
      v-if="imageUrl"
      :src="imageUrl"
      class="avatar"
    />
    <i
      v-else
      class="el-icon-plus avatar-uploader-icon"
    ></i>
  </el-upload>
</template>

<script>
export default {
  name: 'PsUpload',
  props: {
    limit: {
      type: Number,
      default: 30
    },
    fileSize: {
      type: Number,
      default: 500
    },
    fileType: {
      type: Array,
      default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf', 'png', 'jpg', 'jpeg']
    },
    isShowTip: {
      type: Boolean,
      default: true
    },
    action: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      imageUrl: '',
      fileList: [],
      notifyPromise: Promise.resolve()
    }
  },

  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize)
    }
  },

  created() {},

  mounted() {},

  methods: {
    handleRemove(file, fileList) {
      this.$emit('remove', fileList)
      console.log(file, fileList)
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.row)
      this.$emit('success', !this.imageUrl)
    },

    // 上传前校检格式和大小
    beforeAvatarUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        const isTypeOk = this.fileType.some(type => {
          return fileExtension && fileExtension.indexOf(type) > -1
        })
        if (!isTypeOk) {
          this.warningNotify(`文件格式不正确，请上传${this.fileType.join('/')}格式文件！`)
          return false
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        // KB
        const fileSize = file.size / 1024
        const isLt = fileSize < this.fileSize
        if (!isLt) {
          this.warningNotify(`上传文件大小不能超过 ${this.fileSize} KB!`)
          return false
        }
      }
      return true
    },

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

<style>
</style>
