<template>
  <view class="cu-form-group">
    <view class="grid col-4 grid-square flex-sub">
      <view
        v-for="(item, index) in imgList"
        @tap="viewImg(index)"
        :key="index"
        class="bg-img"
      >
	  <!-- {{item.id?CONFIG('webHost')+item.url:item.url}} -->
        <image
          v-if="showfile()"
          :src="item.id?CONFIG('webHost')+item.url:item.url"
          mode="aspectFill"
        ></image>
        <view v-if="!readonly" @tap.stop="delImg(index)" class="cu-tag bg-red" style="width: 18px; height: 18px; font-size: 24px">
          <l-icon
            type="close"
            style="width: 18px; height: 18px; font-size: 12px"
          />
        </view>
      </view>

      <view
        v-if="!readonly && imgList.length < Number(number)"
        @tap="chooseImg"
        class="solids"
      >
        <l-icon type="cameraadd" />
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "l-upload",

  props: {
    number: { default: 1 },
    readonly: {},
    value: { default: () => [] },
  },
  
  data(){
	  return{
		  imgList:[],
	  }
  },

  methods: {
    delImg(index) {
      const newList = JSON.parse(JSON.stringify(this.imgList));
      newList.splice(index, 1);
	  this.imgList = newList
	  
	  this.$emit("update:value", newList);
      this.$emit("input", newList);
      this.$emit("change");
      this.$emit("del");
    },
    showfile() {
      return true;
    },

    chooseImg() {
      uni.chooseImage({
        count: (Number(this.number) - this.imgList.length),
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
		  let {tempFilePaths,tempFiles} = res
		  if(!this.validate(tempFiles))return
          const newList = JSON.parse(JSON.stringify(this.imgList || [])).concat(
            tempFilePaths.map(item=>{
				return{
					url:item,
					id:''
				}
			})
          );
		  this.imgList = newList
		  
		  this.$emit("update:value", newList);
          this.$emit("input", newList);
          this.$emit("change",newList);
          this.$emit("add");
        },
      });
    },
	
	uploadImage(){
		// 单图上传
		return new Promise(async (reslove,reject)=>{
			let hasNotUpdatedList = this.imgList.every(item=>item.id)
			if(hasNotUpdatedList){
				reslove(this.imgList)
			}
			if(this.imgList.length){
				var postData = {
					Base64Url: await this.imgToBase64(this.imgList[0].url)
				}
				this.HTTP_POST('StuInfoFresh/savePhoto', postData, '图片上传失败！').then((data) => {
					if (data) {
						reslove([{
							url:data.Url,
							id:data.AnnexesFileId
						}])
					}else{
						reject('图片上传失败！')
					}
				})
			}else{
				reslove("")
			}
		})
	},
	
	/**
	 * @description 控制promise.all并发数量
	 * @param limit 并发数
	 * @param array 参数列表
	 * @param apiFn 执行函数
	 * @returns {Promise<Awaited<unknown>[]>}
	 */
	async promiseAllLimit(limit, array, apiFn) {
		const ret = [] // 用于存放所有的promise实例
		const executing = [] // 用于存放目前正在执行的promise
		for (const item of array) {
			const p = apiFn(item)
			ret.push(p)
			if (limit <= array.length) {
				// then回调中，当这个promise状态变为fulfilled后，将其从正在执行的promise列表executing中删除
				const e = p.then(() => executing.splice(executing.indexOf(e), 1))
				executing.push(e)
				if (executing.length >= limit) {
					// 一旦正在执行的promise列表数量等于限制数，就使用Promise.race等待某一个promise状态发生变更，
					// 状态变更后，就会执行上面then的回调，将该promise从executing中删除，
					// 然后再进入到下一次for循环，生成新的promise进行补充
					await Promise.race(executing)
				}
			}
		}
		return Promise.all(ret)
	},
	
	imgToBase64(url){
		return new Promise((resolve,reject)=>{
			if(!url){
				resolve("")
			}
			var canvas = document.createElement('canvas'),
			  ctx = canvas.getContext('2d'),
			  img = new Image;
			  
			  img.crossOrigin = 'Anonymous';
			  img.onload = function () {
				canvas.height = img.height;
				canvas.width = img.width;
				ctx.drawImage(img, 0, 0);
				var dataURL = canvas.toDataURL('image/png');
				canvas = null;
				resolve(dataURL)
			  };
			  img.src = url;
		})
	},
	
	validate(array){
		// let type = array.every(item=>{
		// 	return item.type && item.type.substring(0,6) == "image/"
		// })
		// if(!type){
		// 	this.TOAST('文件类型错误');
		// 	return false
		// }
		let size = array.every(item=>{
			return item.size && item.size <= 100 * 1024 * 1024
		})
		if(!size){
			this.TOAST('文件大小不得超过100M');
			return false
		}
		return true
	},

    viewImg(index) {
      uni.previewImage({
        urls: this.imgList.map(item=>item.id?this.CONFIG('webHost')+item.url:item.url),
        current: this.imgList[index].id?this.CONFIG('webHost')+this.imgList[index].url:this.imgList[index].url,
      });
    },
	
	// previewFile() {
	//     var file = document.querySelector('input[type=file]').files[0];
	//     var reader = new FileReader();
	// 	// fileReader.readAsDataURL(blob);
	// 						// fileReader.onerror = () => {
	// 						// 	reject(new Error('blobToBase64 error'));
	// 						// };
	// 	// var encodedData = window.btoa("Hello, world");
	//     reader.onloadend = function () {
	//         //$('#PhotoImg').attr('src', reader.result);
	//         var postData = {
	//             Base64Url: reader.result
	//         }
	//         this.HTTP_POST(config.webapi + "StuInfoFresh/savePhoto", postData, (data) => {
	//             if (data) {
	//                 $('#Photo').val(data.AnnexesFileId);
	//                 $('#PhotoImg').attr('src', config.web + data.Url);
	//             } else {
	//                 learun.layer.toast('采集照片信息失败！');
	//             }
	//         });
	//     }
	//     if (file) {
	//         reader.readAsDataURL(file);
	//     }
	// },
  },
  created() {
	  console.log(123)
  	this.imgList = JSON.parse(JSON.stringify(this.value.map(item=>{
		item.isUploaded = true
		return item
	})))
	// [{url:"",id:""}]
  }
};
</script>
