<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) {
					// console.log(newVal)
					// console.log(this.fileList)
					this.fileList = []
					if (newVal) {
						const urlList = newVal.split(",")
						urlList.forEach(item => {
							// 防止直接传递全路径
							let url = this.removeUrl(item, this.$config.domain)
							this.fileList.push({
								status: 'success',
								message: '',
								fullurl: this.$config.domain + url,
								url: url
							})
						})
					}
				}
			}
		},
		methods: {
			// 删除图片
			deletePic(event, type) {
				this.fileList.splice(event.index, 1)

				this.uploadParseData()
			},
			// 新增图片
			async afterRead(event, type) {
				// console.log(event)
				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.fullurl
					}))
					fileListLen++
				}
				this.uploadParseData()
			},
			uploadParseData() {
				const images = this.fileList.map(item => item[this.type]).join(",")
				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>