<template>
  <el-upload
    class="upload-demo"
    :action="action"
    :on-remove="handleRemove"
    :on-success="handleUploadSuccess"
    :headers="headers"
    :before-remove="beforeRemove"
    :file-list="fileTmpList"
  >
    <el-button
      size="small"
      type="primary"
    >点击上传</el-button>
    <div
      slot="tip"
      class="el-upload__tip"
    >{{ tip }}</div>
  </el-upload>
</template>

<script>
import uploadAPI from '@/api/uploadAPI'
import { getToken } from '@/utils/auth'

export default {
  name: 'FileUpload',
  computed: {
    fileTmpList: function () {
      // console.log(this.fileList);
      let tmpList = []
      for (var i = 0; i < this.fileList.length; i++) {
        let tmp = this.fileList[i]
        tmp.name = tmp.fileName
        tmpList.push(tmp)
      }
      return this.fileList
    }
  },
  props: {
    fileList: {
      type: Array,
      default: function () {
        return []
      }
    },
    tip: {
      type: String,
      default: ''
    },
    handleUploadSuccess: {
      type: Function,
      default: function (res, file) {
        this.fileList.push(res.data)
      }
    },

    handleRemove: {
      type: Function,
      default: function (file, fileList) {
        // console.log(file);
        for (var i = 0; i < this.fileList.length; i++) {
          let tmp = this.fileList[i]
          if (tmp.fileID === file.fileID) {
            this.fileList.splice(i, 1)
            return
          }
        }
      }
    }

  },
  data () {
    return {
      action: uploadAPI.uploadUrl,
      headers: {
        'X-TOKEN': getToken()
      }
    }
  },
  methods: {
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    }
  }
}
</script>

<style scoped>

</style>
