<template>
	<un-pages
		:show-nav-bar="true"
		nav-bar-title="编辑资料"
		:show-back="true"
		:show-tab-bar="false"
		:nav-bar-right-text="loading ? '保存中...' : '保存'"
		@nav-bar-right-click="handleSave"
	>
		<view class="edit-profile-container">
			<!-- 头像上传 -->
			<view class="avatar-section">
				<view class="avatar-wrapper" @tap="chooseAvatar">
					<image v-if="formData.avatar" :src="formData.avatar" class="avatar-image" mode="aspectFill"></image>
					<uni-icons v-else type="person-filled" size="60" color="#ccc"></uni-icons>
					<view class="avatar-overlay">
						<uni-icons type="camera" size="20" color="#fff"></uni-icons>
						<text class="avatar-tip">更换头像</text>
					</view>
				</view>
			</view>

			<!-- 表单区域 -->
			<view class="form-section">
				<view class="form-item">
					<text class="form-label">用户名</text>
					<input class="form-input" type="text" v-model="formData.username" placeholder="请输入用户名" disabled />
					<text class="form-tip">用户名不可修改</text>
				</view>

				<view class="form-item">
					<text class="form-label">昵称</text>
					<input class="form-input" type="text" v-model="formData.nickname" placeholder="请输入昵称" maxlength="20" />
				</view>

				<view class="form-item">
					<text class="form-label">邮箱</text>
					<input class="form-input" type="text" v-model="formData.email" placeholder="请输入邮箱" />
				</view>
			</view>

			<!-- 保存按钮 -->
			<view class="submit-section">
				<button class="submit-btn" @tap="handleSave" :disabled="loading">保存</button>
			</view>
		</view>
	</un-pages>
</template>

<script>
import memberApi from '@/api/modules/member'
import authApi from '@/api/modules/auth'
import commonApi from '@/api/modules/common'

export default {
	data() {
		return {
			loading: false,
			formData: {
				username: '',
				nickname: '',
				email: '',
				avatar: ''
			},
			originalData: {}
		}
	},

	onLoad() {
		this.loadUserInfo()
	},

	methods: {
		// 加载用户信息
		async loadUserInfo() {
			try {
				// 从本地存储获取用户信息
				const userInfo = uni.getStorageSync('userInfo') || {}
				this.formData = {
					username: userInfo.username || '',
					nickname: userInfo.nickname || '',
					email: userInfo.email || '',
					avatar: userInfo.avatar || ''
				}
				// 保存原始数据用于对比
				this.originalData = { ...this.formData }
			} catch (error) {
				console.error('加载用户信息失败:', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			}
		},

		// 选择头像
		chooseAvatar() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					const tempFilePath = res.tempFilePaths[0]
					this.uploadAvatar(tempFilePath)
				}
			})
		},

		// 上传头像
		async uploadAvatar(filePath) {
			try {
				uni.showLoading({
					title: '上传中...'
				})

				// 调用上传接口
				uni.uploadFile({
					url: commonApi.upload.url,
					filePath: filePath,
					name: 'file',
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('token')
					},
					success: (uploadRes) => {
						uni.hideLoading()
						try {
							const data = JSON.parse(uploadRes.data)
							if (data.code === 1) {
								this.formData.avatar = data.data.url || data.data
								uni.showToast({
									title: '上传成功',
									icon: 'success'
								})
							} else {
								uni.showToast({
									title: data.message || '上传失败',
									icon: 'none'
								})
							}
						} catch (e) {
							console.error('解析上传结果失败:', e)
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
					},
					fail: (error) => {
						uni.hideLoading()
						console.error('上传失败:', error)
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
					}
				})
			} catch (error) {
				uni.hideLoading()
				console.error('上传头像失败:', error)
				uni.showToast({
					title: '上传失败',
					icon: 'none'
				})
			}
		},

		// 保存修改
		async handleSave() {
			// 检查是否有修改
			const hasChanges = Object.keys(this.formData).some(key => {
				if (key === 'username') return false // 用户名不可修改
				return this.formData[key] !== this.originalData[key]
			})

			if (!hasChanges) {
				uni.showToast({
					title: '未做任何修改',
					icon: 'none'
				})
				return
			}

			// 表单验证
			if (!this.validateForm()) {
				return
			}

			try {
				this.loading = true
				uni.showLoading({
					title: '保存中...'
				})

				// 调用更新用户信息接口
				const result = await memberApi.edit.put({
					nickname: this.formData.nickname,
					email: this.formData.email,
					avatar: this.formData.avatar
				})

				uni.hideLoading()

				if (result && result.code === 1) {
					// 重新获取用户信息
					const userInfoRes = await authApi.info.get()
					if (userInfoRes && userInfoRes.code === 1) {
						const updatedUserInfo = userInfoRes.data || {}
						uni.setStorageSync('userInfo', updatedUserInfo)
						this.$store.commit('setUserInfo', updatedUserInfo)
					}

					uni.showToast({
						title: '保存成功',
						icon: 'success',
						duration: 1500
					})

					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: result.message || '保存失败',
						icon: 'none'
					})
				}
			} catch (error) {
				uni.hideLoading()
				console.error('保存失败:', error)
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},

		// 表单验证
		validateForm() {
			const { nickname, email } = this.formData

			if (nickname && nickname.length < 2) {
				uni.showToast({
					title: '昵称至少2个字符',
					icon: 'none'
				})
				return false
			}

			if (email) {
				const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
				if (!emailReg.test(email)) {
					uni.showToast({
						title: '邮箱格式不正确',
						icon: 'none'
					})
					return false
				}
			}

			return true
		},

	}
}
</script>

<style lang="scss" scoped>
.edit-profile-container {
	min-height: 100vh;
	background: #f5f5f5;
	padding-bottom: 40rpx;
}

.avatar-section {
	background: #fff;
	padding: 60rpx 0;
	margin: 20rpx 30rpx;
	border-radius: 24rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

	.avatar-wrapper {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		border-radius: 50%;
		overflow: hidden;
		background: #f5f5f5;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

		.avatar-image {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		.avatar-overlay {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			height: 60rpx;
			background: rgba(0, 0, 0, 0.5);
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			opacity: 0;
			transition: opacity 0.3s ease;

			.avatar-tip {
				font-size: 20rpx;
				color: #fff;
				margin-top: 4rpx;
			}
		}

		&:active {
			transform: scale(0.98);
		}

		&:hover .avatar-overlay {
			opacity: 1;
		}
	}
}

.form-section {
	margin: 20rpx 30rpx;
	background: #fff;
	border-radius: 24rpx;
	padding: 0 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

	.form-item {
		display: flex;
		align-items: center;
		padding: 32rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
		position: relative;

		&:last-child {
			border-bottom: none;
		}

		.form-label {
			width: 140rpx;
			font-size: 30rpx;
			color: #333;
			font-weight: 500;
		}

		.form-input {
			flex: 1;
			font-size: 30rpx;
			color: #333;
			height: 44rpx;
			line-height: 44rpx;
			padding-right: 60rpx;

			&[disabled] {
				color: #999;
			}
		}

		.form-tip {
			position: absolute;
			right: 0;
			font-size: 24rpx;
			color: #999;
		}
	}
}

.submit-section {
	margin: 40rpx 30rpx;

	.submit-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		color: #fff;
		font-weight: 500;
		box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.35);
		border: none;
		padding: 0;
		margin: 0;

		&:active {
			transform: scale(0.98);
			box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.25);
		}

		&[disabled] {
			opacity: 0.6;
		}
	}
}
</style>
