<template>
  <div class="UploadFile-container">
    <el-upload :action="define.comUploadUrl+'/'+type" :headers="uploadHeaders"
      :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove"
      :on-success="handleSuccess" :file-list="fileList" :accept="accept"
      :http-request="customUpload">
      <el-button size="small" icon="el-icon-upload">选择文件</el-button>
    </el-upload>
  </div>
</template>

<script>
import { getDownloadUrl } from '@/api/common'
import { ossUploadFile } from '@/utils/oss-upload'
export default {
  name: 'UploadFileSingle',
  props: {
    value: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'workFlow'
    },
    accept: {
      type: String,
      default: '*'
    }
  },
  data() {
    return {
      fileList: [],
      uploadHeaders: { Authorization: this.$store.getters.token }
    }
  },
  watch: {
    value(val) { if (!val) this.fileList = [] }
  },
  methods: {
    customUpload(options) {
      var file = options.file
      if (this.type === 'annexpic' || this.type === 'attendancepic') {
        ossUploadFile(file, this.type).then(data => {
          this.fileList = [{ name: file.name, url: '' }]
          this.$emit('input', data.name)
        }).catch(() => {
          this.$message({ message: '上传失败，请重试', type: 'error', duration: 1500 })
        })
      } else {
        var formData = new FormData()
        formData.append('file', file)
        var xhr = new XMLHttpRequest()
        xhr.open('POST', this.define.comUploadUrl + '/' + this.type, true)
        xhr.setRequestHeader('Authorization', this.$store.getters.token)
        xhr.onload = () => {
          if (xhr.status === 200) {
            var res = JSON.parse(xhr.responseText)
            this.handleSuccess(res, { name: file.name, uid: Date.now() }, this.fileList)
          }
        }
        xhr.send(formData)
      }
    },
    handlePreview(file) {
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.$emit('input', '')
    },
    handleSuccess(res, file, fileList) {
      if (res.code == 200) {
        this.fileList = [{ name: file.name, url: '' }]
        this.$emit('input', res.data.name)
      } else {
        this.fileList = fileList.filter(o => o.uid != file.uid)
        this.$message({ message: res.msg, type: 'error', duration: 1500 })
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).catch(() => { });
    }
  }
}
</script>