<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>
			<!-- #ifdef APP-PLUS -->
			<view v-if="formData.folderId&&!readonly && value.length < Number(number)" style="display: inline-block;padding-left: 20px;">
				<lsjupload ref="lsjUpload" height="32px" width="80px" :option="{
					url:API+'/learun/adms/annexes/wxupload',formData
				}"  :instantly="true" :count="1" :size="200" @change="chooseChange" @uploadEnd="uploadEnd">
				</lsjupload>
			</view>
			<!-- #endif -->
		</view>

		<view class="cu-form-group" style="border-top: none;">
			<view class="grid col-4 grid-square flex-sub">
				<view v-for="(file, index) in value" :key="index" class="bg-img" style="position: relative;">
					<view v-if="file.noUpdated" class="mask"></view>
					<image v-if="isImgFile(file.type)" @click="fileClick(index)" :src="file.path?file.path:file"
						:webp="file.type === 'webp'" mode="aspectFill"></image>
					<view v-else-if="isDocFile(file.type)" @click="fileClick(index)" class="file-icon solids">
						<l-icon type="text" />
					</view>
					<view v-else class="file-icon solids" @click="fileClick(index)">
						<l-icon type="text" />
					</view>

					<view v-if="!readonly" @click.stop="delFile(index,file.uid)" class="cu-tag bg-red"
						style="height: 24px; width: 24px;">
						<l-icon type="close" color="white" style="width: 18px; height: 24px; font-size: 24px;" />
					</view>
					<view class="fileName">
						<text>{{file.name}}</text>
					</view>
				</view>
				<!-- #ifndef APP-PLUS -->
				<view v-if="!readonly && value.length < Number(number)" @click="chooseFile" class="solids">
					<l-icon type="file" />
				</view>
				<!-- #endif -->
			</view>
		</view>
	</view>
</template>

