<!-- 上传图片组件 -->
<template>
  <ele-image-upload
    v-model="imgs"
    :limit="limit"
    :drag="true"
    :multiple="multiple"
    :upload-handler="onHandler"
    @upload="onUpload"
  />
</template>

<script>
  import EleImageUpload from 'ele-admin/es/ele-image-upload';
  import request from '@/utils/request';
  export default {
    components: {
      EleImageUpload
    },
    name: 'UploadImg',
    props: {
      limit: {
        type: Number,
        default: 1
      },
      multiple: {
        type: Boolean,
        default: false
      },
      images: {
        default: null,
        type: Array
      }
    },
    data() {
      return {
        imgs: []
      };
    },
    mounted() {
      if (this.images && this.images.length > 0) {
        this.imgs = this.images;
      }
    },
    methods: {
      emitInput() {
        this.$emit('input', this.imgs);
      },
      onHandler(file) {
        const item = {
          file,
          uid: file.uid,
          name: file.name,
          progress: 0,
          status: null
        };
        if (!file.type.startsWith('image')) {
          this.$message.error('只能选择图片');
          return;
        }
        if (file.size / 1024 / 1024 > 10) {
          this.$message.error('大小不能超过 10MB');
          return;
        }
        item.url = window.URL.createObjectURL(file);
        // 关键就是这里要自己 push 添加数据而不是靠 v-modal 自动更新
        this.imgs.push(item);
        this.onUpload(item);
      },
      /* 上传 item */
      onUpload(item) {
        let that = this;
        item.status = 'uploading';
        const formData = new FormData();
        formData.append('file', item.file);
        request({
          url: '/upload',
          method: 'post',
          data: formData,
          onUploadProgress: (e) => {
            if (e.lengthComputable) {
              item.progress = (e.loaded / e.total) * 100;
            }
          }
        })
          .then((res) => {
            if (res.data.code === 0) {
              item.status = 'done';
              item.url = res.data.data.full_url;
              item.fileUrl = res.data.data.url;
              that.emitInput();
            }
          })
          .catch(() => {
            item.status = 'exception';
          });
      }
    },
    watch: {
      imgs: function () {
        this.emitInput();
      },
      images: function () {
        this.imgs = this.images;
      }
    }
  };
</script>
