<template>
	<view class="">
		<u-upload 
			accept="image" 
			:capture="['album', 'camera']" 
			:fileList="fileList" 
			@afterRead="afterRead"
			@delete="deletePic" 
			:max-count="1" 
			name="pet" width="60" 
			height="60">
			<image src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/image.png" style="width: 60px;height: 60px;">
			</image>
		</u-upload>
	</view>
</template>

<script>
import { currentUrl } from '@/utils/getUrl'
export default{
	data(){
		return{
			fileList:[]
		}
	},
	props:{
		imageUrl:{
			type:String,
			default:''
		}
	},
	mounted(){
		if(this.imageUrl){
			this.fileList=[{url:this.imageUrl}]
		}else{
			this.fileList=[]
		}
		
	},
	methods:{
		// 删除图片
		deletePic(event) {
			this.fileList.splice(event.index, 1)
			this.$emit('update:imageUrl', '');
		},
		
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			let fileListLen = this.fileList.length
			lists.map((item) => {
				this.fileList.push({
					...item,
					status: 'uploading',
					message: '上传中'
				})
			})
			
			const result = await this.uploadFilePromise(lists[0].url)
			if(result){
				this.fileList[0].status='success'
				this.fileList[0].message=''
				this.fileList[0].url=result
			} 
			this.$emit('update:imageUrl', this.fileList[0].url);
			// for (let i = 0; i < lists.length; i++) {
			// 	const result = await this.uploadFilePromise(lists[i].url)
			// 	let item = this.fileList[fileListLen]
			// 	this.fileList.splice(fileListLen, 1, Object.assign(item, {
			// 		status: 'success',
			// 		message: '',
			// 		url: result
			// 	}))
			// 	fileListLen++
			// }
			
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: `${currentUrl}/h5/oss/upload`,
					filePath: url,
					name: 'file',
					formData: {
						user: 'test'
					},
					success: (res) => {
						setTimeout(() => {
							if(res&&res.data){
								let resData = JSON.parse(res.data);
								resolve(resData.url);
							}
							reject("上传失败");
						}, 1000)
					},
					
				});
			})
		},
	}
}
</script>

<style></style>