<template>
	<uni-file-picker v-model="imgList" file-mediatype="image" mode="grid" :limit="limit" @progress="FileUploadprogress"
	:image-styles="imageStyles"
		@delete="fileDelete" @success="FileUploadsuccess" @fail="FileUploadail" @select="FileUploadselect" />
</template>

<script setup>
	import {
		$uploadFile
	} from '@/http/yskApi/file.js'
	import {
		reactive,
		ref,
		watch
	} from 'vue';
	const props = defineProps({
		images: {
			type: [Array,String],
			default: () => {
				return []
			}
		},
		limit: {
			type: Number,
			default: 10
		},
		imageStyles:{
			type:Object,
			default:()=>{
				return {
					border:{
						radius:'12rpx'
					}
				}
			}
		}
	})
	const emits = defineEmits(['change'])
	const arr=props.images===''?[]:typeof props.images==='string'? [{path:props.images,url:props.images}]:props.images
	let imgList = ref(arr)
	let flag=false
	const stopWatcher = watch(() => props.images, (newval) => {
		if(!flag){
			imgList.value = (typeof newval==='string'&&newval!=='')?[{path:newval,url:newval}]:newval
			flag=true
		}
	})
	watch(() => imgList.value.length, () => {
		change()
	})
	//图片上传
	function FileUploadprogress() {

	}

	function FileUploadsuccess() {

	}

	function FileUploadail() {

	}

	function FileUploadselect(e) {
		for (let i in e.tempFiles) {
			const file = e.tempFiles[i]
			$uploadFile(file).then(res => {
				console.log(res);
				imgList.value.push({
					url: res.data[0],
					path: file.path
				})
			}).catch(res=>{
				console.log(res);
				if(res.errMsg){
					imgList.value.splice(i,1)
					uni.showToast({
						title:'图片大小超出限制',
						icon:'error'
					})
				}
				
			})
		}
	}

	function fileDelete(e) {
		const index = imgList.value.findIndex(v => e.tempFilePath === v.path)
		if (index != -1) {
			imgList.value.splice(index, 1)
		}
		console.log(imgList.value);
	}

	function getFileList() {
		if (props.limit === 1) {
			const item=imgList.value[0]
			return item===undefined?'':typeof item === 'string' ? item : item.url
		}
		return imgList.value.map(v => {
			const url = v.url
			return typeof v === 'string' ? v : url
		})
	}

	function change() {
		console.log(getFileList());
		emits('change', getFileList())
	}
	defineExpose({
		getFileList
	})
</script>

<style>
</style>