<template>
  <van-uploader
    v-model="fileList"
    :after-read="afterRead"
    :max-size="maxSize"
    @oversize="oversize"
    @delete="onDelete"
    v-bind="$attrs"
  />
</template>

<script>
import { upload } from '@/api/index'

export default {
  name: 'UpliadMultiple',
  // 最大3M
  props: { value: {}, maxSize: { type: Number, default: 3 * 1024 * 1024 } },
  data() {
    return { fileList: [], urlList: [] }
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        if (!value) {
          this.fileList = []
        }
      }
    }
  },
  methods: {
    oversize(file) {
      const rawFile = file.file
      if (rawFile.size > this.maxSize) {
        this.$toast('文件大小不能超过3M')
      }
    },
    afterRead(file) {
      file.status = 'uploading'
      file.message = '上传中...'
      let formData = new FormData()
      formData.append('file', file.file)
      upload(formData)
        .then(response => {
          if (response.success) {
            file.status = 'done'
            this.urlList.push({
              name: file.file.name,
              url: response.url
            })
            this.$emit('input', this.urlList)
          } else {
            file.status = 'failed'
            file.message = '上传失败'
          }
        })
        .catch(() => {
          file.status = 'failed'
          file.message = '上传失败'
        })
    },
    onDelete(value) {
      this.urlList = this.urlList.filter(k => k.name !== value.file.name)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .van-uploader__upload,
::v-deep .van-uploader__preview-image {
  width: 100px;
  height: 100px;
  background-color: #eee;
  border-radius: 0;
}
::v-deep .van-uploader__upload-icon {
  color: #666;
}
</style>
