<template>
<view>
	<view class="cu-form-group" style="border-bottom: none; padding-bottom: 0;">
	  <view class="title">
	    <text v-if="required" class="lr-required">*</text>
	    {{ title || '' }}
	  </view>
	</view>
	<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()&&item&&(typeof item == 'string'||isImage(item.type))" :src="item.url?CONFIG('webHost') + item.url:item" 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">
				<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>
</view>
</template>

<script>
	/**
	 * 附件上传组件
	 * 直接选择手机文件
	 * 
	 * 注意:可以是图片、文档、等;
	 */
	
	export default {

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

		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('/learun/adms/annexes/wxdelete', 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 uploadImageRes = await this.uploadImage(tempFilePaths[0], tempFiles[0] ? tempFiles[0].name : "")
				let newList = this.imgList || []
				if (uploadImageRes) {
					//请求‘获取附件列表’接口
					let data =  await this.FETCH_FILEList(uploadImageRes);
					if(data){
						newList = data.map(t=>({
							id: t.F_Id,
							name: t.F_FileName,
							url: t.F_FilePath.substring(t.F_FilePath.indexOf('Resource')),
							type: t.F_FileType,
							folderid:t.F_FolderId,
						}))
					}
				}

				this.imgList = newList

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

			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('/learun/adms/annexes/wxuploadinsingle', url, params).then((data) => {
						this.HIDE_LOADING();
						this.$refs.lsjUpload.show()
						if (data) {
							reslove(data)
						} 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
					});
				}
			},
		},
		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.substring(item.F_FilePath.indexOf('Resource')),
					type: item.F_FileType,
					folderid:item.F_FolderId,
				}
			})))
			this.$nextTick(() => {
				this.isShow = true
			})
		}
	};
</script>

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

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