<script>
	import lsjupload from '@/components/lsj-upload/lsj-upload.vue'
	export default {
		name: 'l-upload-file',
		components: {
			lsjupload,
		},
		props: {
			number: {
				default: 1
			},
			labelId: {
				default: ''
			},
			tableName: {
				default: ''
			},
			fieldName: {
				default: ''
			},
			readonly: {},
			value: {
				default: () => []
			},
			title: {},
			required: {}
		},
		data() {
			return {
				formData: {},
			}
		},
		created() {
			// #ifdef APP-PLUS
			if(this.labelId){
				var guid = undefined
				// 先生成一个guid
				guid = this.newguid();
				// 取出当前列对应的labelId
				var labeId = this.labelId
				// 从缓存取出当前审批流程所有的guid
				var guids = JSON.parse(uni.getStorageSync('guids'))
				if (guids && JSON.stringify(guids) !== '{}' && guids[labeId]) {
					guid = guids[labeId]
				}
				this.formData.loginMark=this.getLoginMark(),
				this.formData.token=this.GET_GLOBAL('token')
				this.formData['folderId'] = guid
			}else{
				if(!this.tableName||!this.fieldName)return
				var uploadUid = '',
				tableName=this.tableName,
				fieldName=this.fieldName
				let folderIds = uni.getStorageSync('folderIds');
				if(folderIds){
				  folderIds = JSON.parse(folderIds)
				  if(folderIds[tableName]&&folderIds[tableName][fieldName]){
					uploadUid = folderIds[tableName][fieldName]
				  }
				}
				if(!uploadUid){
					uploadUid = this.newguid()
				}
				
				this.formData.loginMark=this.getLoginMark(),
				this.formData.token=this.GET_GLOBAL('token')
				this.formData['folderId'] = uploadUid
			}
			// #endif
		},

		methods: {
			async chooseChange(files) {
				this.LOADING('正在提交...')
			},
			async uploadEnd(){
				this.$refs.lsjUpload.clear()
				this.HIDE_LOADING() 
				this.folderIdToList(this.formData['folderId'])
			},
			async chooseChangeOld(files) {
				this.LOADING('正在提交...') 
				await this.$refs.lsjUpload.upload()
				this.HIDE_LOADING() 
				let array = Array.from(files);
				if (array.length) {
					await this.$refs.lsjUpload.clear()
				}
				let tempFilePaths = [],
					tempFiles = [];
				array.forEach(item => {
					tempFilePaths.push(item[1].path)
					tempFiles.push({
						name: item[1].name,
						size: item[1].size,
						folderId: this.formData.folderId
					})
				})
				if (!tempFilePaths.length) {
					return
				}
				// let fileName = tempFiles[tempFiles.length]
				// let uploadRes = await this.$refs.lsjUpload.upload(tempFiles[i].name)
				// if(!uploadRes){
				// 	this.TOAST('上传失败！')
				// 	return
				// }
				const newList = JSON.parse(JSON.stringify(this.value || [])).concat(
					tempFilePaths.map((t, i) => ({
						path: t,
						type: tempFiles[i].type,
						size: tempFiles[i].size,
						name: tempFiles[i].name,
						folderId:tempFiles[i].folderId,
						noUpdated: false
					}))
				)
				this.$emit('input', newList)
				this.$emit('change', newList)
				this.$emit('add')
			},
			// 文件夹id转化为文件列表
			async folderIdToList(folderId){
				const uidList = folderId;
				const fileList = []
				const wxlist = await this.FETCH_FILEList(uidList);
				for (const wxfile of wxlist) {
					const fileInfo = await this.FETCH_FILEINFO(wxfile.F_Id)
					if (!fileInfo) {
						continue
					}
		
					const fileType = fileInfo.F_FileType
					const fileSize = fileInfo.F_FileSize
					const fileName = fileInfo.F_FileName
		
					const path = this.API + '/learun/adms/annexes/wxdown?' + this.URL_QUERY(wxfile.F_Id, true)
					fileList.push({
						path,
						type: fileType,
						uid:wxfile.F_Id,
						folderId:wxfile.F_FolderId,
						size: fileSize,
						name:fileName
					})
				}
				
				this.$emit('input', fileList)
				this.$emit('change', fileList)
				this.$emit('add')
			},

			getFileExt(path) {
				return /\.(\w{2,5})$/.exec(path)[1] || null
			},

			isImgFile(type) {
				const typeString = (type || '').toLowerCase()
				return ['jpg', 'image/jpg', 'jpeg', 'image/jpeg', 'png', 'image/png', 'gif', 'image/gif', 'bmp',
					'image/bmp', 'webp', 'image/webp', 'image'
				].includes(typeString)
			},

			isDocFile(type) {
				const typeString = (type || '').toLowerCase()
				return ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'].includes(typeString)
			},

			async delFile(index, fileId) {
				if (!(await this.CONFIRM('删除文件', '确定要删除该文件吗？', true))) {
					return
				}
				const newList = JSON.parse(JSON.stringify(this.value))
				newList.splice(index, 1)
				this.$emit('input', newList)
				this.$emit('change')
				this.$emit('del')
				//物理删除
				this.DELETE_FILE(fileId);
			},

			chooseFile() {
				// #ifdef APP-PLUS
				return
				// #endif
				uni.chooseFile({
					count: Number(this.number),
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: ({
						tempFilePaths,
						tempFiles
					}) => {
						const newList = JSON.parse(JSON.stringify(this.value || [])).concat(
							tempFilePaths.map((t, i) => ({
								path: t,
								type: tempFiles[i].type,
								size: tempFiles[i].size,
								name: tempFiles[i].name,
								noUpdated: false
							}))
						)
						this.$emit('input', newList)
						this.$emit('change', newList)
						this.$emit('add')
					}
				})
			},

			async fileClick(index) {
				const {
					path,
					type,
					uid,
					size = 0
				} = this.value[index]
				if (this.isImgFile(type)) {
					uni.previewImage({
						urls: [path],
						current: path
					})
				} else {
					// #ifdef APP-PLUS
					uni.downloadFile({
						url: path, //仅为示例，并非真实的资源
						success: (res) => {
							if (res.statusCode === 200) {
								uni.openDocument({
									filePath: res.tempFilePath,
									fileType: type
								})
							}else{
								this.TOAST('下载失败！')
							}
						}
					});
					return
					// #endif
					
					
					uni.openDocument({
						filePath: path,
						fileType: type
					})
				}
			},


			newguid() {
				return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},
		}
	}
</script>

<style lang="less" scoped>
	.file-icon {
		line-height: 100%;
		position: static;
	}

	.fileName {
		padding: 2px 2px;
		margin-bottom: 2px;
		text-align: center;
		position: absolute;
		bottom: 0px;
		width: 100%;
		background: rgba(0, 0, 0, 0.2);
		color: #fff;
		font-size: 12px;

		text-overflow: ellipsis;
		overflow: hidden;
		white-space: nowrap;
	}

	.mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		// background: rgba(255,252,153,0.2);
		background: rgba(0, 0, 0, 0.7);
		z-index: 100;
		pointer-events: none;
	}
</style>
