<template>
	<u-upload :capture="['album', 'camera']" :multiple="true" :fileList="fileList"
		@afterRead="afterRead($event, 'fileList')" @delete="deletePic($event, 'fileList')" :maxCount="maxCount"
		:width="width" :height="height">
		<image :style="{'width': width + 'px', 'height': height + 'px'}" src="@/static/icon_upload.png"></image>
	</u-upload>
</template>

<script>
	export default {
		props: {
			width: {
				type: String,
				default: '100'
			},
			height: {
				type: String,
				default: '100'
			},
			maxCount: {
				type: String,
				default: '9'
			},
			type: {
				type: String,
				default: 'fullurl'
			},
			images: { // 重置fileList把images设为空即可
				type: String,
				default: ''
			}
		},
		data() {
			return {
				fileList: []
			}
		},
		model: {
			prop: 'images',
			event: 'upload'
		},
		watch: {
			images: {
				immediate: true,
				handler(newVal, oldVal) {
					this.fileList = []
					if (newVal) {
						const urlList = newVal.split(",")
						console.log(urlList)
						urlList.forEach(item => {
							this.fileList.push({
								status: 'success',
								message: '',
								fullurl: url,
								url: url
							})
						})
					}
				}
			}
		},
		methods: {
			// 删除图片
			deletePic(event, type) {
				this.fileList.splice(event.index, 1)
				this.uploadParseData()
			},
			// 新增图片
			async afterRead(event, type) {
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.$wskj.uploadImg(lists[i].url)
					console.log(result)
					let item = this[[type]][fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url,
						fullurl: result.url
					}))
					fileListLen++
				}
				this.uploadParseData()
			},
			uploadParseData() {
				const images = this.fileList.map(item => item[this.type]).join(",")
				console.log(this.fileList)
				console.log(images)
				this.$emit('upload', images)
			},
			removeUrl(str, urlToRemove) {
				// 使用正则表达式匹配要删除的URL，确保匹配整个字符串  
				// 注意：这里我们假设urlToRemove不包含查询字符串或路径，如果包含，需要调整正则表达式  
				const regex = new RegExp(urlToRemove, 'g');

				// 使用replace方法替换匹配的URL为空字符串，即删除它们  
				return str.replace(regex, '');
			}
		}
	}
</script>

<style scoped>

</style>