<template>
  <el-upload
    class="upload-demo"
    :action="uploadUrl"
    :before-upload="beforeHandle"
    :on-preview="previewHandle"
    :on-remove="removeHandle"
    :headers="{ token: token }"
    :limit="5"
    multiple
    :on-success="successHandle"
    :file-list="fileList">
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传5个文件，且不超过100M</div>
  </el-upload>
</template>

<script>
import { Auth } from '@/util/auth'
export default {
  data() {
    return {
      uploadUrl: '/mdxtpt/teamwork/api/team/base/uploadImage',
      fileList: [],
      token: Auth.getLoginInfo(),
    }
  },
  props: {
    setFileList: {
      type: Array,
      default: null
    }
  },
  watch:{
    setFileList: function(val) {
      this.fileList = val || []
    }
  },
  methods: {
    beforeHandle(file) {
      const isLt500M = file.size / 1024 / 1024 < 500;
      if (!isLt500M) {
        this.$message.error('上传文件大小不能超过 500MB!');
      }
      return isLt500M
    },
    successHandle(res, file) {
      if (res.msg === 201 && file.name && file.response && file.response.respData) {
        this.fileList.push({
          name: file.name,
          url: file.response.respData
        })
      } else {
        this.$message.error(res.content)
      }
      console.log(file, this.fileList)
    },
    previewHandle(file) {
      var a = document.createElement('a')
      a.href = file.url
      a.download = file.name
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    removeHandle(file, fileList) {
      this.fileList = fileList
    },
    getFileList() {
      return this.fileList.map(item => {
        return {
          name: item.name,
          url: item.url
        }
      })
    }
  }
}
</script>

<style>

</style>