<template>
	<view class="content">

		<view class="" style="width: 100%; height: 394.95rpx; background-color: aquamarine;">

		</view>

		<view class="column"
			style="width: 684.18rpx; height: 373.01rpx; border-radius: 28rpx; background-color: #F7F7F7; box-shadow: 0 15rpx 15rpx -3rpx rgba(0, 0, 0, 0.1); margin: -195.48rpx auto 0;">

			<!-- 已登录状态 -->
			<view v-if="isLogin && user" class="row" style="align-items: center; margin-top: 35rpx;" @click="goToProfileEdit">
				<image :src="user.avatar || '/static/default_avatar.png'"
					style="width: 129.65rpx; height: 129.65rpx; border-radius: 50%; background-color: #E0E0E0; margin-left: 33rpx;"
					mode="aspectFill"></image>

				<view class="column" style="margin-left: 30rpx;">
					<text style="font-size: 33.91rpx;">{{ user.nickname || '用户' }}</text>
					<text style="font-size: 27.93rpx; color: #4E4E4E;">UID：{{ user.uid || '' }}</text>
				</view>

				<image src="/static/arrow_right.png"
					style="width: 43.88rpx; height: 43.88rpx; margin-left: auto; margin-right: 12rpx;" mode=""></image>
			</view>

			<!-- 未登录状态 -->
			<view v-else class="row" style="align-items: center; margin-top: 35rpx;" @click="handleLogout">
				<image src="/static/default_avatar.png"
					style="width: 129.65rpx; height: 129.65rpx; border-radius: 50%; background-color: #E0E0E0; margin-left: 33rpx;"
					mode="aspectFill"></image>

				<view class="column" style="margin-left: 30rpx;">
					<text style="font-size: 33.91rpx;">点击登录</text>
					<text style="font-size: 27.93rpx; color: #4E4E4E;">登录后查看更多功能</text>
				</view>

				<image src="/static/arrow_right.png"
					style="width: 43.88rpx; height: 43.88rpx; margin-left: auto; margin-right: 12rpx;" mode=""></image>
			</view>


			<view class="stats-row">
				<view class="stats-item" @click="goToMyAppointments('all')">
					<text class="stats-number">{{ isLogin ? appointmentStats.pending : '-' }}</text>
					<text class="stats-label">{{ $t('me.appointment') }}</text>
				</view>
				<view class="stats-divider"></view>
				<view class="stats-item" @click="goToMyAppointments('inProgress')">
					<text class="stats-number">{{ isLogin ? appointmentStats.inProgress : '-' }}</text>
					<text class="stats-label">{{ $t('me.inProgress') }}</text>
				</view>
				<view class="stats-divider"></view>
				<view class="stats-item" @click="goToMyAppointments('completed')">
					<text class="stats-number">{{ isLogin ? appointmentStats.completed : '-' }}</text>
					<text class="stats-label">{{ $t('me.completed') }}</text>
				</view>
			</view>
		</view>

		<text class="section-title">{{ $t('me.general') }}</text>


		<!-- 通知 -->
		<view class="row" style="width: 684.18rpx; align-items: center; margin: 30rpx auto 0;" @click="goToNotification">

			<image src="/static/ic_notice.png" style="width: 55.85rpx; height: 55.85rpx;" mode=""></image>

			<text style="font-size: 27.93rpx; margin-left: 36rpx; flex: 1;">{{ $t('me.notification') }}</text>
			
			<view v-if="unreadCount > 0" class="unread-badge">{{ unreadCount > 99 ? '99+' : unreadCount }}</view>

			<image src="/static/arrow_right2.png" style="width: 31.91rpx; height: 31.91rpx; margin-left: 20rpx;" mode=""></image>
		</view>

		<view class=""
			style="width: 590.46rpx; height: 2rpx; background-color: #EAEAEA; margin-left: auto; margin-right: 36rpx; margin-top: 8rpx;">
		</view>

		<!-- 客服 -->
		<view class="row" style="width: 684.18rpx; align-items: center; margin: 22rpx auto 0;">

			<image src="/static/customer_service.png" style="width: 55.85rpx; height: 55.85rpx;" mode=""></image>

			<text style="font-size: 27.93rpx; margin-left: 36rpx;">{{ $t('me.customerService') }}</text>

			<image src="/static/arrow_right2.png" style="width: 31.91rpx; height: 31.91rpx; margin-left: auto;" mode="">
			</image>
		</view>

		<view class=""
			style="width: 590.46rpx; height: 2rpx; background-color: #EAEAEA; margin-left: auto; margin-right: 36rpx; margin-top: 8rpx;">
		</view>

		<!-- 联系我们 -->
		<view class="row" style="width: 684.18rpx; align-items: center; margin: 22rpx auto 0;" @click="goToContactUs">

			<image src="/static/contact_us.png" style="width: 55.85rpx; height: 55.85rpx;" mode=""></image>

			<text style="font-size: 27.93rpx; margin-left: 36rpx;">{{ $t('me.contactUs') }}</text>

			<image src="/static/arrow_right2.png" style="width: 31.91rpx; height: 31.91rpx; margin-left: auto;" mode="">
			</image>
		</view>

		<view class=""
			style="width: 590.46rpx; height: 2rpx; background-color: #EAEAEA; margin-left: auto; margin-right: 36rpx; margin-top: 8rpx;">
		</view>

		<!-- 邀请新人得奖励 -->
		<view class="row" style="width: 684.18rpx; align-items: center; margin: 22rpx auto 0;" @click="goToInviteReward">

			<image src="/static/invite_new.png" style="width: 55.85rpx; height: 55.85rpx;" mode=""></image>

			<text style="font-size: 27.93rpx; margin-left: 36rpx;">{{ $t('me.inviteReward') }}</text>

			<image src="/static/arrow_right2.png" style="width: 31.91rpx; height: 31.91rpx; margin-left: auto;" mode="">
			</image>
		</view>

		<view class=""
			style="width: 590.46rpx; height: 2rpx; background-color: #EAEAEA; margin-left: auto; margin-right: 36rpx; margin-top: 8rpx;">
		</view>



		<text class="section-title">{{ $t('me.other') }}</text>


		<!-- 语言设置 -->
		<view class="row" style="width: 684.18rpx; align-items: center; margin: 32rpx auto 0;" @click="showLanguagePicker = true">

			<image src="/static/ic_inter.png" style="width: 55.85rpx; height: 55.85rpx;" mode=""></image>

			<text style="font-size: 27.93rpx; margin-left: 36rpx;">{{ $t('me.language') }}</text>

			<text style="font-size: 24rpx; color: #999; margin-left: auto; margin-right: 20rpx;">{{ getCurrentLanguageName() }}</text>

			<image src="/static/arrow_right2.png" style="width: 31.91rpx; height: 31.91rpx;" mode="">
			</image>
		</view>

		<view class=""
			style="width: 590.46rpx; height: 2rpx; background-color: #EAEAEA; margin-left: auto; margin-right: 36rpx; margin-top: 8rpx;">
		</view>

		<!-- 关于 -->
		<view class="row" style="width: 684.18rpx; align-items: center; margin: 32rpx auto 0;" @click="goToAboutUs">

			<image src="/static/ic_about.png" style="width: 55.85rpx; height: 55.85rpx;" mode=""></image>

			<text style="font-size: 27.93rpx; margin-left: 36rpx;">{{ $t('me.about') }}</text>

			<image src="/static/arrow_right2.png" style="width: 31.91rpx; height: 31.91rpx; margin-left: auto;" mode="">
			</image>
		</view>

		<view class=""
			style="width: 590.46rpx; height: 2rpx; background-color: #EAEAEA; margin-left: auto; margin-right: 36rpx; margin-top: 8rpx;">
		</view>

		<!-- 用户协议 -->
		<view class="row" style="width: 684.18rpx; align-items: center; margin: 22rpx auto 0;" @click="goToUserAgreement">

			<image src="/static/ic_agreement2.png" style="width: 55.85rpx; height: 55.85rpx;" mode=""></image>

			<text style="font-size: 27.93rpx; margin-left: 36rpx;">{{ $t('me.userAgreement') }}</text>

			<image src="/static/arrow_right2.png" style="width: 31.91rpx; height: 31.91rpx; margin-left: auto;" mode="">
			</image>
		</view>

		<view class=""
			style="width: 590.46rpx; height: 2rpx; background-color: #EAEAEA; margin-left: auto; margin-right: 36rpx; margin-top: 8rpx;">
		</view>

		<!-- 隐私协议 -->
		<view class="row" style="width: 684.18rpx; align-items: center; margin: 22rpx auto 0;" @click="goToPrivacyPolicy">

			<image src="/static/ic_agreement.png" style="width: 55.85rpx; height: 55.85rpx;" mode=""></image>

			<text style="font-size: 27.93rpx; margin-left: 36rpx;">{{ $t('me.privacyPolicy') }}</text>

			<image src="/static/arrow_right2.png" style="width: 31.91rpx; height: 31.91rpx; margin-left: auto;" mode="">
			</image>
		</view>

		<view class=""
			style="width: 590.46rpx; height: 2rpx; background-color: #EAEAEA; margin-left: auto; margin-right: 36rpx; margin-top: 8rpx;">
		</view>

		<!-- 退出登录/登录 -->
		<view class="row" style="width: 684.18rpx; align-items: center; margin: 22rpx auto 0;" @click="handleLogout">

			<image src="/static/ic_exit.png" style="width: 55.85rpx; height: 55.85rpx;" mode=""></image>

			<text style="font-size: 27.93rpx; margin-left: 36rpx;">{{ isLogin ? $t('me.logout') : '登录' }}</text>

			<image src="/static/arrow_right2.png" style="width: 31.91rpx; height: 31.91rpx; margin-left: auto;" mode="">
			</image>
		</view>

		<view class=""
			style="width: 590.46rpx; height: 2rpx; background-color: #EAEAEA; margin-left: auto; margin-right: 36rpx; margin-top: 8rpx;">
		</view>

		<!-- 语言选择弹窗 -->
		<up-popup :show="showLanguagePicker" @close="showLanguagePicker = false" mode="bottom" border-radius="20">
			<view class="language-picker">
				<view class="picker-header">
					<text class="picker-title">{{ $t('me.language') }}</text>
					<view @click="showLanguagePicker = false" style="padding: 10rpx;">
						<text style="font-size: 28rpx; color: #666;">✕</text>
					</view>
				</view>
				<view class="language-list">
					<view 
						class="language-item" 
						v-for="lang in languages" 
						:key="lang.code"
						@click="changeLanguage(lang.code)"
						:class="{ active: currentLanguage === lang.code }"
					>
						<text class="language-name">{{ lang.name }}</text>
						<text v-if="currentLanguage === lang.code" style="color: #007AFF; font-size: 32rpx;">✓</text>
					</view>
				</view>
			</view>
		</up-popup>


	</view>
