<template>
  <div class="clearfix">
    <a-upload
      :action="action"
      :fileList="fileList"
      @change="handleChange"
      :customRequest="customRequest"
      :remove="handleRemove"
      :beforeUpload="beforeUpload"
    >
      <div v-if="fileList.length < maxSize">
        <a-icon type="upload" style="margin-left: 15px"/>
        <div class="ant-upload-text">上传文件</div>
      </div>
    </a-upload>
  </div>
</template>

<script>
import { uploadFile } from '@/api/upms/file'
export default {
  name: 'Upload',
  data () {
    return {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      action: process.env.VUE_APP_API_BASE_URL + '/upms/files/upload'
    }
  },
  props: {
    maxSize: {
      type: Number,
      default: 1
    }
  },
  methods: {
    base (fileList) {
      this.fileList = fileList
    },
    handleCancel () {
      this.previewVisible = false
    },
    handlePreview (file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleChange ({ fileList }) {
      // this.fileList = fileList
      // this.$emit('catchFile', fileList)
    },
    async customRequest (data) {
      const formData = new FormData()
      formData.append('file', data.file)
      data.onProgress()
      uploadFile(formData).then(res => {
        data.onSuccess()
        this.fileList.push({
          uid: '-1',
          name: res.data.name,
          status: 'done',
          url: this.BaseTool.Constant.FILE_URL + res.data.url
        })
        this.$emit('catchFile', this.fileList)
      })
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
      this.$emit('catchFile', this.fileList)
      return true
    },
    beforeUpload (file, fileList) {
      const reg = /\.(doc|docx|html|pdf|txt|mht|xlsx|xls|jpg|png|zip)(\?.*)?$/
      // if (this.fileType === 1) {
      //   reg = /\.(jpg|png|gif)(\?.*)?$/
      // }
      return new Promise((resolve, reject) => {
        if (reg.test(file.name)) {
          resolve()
        } else {
          this.$message.error(`请上传正确的文件格式`)
          reject(new Error('请上传正确的文件格式'))
        }
      })
    }
  }
}
</script>
<style>
  /* you can make up upload button and sample style by using stylesheets */
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
  .ant-upload-btn {
    margin-top: 20px;
  }
</style>
