<template>
  <ele-image-upload
    v-model="images"
    :limit="9"
    :drag="true"
    :multiple="true"
    :upload-handler="uploadHandler"
    :beforeUpload="beforeUpload"
    @upload="onUpload"
    :remove-handler="removeHandler"
  >
  </ele-image-upload>
</template>

<script>
  import EleImageUpload from 'ele-admin/es/ele-image-upload';
  import { uploadFile } from '@/api/system/file/index';

  export default {
    components: { EleImageUpload },
    props: {
      // 所属模块
      module: {
        type: String,
        default: 'main'
      },
      // 限制数量
      limit: {
        type: Number,
        default: -1
      },
      value: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        images: []
      };
    },

    methods: {
      beforeUpload() {},
      /* 上传事件 */
      async uploadHandler(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 > 2) {
        //   this.$message.error('大小不能超过 2MB');
        //   return;
        // }
        await this.onUpload(item);
        this.$emit('input', [...this.images]);
      },
      removeHandler(item) {
        // item 即点击删除对应的 item 数据
        console.log('item:', item);
        // 这里你可以弹可询问弹窗, 需要删除数据可以这样写:
        this.images = this.images.filter((d) => d.id !== item.id);
        this.$emit('input', [...this.images]);

      },
      /* 上传 item */
      async onUpload(item) {
        // 模拟上传
        item.status = 'uploading';
        item.progress = 20;

        const res = await uploadFile({
          module: this.module,
          multiPartFile: item.file
        });
        if (res.data) {
          item.url = res.data.url;
          item.id = res.data.id;
          item.progress = 100;
          item.status = 'done';
          this.images.push(item);
        }
      },

      putValue(item) {
        if (item) {
          this.images = item;
        } else {
          this.images = [];
        }
      }
    }
  };
</script>
