<template>
  <el-upload
    class="upload-file-container"
    action=""
    :http-request="uploadFile"
    :on-remove="onRemove"
    :before-upload="beforeUpload"
    :show-file-list="showFileList"
    :accept="acceptType"
  >
    <slot />
    <div slot="tip" class="el-upload__tip">
      <slot name="tip" />
    </div>
  </el-upload>
</template>

<script>
import { uploadSingle } from '@/api/components/file'

export default {
  name: 'UploadFile',
  props: {
    // eslint-disable-next-line vue/require-default-prop
    value: {
      type: [String, null],
      default: () => ''
    },
    accept: {
      type: String,
      default: () => 'image'
    },
    showFileList: {
      type: Boolean,
      default: () => true
    }
  },
  computed: {
    visible() {
      return this.value && this.value.length > 0
    },
    acceptType() {
      if (this.accept === 'image') return 'image/*'
      if (this.accept === 'pdf') return '.pdf'
      if (this.accept === 'word') return '.doc,.docx'
      return ''
    }
  },
  methods: {
    beforeUpload(file) {
      const arr = this.acceptType.split(',')
      // eslint-disable-next-line no-unused-vars
      let flag = false
      arr.forEach((v, i) => {
        flag = (i === 0 ? true : flag) && file.name.indexOf(v) === -1
      })
      if (flag) {
        this.$message.warning(`请上传 ${this.accept} 格式文件`)
        return false
      }
    },
    onRemove() {
      this.$emit('update:value', '')
    },
    reg(type) {
      return new RegExp(`^data:${type};base64,`)
    },
    uploadFile(http) {
      const reader = new FileReader()
      reader.readAsDataURL(http.file)
      reader.onload = e => {
        const result = e.target.result.replace(this.reg(http.file.type), '')
        const params = {
          fileType: this.accept,
          fileData: result,
          fileName: http.file.name
        }
        uploadSingle(params)
          .then(res => {
            const { data } = res
            this.$emit('update:value', data.url)
          })
          .catch(err => this.$message.error(err.message))
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .upload-file-container{
    display: inline-block;
  }
</style>
