<template>
  <div class="upload-single">
    <el-upload
      :ref="refName"
      :name="aliasName"
      :show-file-list="showFileList"
      action=""
      :http-request="httpRequest"
      :on-change="onChange"
      v-bind="$attrs"
    >
      <el-button icon="el-icon-upload2">{{ btnText }}</el-button>
      <slot />
    </el-upload>
  </div>
</template>

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

let _uploadId_ = 0
export default {
  name: 'UploadFile',
  inheritAttrs: false,
  props: {
    btnText: {
      type: String,
      default: '上传'
    },
    fileType: {
      type: Number,
      default: -1
    },
    showFileList: {
      type: Boolean,
      default: false
    },
    uploadChange: {
      type: Function,
      default() {}
    }
  },
  data() {
    return {
      uploadedFile: null,
      refName: '_upload_ref_',
      aliasName: '_upload_name_'
    }
  },
  created() {
    this.initConfig()
  },
  methods: {
    initConfig() {
      if (this.$attrs.name) {
        this.aliasName = this.$attrs.name
      }
      this.refName += _uploadId_
      this.aliasName += _uploadId_
      _uploadId_++
    },
    onChange(file, fileList) {
      if (file.status === 'ready') {
        fileList.splice(0, fileList.length - 1)
      }
      this.uploadChange && this.uploadChange(file)
    },
    submit() {
      this.$refs[this.refName].submit()
    },
    httpRequest(options) {
      const formData = new FormData()
      formData.append('file', options.file)
      uploadFile(this.fileType, formData).then(res => {
        if (options.onSuccess) {
          options.onSuccess(res.data)
        } else {
          console.log(res.data)
        }
      }).catch(error => {
        console.log(error)
        options.onError(error)
      })
    }
  }
}
</script>

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