<template>
  <div>
    <file-pond
      ref="pond"
      name="file"
      label-idle="选择图片或拖动图片到此处"
      label-file-processing="图片正在上传，请稍后"
      label-file-processing-aborted="图片上传被取消"
      label-tap-to-retry="尝试重试"
      label-file-processing-complete="图片上传成功！"
      label-max-file-size="上传的图片大小不能超过 10MB"
      label-max-file-size-exceeded="上传的图片大小不能超过 10MB"
      allow-file-size-validation="true"
      max-file-size="10MB"
      accepted-file-types="image/png, image/jpeg, image/jpg, image/gif"
      :allow-multiple="true"
      :max-files="12"
      :server="server"
      :instant-upload="true"
      @init="handleFilePondInit"
      @processfile="success"
      @removefile="removeFile"
    />
  </div>
</template>

<script>
import VueFilePond from 'vue-filepond'
import 'filepond/dist/filepond.min.css'
import FilePondPluginImagePreview from 'filepond-plugin-image-preview'
import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css'
import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type'
import FilePondPluginFileValidateSize from 'filepond-plugin-file-validate-size'

// Create component
const FilePond = VueFilePond(
  FilePondPluginFileValidateType,
  FilePondPluginImagePreview,
  FilePondPluginFileValidateSize
)
var resp = ''

export default {
  name: 'FilePondImage',
  components: {
    FilePond
  },
  resp,
  data() {
    return {
      imgMap: {},
      server: {
        url: '//api.reghao.cn/api/file/upload/image',
        revert: null,
        process: {
          headers: {
            'Authorization': this.$store.getters.token
          },
          ondata(formData) {
            return formData
          },
          onload(response) {
            resp = JSON.parse(response)
          }
        }
      }
    }
  },
  created() {
  },
  methods: {
    handleFilePondInit() {
      // FilePond instance methods are available on `this.$refs.pond`
    },
    success(error, metadata) {
      if (error === null) {
        const file = metadata.file
        const filename = file.name
        this.imgMap[filename] = resp.data.uploadId
      }
      this.$emit('resp', resp)
    },
    removeFile(error, metadata) {
      if (error === null) {
        const file = metadata.file
        const uploadId = this.imgMap[file.name]
        fetch('//file.reghao.cn/api/file/rm/' + uploadId, {
          headers: {
            'Authorization': this.$store.getters.token
          },
          method: 'DELETE'
        }).then(response => response.json())
          .then(json => {
            console.log(json)
          })
          .catch(e => {
            return null
          })
      }
    }
  }
}
</script>
