<template>
  <div class="clearfix">
    <a-upload
      :action="action"
      listType="picture-card"
      :fileList="fileList"
      @change="handleChange"
      :customRequest="customRequest"
      :remove="handleRemove"
      :beforeUpload="beforeUpload"
    >
      <div v-if="fileList.length < maxSize">
        <a-icon type="plus" />
        <div class="ant-upload-text">Upload</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel" :width="1200">
      <img style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import { uploadFileSpare } from '@/api/upms/file'
export default {
  name: 'UploadSpareImg',
  data () {
    return {
      previewVisible: false,
      action: '/upms/files/upload/spare',
      maxSize: 1,
      previewImage: '',
      fileList: []
    }
  },
  methods: {
    base (maxSize, fileList) {
      this.fileList = fileList
      this.maxSize = maxSize
    },
    handleCancel () {
      this.previewVisible = false
    },
    handlePreview (file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleChange ({ fileList }) {
      // this.fileList = fileList
      // this.$emit('catchImage', fileList)
    },
    async customRequest (data) {
      const formData = new FormData()
      formData.append('file', data.file)
      data.onProgress()
      const that = this
      uploadFileSpare(formData).then(res => {
        data.onSuccess()
        that.fileList.push({
          uid: '-1',
          name: res.data.fileName,
          status: 'done',
          url: this.BaseTool.Constant.FILE_URL + res.data.url
        })
        this.$emit('catchImage', that.fileList)
      })
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
      this.$emit('catchImage', this.fileList)
      return true
    },
    beforeUpload (file, fileList) {
    }
  }
}
</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>
