<template>
  <van-uploader
    v-model="fileList"
    upload-icon="plus"
    :after-read="afterRead"
    :max-size="MaxSize"
    @delete="onDelete"
    @oversize="oversize"
    v-bind="$attrs"
  >
    <div class="van-uploader__upload">
      <i class="van-icon van-icon-plus van-uploader__upload-icon"></i>
      <p class="placeholder" v-if="$attrs.placeholder">{{ $attrs.placeholder }}</p>
    </div>
  </van-uploader>
</template>

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

export default {
  name: 'Upload',
  // 最大3M
  props: { value: String, MaxSize: { type: Number, default: 3 * 1024 * 1024 } },
  data() {
    return { fileList: [] }
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        this.fileList = value ? [{ url: value }] : []
      }
    }
  },
  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.$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>
.van-uploader {
  display: block;
  width: 100%;
}
.placeholder {
  margin-top: 10px;
  color: #c9c9c9;
}
::v-deep .van-uploader__input-wrapper,
::v-deep .van-uploader__preview {
  width: 100%;
}
::v-deep .van-uploader__upload,
::v-deep .van-uploader__preview-image {
  width: 100%;
  height: 100%;
  background-color: #eaeef0;
  border-radius: 0;
}
::v-deep .van-uploader__upload-icon {
  font-size: 40px;
  color: #dcdcdc;
}
::v-deep .van-cell{
  width: auto !important;
}
</style>
