<template>
	<view class="container">
		<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="1"></u-upload>
		<view class="form-item">
			<text>昵称：</text>
			<input v-model="nickname" placeholder="请输入昵称" />
		</view>
		<view class="form-item">
			<text>手机号码：</text>
			<input v-model="mobile" placeholder="请输入手机号码" />
		</view>
		<button @click="saveChanges">保存</button>
	</view>
</template>

<script>
	import {
		getTenantId,
		getToken
	} from "@/utils/auth";
	import request from "@/utils/request";
	import {
		baseImageUrl
	} from "@/config";

	export default {
		data() {
			return {
				nickname: '',
				mobile: '',
				fileList: [],
			};
		},
		onLoad(options) {
			// 获取传递的参数并赋值
			this.id = options.id;
			this.getMy()
		},
		methods: {
			saveChanges() {
				request({
					url: '/system/user/profile/update',
					method: 'put',
					data: {
						nickname: this.nickname,
						mobile: this.mobile,
					}
				})
				// 保存修改后的信息（你可以进行表单验证和 API 请求）
				console.log('保存信息', this.nickname, this.mobile);
				request({
					url: '/company/staff/getByUserId',
					method: 'get',
					params: {
						id: uni.getStorageSync('userId')
					}
				}).then((res) => {
					setUserInfo(res.data.user)
				})
				// 假设保存成功后返回上一页
				setTimeout(() => {
					uni.navigateBack();
				}, 500);
			},
			async getMy() {
				let res = await request({
					url: '/system/user/profile/get',
					method: 'get',
				})
				this.nickname = res.data.nickname
				this.mobile = res.data.mobile
				this.avatar = res.data.avatar
				this.fileList.push({
					url: baseImageUrl + '/' + this.avatar,
					status: 'success'
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log('event', event)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				console.log('lists', lists)
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].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.$baseUrl + '/system/user/profile/update-avatar',
						filePath: url,
						name: 'avatarFile',
						header: {
							'Tenant-Id': getTenantId(),
							'Authorization': 'Bearer ' + getToken()
						},
						formData: {
							user: 'test'
						},
						success: (res) => {
							try {
								let img = JSON.parse(res.data);
								this.imagePath = img.data.url

							} catch (e) {
								//TODO handle the exception
							}
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
		}
	};
</script>

<style scoped>
	.container {
		padding: 20px;
	}

	.form-item {
		margin-bottom: 15px;
	}

	input {
		width: 95%;
		padding: 10px;
		margin-top: 5px;
		border: 1px solid #ddd;
		border-radius: 4px;
	}

	button {
		margin-top: 20px;
		background-color: #007aff;
		color: white;
		padding: 10px;
		border-radius: 5px;
		width: 100%;
	}
</style>