<template>
	<view>
		<u-upload
			:fileList="fileList"
			@afterRead="afterRead"
			@delete="deletePic"
			name="3"
			:multiple='false'
			:maxCount="maxCount"
			:previewFullImage="true"
			width="110"
				height="110"
				:deletable="id==''"
		></u-upload>
	</view>
</template>

<script>
	export default {
		onLoad(option) {
			if(option.id){
				this.id=option.id
			}
			this.getpersonPhoto()
		},
		data() {
			return {
				fileList: [],
				id:'',
				maxCount:10
			}
		},
		methods: {
			getpersonPhoto(){
				uni.$u.http.post('/api/user/personal_album',{id:this.id?this.id:uni.getStorageSync('userId')}).then(res => {
					if(res.code==1){
						this.fileList=res.data
						if(this.id){
							this.maxCount=res.data.length
						}
					}
				})
			},
			// 删除图片
						deletePic(event) {
							console.log(event)
							var that=this
							uni.showModal({
								title: '',
								content: '是否删除这张图片',
								confirmColor:'#FF3D3D',
								confirmText:'删除',
								success: function (res) {
									if (res.confirm) {
										uni.$u.http.post('/api/user/del_album',{id:event.file.id}).then(res => {
											if(res.code==1){
												that.getpersonPhoto()
											}
										})
									} else if (res.cancel) {
										console.log('用户点击取消');
									}
								}
							});

						},
						// 新增图片
						async afterRead(event) {
							// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
							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.uploadFilePromise(lists[i].url)
								uni.$u.http.post('/api/user/upload_album',{image:result,type:1}).then(res => {
									if(res.code==1){
										this.getpersonPhoto()
									}
								})
								// 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) => {
								let a = uni.uploadFile({
									url: this.$url+'/api/Publics/uploadLocality', // 仅为示例，非真实的接口地址
									filePath: url,
									name: 'file',
									formData: {
										user: 'test'
									},
									success: (res) => {
										setTimeout(() => {
											resolve(JSON.parse(res.data).data.url)
										}, 1000)
									}
								});
							})
						},
		}
	}
</script>

<style>
page{
	padding: 30rpx;
}
</style>
