<template>
  <view class="uploader">
    <view v-for="(item, index) in queue" :key="index" class="uploaded">
      <image :src="item.url" />
      <icon class="close" type="clear" :size="18" @click="remove(index)" />
    </view>

    <view v-if="!limited" class="upload" @click="upload">
      <image src="https://img.lkbang.net/xcx/pic.png" mode="aspectFit" />
      <view>
        <text class="tips">最多{{ maxCount }}张</text>
      </view>
    </view>
  </view>
</template>
<script>
import qiniu from "./qiniu";
export default {
  name: "ImageUploader",
  props: {
    maxCount: {
      type: Number,
      default: 3
    }
  },
  data() {
    return {
      queue: [],
      uploader: null
      // cancelTask: function() {},
    };
  },
  computed: {
    limited() {
      return this.queue.length >= this.maxCount;
    }
  },
  created() {
    this.initQiniu();
    this.uploader = qiniu;
  },
  methods: {
    upload() {
      uni.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album"], //从相册选择
        success: res => {
          uni.showLoading({
            title: "上传中"
          });
          this.uploader.upload(
            res.tempFilePaths[0],
            this.uploadSuccess,
            this.uploadFail,
            null,
            this.uploadProgress,
            // eslint-disable-next-line no-unused-vars
            cancelTask => {}
          );
        }
      });
    },
    uploadSuccess(res) {
      uni.hideLoading();
      this.queue.push({
        url: res.fileURL
      });
      this.onChange();
    },
    uploadFail(err) {
      console.error(err);
      uni.hideLoading();
    },
    uploadProgress() {},
    remove(index) {
      this.queue.splice(index, 1);
      this.onChange();
    },
    onChange() {
      this.$emit("change", JSON.parse(JSON.stringify(this.queue)));
    },
    initQiniu() {
      const option = {
        region: "ECN",
        uptokenURL: "https://mapi.q-gp.com/upload/token",
        domain: "https://appsync.lkbang.net",
        shouldUseQiniuFileName: true
      };
      qiniu.init(option);
    }
  }
};
</script>
<style lang="scss" scoped>
.uploader {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;

  .upload {
    width: 170rpx;
    height: 170rpx;
    border: 1px dashed #999;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    image {
      width: 40rpx;
      height: 36rpx;
    }

    .tips {
      font-size: 24rpx;
      color: #999;
    }
  }

  .uploaded {
    width: 170rpx;
    height: 170rpx;
    margin-right: 30rpx;
    margin-bottom: 20rpx;
    position: relative;

    image {
      width: 100%;
      height: 100%;
    }

    .close {
      position: absolute;
      top: 0;
      right: 0;
      transform: translate(50%, -50%);
    }
  }
}
</style>
