<template>
  <div>
    <ele-image-upload v-model="images" @upload="onUpload" />
    <el-button @click="onSubmit">提交</el-button>
  </div>
</template>

<script>
  import EleImageUpload from 'ele-admin/es/ele-image-upload';
  // import { upload } from '@/api/test/upload';
  import request from '@/utils/request';
  //import { upload } from '@/api/test/upload';
  // import request from '@/utils/request';

  export default {
    components: { EleImageUpload },
    data() {
      return {
        images: []
      };
    },
    methods: {
      /* 上传事件 */
      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;
        }
        item.url = window.URL.createObjectURL(file);
        // 关键就是这里要自己 push 添加数据而不是靠 v-modal 自动更新
        this.images.push(item);
        this.onUpload(item);
      },
      /* 上传 item */
      onUpload(item) {
        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;
            }
          })
          .catch(() => {
            item.status = 'exception';
          });
      },
      // /* 上传 item */
      // onUpload(item) {
      //   const loading = this.$messageLoading('上传中..');
      //   const formData = new FormData();
      //   formData.append('file', item.file);
      //   upload(formData)
      //     .then((res) => {
      //       loading.close();
      //       console.log(res);
      //       if (res.data.code === 0) {
      //         item.status = 'done';
      //         item.url = res.data.data.full_url;
      //         item.fileUrl = res.data.data.url;
      //       } else {
      //         item.status = 'exception';
      //       }
      //       console.log(item);
      //       console.log('images');
      //       console.log(this.images);
      //     })
      //     .catch(() => {
      //       console.log(111);
      //       loading.close();
      //     });
      // },
      onSubmit() {
        //const urls = this.images.map(d => d.url);
        const urls = this.images.map((d) => d.fileUrl);
        console.log('urls:', urls);
      }
    }
  };
</script>
