<template>
	<view class="cu-form-group">
		<view class="grid col-4 grid-square flex-sub">
			<view v-for="(item, index) in imgList" @tap="viewImg(item)" :key="index" class="bg-img">
				<image v-if="showfile()&&isImage(item.type)" :src="CONFIG('webHost') + item.url" mode="aspectFill">
				</image>
				<l-icon v-if="showfile()&&!isImage(item.type)" type="text" />
				<text class="file-name">{{item.name}}</text>
				<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-show="!readonly && imgList.length < Number(number)&&isShow" class="solids">
				<!-- @tap="chooseImg" -->
				<l-icon type="file" />
				<lsj-upload ref="lsjUpload" height="80px" width="100%" :size="20" :option="{}" :count="1"
					@change="chooseChange" style="opacity: 0;"></lsj-upload>
			</view>

		</view>
	</view>

</template>

<script>
	export default {

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

		data() {
			return {
				isShow: false,
				imgList: [],
			}
		},

		methods: {
			chooseChange(files) {
				let array = Array.from(files);
				if (array.length) {
					this.$refs.lsjUpload.clear()
				}
				let tempFilePaths = [],
					tempFiles = [];
				array.forEach(item => {
					tempFilePaths.push(item[1].path)
					tempFiles.push(item[1].file)
				})
				this.chooseChangeback(tempFilePaths, tempFiles)
			},
			delImg(index) {
				this.CONFIRM("", "是否确认删除？", true).then(res => {
					if(!res)return
					this.LOADING('正在删除…');
					const newList = JSON.parse(JSON.stringify(this.imgList));
					this.HTTP_POST('StuInfoFresh/deleteFiles', {
						id: this.imgList[index].id
					}, "文件删除失败").then((data) => {
						this.HIDE_LOADING();
						if (data) {
							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;
			},

			async chooseChangeback(tempFilePaths, tempFiles) {
				// let {tempFilePaths,tempFiles} = res
				// if(!this.validate(tempFiles))return
				let uploadImageRes = await this.uploadImage(tempFilePaths[0], tempFiles[0] ? tempFiles[0].name : "")
				let newList = this.imgList || []
				if (uploadImageRes) {
					newList = JSON.parse(JSON.stringify(newList)).concat(uploadImageRes);
				}

				this.imgList = newList

				this.$emit("update:value", newList);
				this.$emit("input", newList);
				this.$emit("change", newList);
				// this.$emit("add");
			},

			uploadImage(url, name) {
				if (!url) return
				// 文件上传
				return new Promise(async (reslove, reject) => {
					this.LOADING('正在上传…');
					let params = name ? {
						folderId: this.folderId,
						name
					} : {
						folderId: this.folderId
					}
					this.HTTP_UPLOAD2('StuInfoFresh/upload', url, params).then((data) => {
						this.HIDE_LOADING();
						this.$refs.lsjUpload.show()
						if (data) {
							// this.HTTP_GET('StuInfoFresh/upload', {fileId:data})
							reslove([{
								id: data.F_Id,
								name: data.F_FileName,
								url: data.F_FilePath,
								type: data.F_FileType,
							}])
						} else {
							reject('上传失败！')
						}
					})
				})

			},

			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 <= 200 * 1024 * 1024
				})
				if (!size) {
					this.TOAST('文件大小不得超过200M');
					return false
				}
				return true
			},

			isImage(type) {
				if (type && type.length) {
					return ["png", "jpg"].includes(type.substring(type.length - 3, type.length))
				} else {
					return false
				}
			},

			viewImg(item) {
				if (!this.isImage(item.type)) {
					window.location.href = this.CONFIG("webHost") + item.url
				} else {
					uni.previewImage({
						urls: [this.CONFIG('webHost') + item.url],
						current: this.CONFIG('webHost') + item.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(this.value)
			this.imgList = JSON.parse(JSON.stringify(this.value.map(item => {
				return {
					id: item.F_Id,
					name: item.F_FileName,
					url: item.F_FilePath,
					type: item.F_FileType
				}
			})))
			this.$nextTick(() => {
				this.isShow = true
			})
		}
	};
</script>

<style scoped>
	.file-name {
		position: absolute;
		bottom: 0;
		width: 100%;
		color: #606266;
		font-size: 13px;
		text-align: center;
		background-color: rgba(255, 255, 255, 0.6);

		text-overflow: ellipsis;
		overflow: hidden;
		white-space: nowrap;
	}
</style>
