<template lang="pug">
  view.layout.pannel
    view.uni-uploader__files
      view(v-for="(image, index) in imageList" :key="index")
        view.uni-uploader__file
          image.uni-uploader__img(:src="image" :data-src="image" @tap="previewImage")
          image.del(:src="getIcon('del')" @click="removeImage(index)")
    image.add(:src="getIcon('add')" @click="chooseImage")
</template>

<script lang="ts">
import {Component, Prop, Vue} from "vue-property-decorator";
import IconHelper from "../images-upload/IconHelper";
// @ts-ignore
import { pathToBase64, base64ToPath } from 'image-tools'

const sourceType = [
  // ['camera'],
  ['album'],
  // ['camera', 'album']
];
const sizeType = [
  ['compressed'],
  // ['original'],
  // ['compressed', 'original']
];

@Component
export default class ImagesUpload extends Vue {
  @Prop() public maxImage!: number;
  private imageList: any = [];
  private imageBase: string = "";
  private countIndex: number = 8;
  private count: any = [1, 2, 3, 4, 5, 6, 7, 8, 9];

  getIcon(type: string) {
    if(type=='add') {
      return IconHelper.getAdd();
    }
    if(type=='del') {
      return IconHelper.getDelete();
    }
    return '';
  }

  removeImage(index: number) {
    this.imageList.splice(index, 1);
    this.onChange();
  }

  chooseImage() {
    if (this.imageList.length >= (this.maxImage || 3)) {
      this.isFullImg((reason: any) => {
        console.log(reason + "...");
        if (reason === true) {
          this.openPhotoAlbum();
        }
      });
    } else {
      this.openPhotoAlbum();
    }
  }

  previewImage(e: any) {
    var current = e.target.dataset.src
    uni.previewImage({
      current: current,
      urls: this.imageList
    })
  }

  isFullImg(callback: Function) {
    return new Promise((res) => {
      uni.showModal({
        content: "图片已经超出限制数量，是否清空现有图片？",
        success: (e) => {
          if (e.confirm) {
            this.imageList = [];
            res(true);
            callback(true);
          } else {
            res(false)
          }
        },
        fail: () => {
          res(false)
        }
      })
    })
  }

  openPhotoAlbum() {
    uni.chooseImage({
      sourceType: sourceType[0],
      sizeType: sizeType[0],
      count: this.imageList.length + this.count[this.countIndex] > 3 ? 3 - this.imageList.length : this.count[this.countIndex],
      success: async (res) => {

        this.imageList = this.imageList.concat(res.tempFilePaths);
        this.onChange();
      },
      fail: (err) => {
        console.log("获取图片失败")
        console.log("err: ", err);
      }
    })
  }

  async onChange() {
    this.imageBase = "";
    for (let i = 0; i < this.imageList.length; i++) {
      await this.toBase64(this.imageList[i]).then((base64: string) => {
        this.imageBase = this.imageBase + base64.replace(/data:image\/\w+;base64,\s*/gmi, '') + ',';
      })
    }
    this.imageBase = this.imageBase.substr(0, this.imageBase.length - 1);
    console.log("获取图片成功")
    this.$emit("choose", this.imageBase);
  }

  async toBase64(path: string) {
    let base64Str: string = '';
    await pathToBase64(path)
        .then((base64: any) => {
          base64Str = base64;
          console.log(base64)
        })
        .catch((error: any) => {
          console.error(error)
          return Promise.reject(error)
        })

    return Promise.resolve(base64Str);
  }
}
</script>

<style scoped lang="scss">
@import '../../static/styles/h5-unit';
@import '../../static/styles/base';

.del{
  width: $px13;
  height: $px13;
  position: absolute;
  top: $px2;
  right: $px11;
}

.uni-uploader-body {
  margin-top: $px16;
}

.uni-uploader__files {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  background-color: rgba(0,0,0,0);
}

.uni-uploader__img {
  display: block;
  width: $px44;
  height: $px44;
  margin-right: $px9;
}


.pannel {
  display: flex;
  flex-direction: column;
  height: $px62;
  background-color: #FFFFFF;
  border-bottom: $px20;
  padding: $px0 $px18;
  margin-left: $px18;
  margin-right: $px18;
  border-bottom-right-radius: $px18;
  border-bottom-left-radius: $px18;

  .add {
    width: $px44;
    height: $px44;

  }
}
</style>