</template>

<script>
	import { updateTabBarI18n } from '@/utils/tabbar-i18n.js'
	import { requireAuth, getCurrentUser, isLoggedIn, logout, saveUserInfo } from '@/utils/auth.js'
	import { AppServer } from '@/modules/api/AppServer.js'
	
	export default {
		data() {
			return {
				showLanguagePicker: false,
				languages: [
					{ code: 'zh', name: '中文' },
					{ code: 'en', name: 'English' },
					{ code: 'es', name: 'Español' }
				],
				user: null,
				isLogin: false,
				appointmentStats: {
					pending: 0,
					inProgress: 0,
					completed: 0
				},
				unreadCount: 0
			}
		},
		computed: {
			currentLanguage() {
				return this.$i18n.locale
			}
		},
		onLoad() {
			this.checkLoginStatus()
		},
		onShow() {
			updateTabBarI18n(this)
			this.checkLoginStatus()
			// 如果已登录，从服务器刷新用户信息和预约统计
			if (this.isLogin) {
				this.refreshUserInfo()
				this.fetchAppointmentStats()
				this.fetchUnreadCount()
			}
		},
		methods: {
			/**
			 * 检查登录状态
			 */
			checkLoginStatus() {
				this.isLogin = isLoggedIn()
				if (this.isLogin) {
					this.user = getCurrentUser()
				}
			},
			
			/**
			 * 从服务器刷新用户信息
			 */
			async refreshUserInfo() {
				try {
					const appserver = new AppServer()
					const response = await appserver.GetUserProfile()
					
					if (response.code === 0 && response.data) {
						this.user = response.data
						// 更新本地存储
						saveUserInfo(response.data)
					}
				} catch (error) {
					console.error('刷新用户信息失败:', error)
				}
			},
			
			/**
			 * 获取预约统计数据
			 */
			async fetchAppointmentStats() {
				try {
					const appserver = new AppServer()
					const response = await appserver.GetAppointmentStats()
					
					if (response.code === 0 && response.data) {
						this.appointmentStats = {
							pending: response.data.pending || 0,
							inProgress: response.data.inProgress || 0,
							completed: response.data.completed || 0
						}
					}
				} catch (error) {
					console.error('获取预约统计失败:', error)
				}
			},
			
			/**
			 * 获取未读通知数量
			 */
			async fetchUnreadCount() {
				try {
					const appserver = new AppServer()
					const response = await appserver.GetNotificationUnreadCount()
					
					if (response.code === 0 && response.data) {
						this.unreadCount = response.data.all || 0
						// 更新TabBar红点
						this.updateTabBarBadge()
					}
				} catch (error) {
					console.error('获取未读通知数量失败:', error)
				}
			},
			
			/**
			 * 更新TabBar红点
			 */
			updateTabBarBadge() {
				if (this.unreadCount > 0) {
					uni.setTabBarBadge({
						index: 2,
						text: this.unreadCount > 99 ? '99+' : String(this.unreadCount)
					})
				} else {
					uni.removeTabBarBadge({
						index: 2
					})
				}
			},
			
			getCurrentLanguageName() {
				const current = this.languages.find(lang => lang.code === this.currentLanguage)
				return current ? current.name : '中文'
			},
			
			changeLanguage(langCode) {
				// 如果语言没有变化，直接关闭弹窗
				if (langCode === this.$i18n.locale) {
					this.showLanguagePicker = false
					return
				}
				
				this.$i18n.locale = langCode
				uni.setStorageSync('language', langCode)
				this.showLanguagePicker = false
				
				// 显示切换成功提示
				uni.showToast({
					title: this.$t('common.success'),
					icon: 'success',
					duration: 1000
				})
				
				// 延迟后返回首页并刷新，清除其他页面栈
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}, 1000)
			},
			
			/**
			 * 跳转到个人资料编辑页面（需要登录）
			 */
			goToProfileEdit() {
				if (!requireAuth()) {
					return
				}
				uni.navigateTo({
					url: '/pages/me/profile-edit-page'
				})
			},
			
			/**
			 * 跳转到通知页面（需要登录）
			 */
			goToNotification() {
				if (!requireAuth()) {
					return
				}
				uni.navigateTo({
					url: '/pages/me/notification-page'
				})
			},
			
			/**
			 * 跳转到我的预约页面（需要登录）
			 */
			goToMyAppointments(tab = 'all') {
				if (!requireAuth()) {
					return
				}
				uni.navigateTo({
					url: '/pages/me/my-appointments-page?tab=' + tab
				})
			},
			
			/**
			 * 跳转到联系我们（不需要登录）
			 */
			goToContactUs() {
				uni.navigateTo({
					url: '/pages/me/contact-us-page'
				})
			},
			
			/**
			 * 跳转到邀请奖励页面（需要登录）
			 */
			goToInviteReward() {
				if (!requireAuth()) {
					return
				}
				uni.navigateTo({
					url: '/pages/me/invite-reward-page'
				})
			},
			
			/**
			 * 跳转到关于我们页面（不需要登录）
			 */
			goToAboutUs() {
				uni.navigateTo({
					url: '/pages/me/about-us-page'
				})
			},
			
			/**
			 * 跳转到用户协议页面（不需要登录）
			 */
			goToUserAgreement() {
				uni.navigateTo({
					url: '/pages/me/user-agreement-page'
				})
			},
			
			/**
			 * 跳转到隐私政策页面（不需要登录）
			 */
			goToPrivacyPolicy() {
				uni.navigateTo({
					url: '/pages/me/privacy-policy-page'
				})
			},
			
			/**
			 * 退出登录
			 */
			handleLogout() {
				if (!this.isLogin) {
					// 未登录，跳转到登录页
					uni.navigateTo({
						url: '/pages/login/login-page'
					})
					return
				}
				
				uni.showModal({
					title: this.$t('common.confirm'),
					content: '确定要退出登录吗？',
					success: async (res) => {
						if (res.confirm) {
							await logout()
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		height: 100vh;
		background-color: #F3F4F8;
		flex-direction: column;
	}

	// 分区标题
	.section-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-left: 32rpx;
		margin-top: 36rpx;
		display: block;
	}

		// 统计数据行
	.stats-row {
		display: flex;
		flex-direction: row;
		width: 90%;
		margin: 45rpx auto 0;
		justify-content: space-between;
		align-items: flex-start;
		min-height: 100rpx;
	}
	
	.stats-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-start;
		flex: 1;
		min-width: 0;
		padding: 0 12rpx;
	}
	
	.stats-number {
		font-size: 48rpx;
		font-weight: bold;
		color: #333;
		line-height: 1.2;
	}
	
	.stats-label {
		font-size: 24rpx;
		color: #767676;
		margin-top: 12rpx;
		text-align: center;
		word-wrap: break-word;
		word-break: break-word;
		white-space: normal;
		line-height: 1.4;
		max-width: 100%;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		line-clamp: 2;
		overflow: visible;
	}
	
	.stats-divider {
		width: 1rpx;
		height: 60rpx;
		background-color: #E0E0E0;
		flex-shrink: 0;
		margin: 8rpx 16rpx 0;
	}

	// 未读数量徽章
	.unread-badge {
		min-width: 36rpx;
		height: 36rpx;
		padding: 0 12rpx;
		background-color: #FF3B30;
		border-radius: 18rpx;
		font-size: 22rpx;
		margin-left: auto;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: auto;
		margin-right: 20rpx;
	}

	.language-picker {
		background: white;
		border-radius: 20rpx 20rpx 0 0;
		
		.picker-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 40rpx 30rpx 20rpx;
			border-bottom: 1px solid #f0f0f0;
			
			.picker-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}
		}
		
		.language-list {
			padding: 20rpx 0;
			
			.language-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 30rpx;
				
				&.active {
					background-color: #f8f9fa;
					
					.language-name {
						color: #007AFF;
						font-weight: 500;
					}
				}
				
				.language-name {
					font-size: 32rpx;
					color: #333;
				}
			}
		}
	}
</style>