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

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

export default {
  name: 'Upload',
  props: { value: String },
  data() {
    return { fileList: [] }
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        this.fileList = value ? [{ url: value }] : []
      }
    }
  },
  methods: {
    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.$emit('input', response.url)
          } else {
            file.status = 'failed'
            file.message = '上传失败'
          }
        })
        .catch(() => {
          file.status = 'failed'
          file.message = '上传失败'
        })
    },
    onDelete() {
      this.$emit('input', '')
    }
  }
}
</script>

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