<template>
  <van-uploader v-model="arrUploadFile"
                :max-count="maxCount"
                :before-read="beforeRead"
                :after-read="afterRead" @delete="handleDelete"/>
</template>

<script>
  import { Uploader, Toast } from 'vant'
  import { uploadFile } from '../../../../api/common'
  import Compressor from 'compressorjs'

  export default {
    name: 'myUploader',
    components: {
      'van-uploader': Uploader
    },
    props: {
      maxCount: {
        type: Number,
        default: 1
      },
      uploadType: {
        type: String,
        default: 'credit'
      }
    },
    data () {
      return {
        Compressor: null,
        arrUploadFile: []
      }
    },
    methods: {
      handleDelete () {
        this.$emit('funSetUploadData', this.uploadType, this.arrUploadFile)
      },
      beforeRead (file) {
        const fileList = Array.isArray(file) ? file : [file]
        const fileType = fileList.every(item => /^image\//.test(item.type) || /(\.png|\.jpeg|\.gif|\.jpg)$/.test(item.name))
        if (!fileType) {
          Toast('只能选择图片')
          return false
        }
        return true
      },
      afterRead (file) {
        const fileList = Array.isArray(file) ? file : [file]
        fileList.forEach(item => {
          item.status = 'uploading'
          item.message = '上传中...'
        })
        const result = fileList.map(async item => {
          const maxSize = 2 * 1024 * 1024
          const compressResult = item.file.size > maxSize ? await this.funCompressor(item.file) : item.file
          return this.funUploadImg(compressResult)
        })
        Promise.all(result).then(res => {
          res.forEach((item, index) => {
            if (item.filePath && item.filePath.startsWith('http')) {
              fileList[index].url = item.filePath
            }
            fileList[index].status = ''
            fileList[index].message = ''
            this.$emit('funSetUploadData', this.uploadType, this.arrUploadFile)
          })
        }).catch(err => {
          fileList.forEach(item => {
            item.status = 'failed'
            item.message = err
          })
        })
      },
      funCompressor (file) {
        return new Promise((resolve, reject) => {
          this.Compressor = new Compressor(file, {
            quality: 0.6,
            success (result) {
              resolve(result)
            },
            error (err) {
              try {
                reject(err)
              } catch (e) {
              }
            }
          })
        })
      },
      funUploadImg (file) {
        return new Promise((resolve, reject) => {
          const formData = new FormData()
          formData.append('file', file, file.name)
          formData.append('type', 'img')
          uploadFile(formData).then(res => {
            resolve(res.data)
          }).catch(err => {
            reject(err)
          })
        })
      }
    },
    beforeDestroy () {
      this.Compressor = null
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .van-uploader__upload {
    border: 1px dashed #CBB091;
    border-radius: 8px;
    background-color: transparent;
  }
</style>
