<template>
	<view class="profile-page">
		<nav-bar title="个人信息" bgColor="#fff" color="#000"></nav-bar>
		
		<view class="form-container" v-if="!loading">
			<view class="avatar-section" @click="handleChooseAvatar">
				<image :src="formData.avatar || '/static/images/profile.png'" class="avatar-img" mode="aspectFill"></image>
				<view class="avatar-tip">点击更换头像</view>
			</view>

			<view class="form-group">
				<view class="form-item">
					<text class="form-label require">用户昵称</text>
					<input class="form-input" v-model="formData.nickName" placeholder="请输入昵称" placeholder-class="input-placeholder" />
				</view>
				<view class="line"></view>

				<view class="form-item">
					<text class="form-label require">手机号码</text>
					<input class="form-input" type="number" v-model="formData.phonenumber" placeholder="请输入手机号码" placeholder-class="input-placeholder" />
				</view>
				<view class="line"></view>

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

				<view class="form-item">
					<text class="form-label">性别</text>
					<picker :range="sexOptions" range-key="label" @change="onSexChange">
						<view class="picker-value" :class="{'placeholder': formData.sex === undefined || formData.sex === ''}">
							{{ getSexLabel }}
						</view>
					</picker>
				</view>
			</view>

			<view class="btn-group">
				<button class="submit-btn" @click="submit">保存修改</button>
			</view>
		</view>
	</view>
</template>

<script setup>
// @Author: Antigravity
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import navBar from '@/components/nav-bar/index.vue'
import { getInfo, updateUserProfile, uploadAvatar } from '@/api/system/user'

const loading = ref(true)
const formData = reactive({
	avatar: '',
	nickName: '',
	phonenumber: '',
	email: '',
	sex: ''
})

const sexOptions = [
	{ label: '男', value: '0' },
	{ label: '女', value: '1' },
	{ label: '未知', value: '2' }
]

onLoad(async () => {
    try {
        const res = await getInfo()
        if (res && res.user) {
            formData.avatar = res.user.avatarUrl || ''
            formData.nickName = res.user.nickName || ''
            formData.phonenumber = res.user.phonenumber || ''
            formData.email = res.user.email || ''
            formData.sex = res.user.sex || '2'
        }
    } catch (e) {
        console.error('获取个人信息失败', e)
        uni.showToast({ title: typeof e === 'string' ? e : '获取个人信息失败', icon: 'none' })
    } finally {
        loading.value = false
    }
})

const getSexLabel = computed(() => {
    const opt = sexOptions.find(o => o.value === String(formData.sex))
    return opt ? opt.label : '请选择'
})

const onSexChange = (e) => {
    formData.sex = sexOptions[e.detail.value].value
}

// 选择并上传头像
const handleChooseAvatar = () => {
    uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
            const tempFilePaths = res.tempFilePaths;
            try {
                uni.showLoading({ title: '上传中...' });
                const uploadRes = await uploadAvatar(tempFilePaths[0]);
                formData.avatar = uploadRes.imgUrl;
                uni.hideLoading();
                uni.showToast({ title: '头像上传成功', icon: 'success' });
            } catch (e) {
                uni.hideLoading();
                console.error('上传头像失败', e);
                uni.showToast({ title: typeof e === 'string' ? e : '上传头像失败', icon: 'none' });
            }
        }
    });
}

const validate = () => {
	if (!formData.nickName || !formData.nickName.trim()) {
		uni.showToast({ title: '请输入昵称', icon: 'none' })
		return false
	}
	if (!formData.phonenumber || !formData.phonenumber.trim()) {
		uni.showToast({ title: '请输入手机号码', icon: 'none' })
		return false
	}
	if (!/^1[3-9]\d{9}$/.test(formData.phonenumber)) {
		uni.showToast({ title: '请输入正确的手机号码', icon: 'none' })
		return false
	}
	if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
		uni.showToast({ title: '请输入正确的邮箱格式', icon: 'none' })
		return false
	}
	return true
}

const submit = async () => {
	if (!validate()) return

	try {
		uni.showLoading({ title: '保存中...' })

		await updateUserProfile(formData)
		
		uni.hideLoading()
		uni.showToast({ title: '个人信息修改成功', icon: 'success' })
		setTimeout(() => {
			uni.navigateBack()
		}, 1000)
	} catch (err) {
		uni.hideLoading()
		console.log('保存失败', err)
		uni.showToast({ title: typeof err === 'string' ? err : '保存失败', icon: 'none' })
	}
}
</script>

<style lang="scss" scoped>
.profile-page {
	min-height: 100vh;
	background-color: #f7f8fa;
}

.form-container {
    padding-top: 0;
}

.avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 60rpx 0;
    background-color: #fff;
    margin-bottom: 20rpx;
    border-bottom: 2rpx solid #f0f0f0;
    .avatar-img {
        width: 160rpx;
        height: 160rpx;
        border-radius: 80rpx;
        background-color: #f7f8fa;
    }
    .avatar-tip {
        margin-top: 20rpx;
        font-size: 24rpx;
        color: #999;
    }
}

.form-group {
	background: #fff;
	margin: 0 24rpx;
	border-radius: 20rpx;
	padding: 0 32rpx;
}

.form-item {
	display: flex;
	align-items: center;
	padding: 24rpx 0;
}

.form-label {
	width: 200rpx;
	font-size: 28rpx;
	color: #333;
	flex-shrink: 0;
	&::before {
		content: '*';
		color: transparent;
		margin-right: 4rpx;
	}
	&.require::before {
		color: #f56c6c;
	}
}

.form-input {
	flex: 1;
	height: 48rpx;
	line-height: 48rpx;
	font-size: 28rpx;
	color: #333;
	text-align: right;
}

.input-placeholder {
	color: #c0c4cc;
	font-size: 28rpx;
}

.line {
	height: 2rpx;
	background: #eee;
	margin: 0;
}

.btn-group {
	margin: 60rpx 32rpx 32rpx;
}

.submit-btn {
	height: 88rpx;
	line-height: 88rpx;
	background: linear-gradient(90deg, #ffd53f, #ff9500);
	color: #fff;
	border: none;
	border-radius: 44rpx;
	font-size: 30rpx;
	font-weight: bold;
	&::after { border: none; }
}

.picker-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    text-align: right;
    height: 48rpx;
    line-height: 48rpx;
    padding-right: 20rpx;
}
.picker-value.placeholder {
    color: #c0c4cc;
}
</style>