<!-- pages/mine/mine.vue -->
<template>
	<view class="mine-container">
		<!-- 顶部用户信息区域 -->
		<view class="user-header ">
			<headerInfo title="个人中心"></headerInfo>
			<view class="user-info-section">
				<view class="avatar-section">
					<u-avatar 
						@click="toUser"
						size="144rpx"
						shape="circle"
						:src="userAvatar"
						mode="aspectFill"
						:show-level="false"
					></u-avatar>
					<view class="user-text-info">
						<view class="user-name-section">
							<view v-if="isLoggedIn">
								<view class="name-section">
									<view class="user-name" @click="toUser">
										{{ displayName }}
									</view>
									<view class="department-badge" v-if="dept">
										{{dept}}
									</view>
								</view>
								
								<view class="user-account">
									账号：{{ userAccount }}
								</view>
							</view>
							<button v-else
								class="login-button"
								open-type="getPhoneNumber"
								@getphonenumber="handleGetPhoneNumber"
								:loading="isLogging"
								:disabled="isLogging || isProcessing"
							>
								{{ loginButtonText }}
							</button>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 菜单功能区域 -->
		<view class="menu-section">
			<view class="menu-card">
				<!-- 订单列表 -->
				<view class="menu-item" @click="toOrderList">
					<view class="menu-item-left">
						<image src="/static/img/mine/icon-mine-order.png" class="menu-icon"></image>
						<text class="menu-text">订单列表</text>
					</view>
					<image src="/static/img/arrow-right.png" class="arrow-icon"></image>
				</view>

				<!-- 地址簿 -->
				<view class="menu-item" @click="toAddressBook">
					<view class="menu-item-left">
						<image src="/static/img/mine/icon-mine-address.png" class="menu-icon"></image>
						<text class="menu-text">地址簿</text>
					</view>
					<image src="/static/img/arrow-right.png" class="arrow-icon"></image>
				</view>
				
				<!-- 到付月结码 -->
				<view class="menu-item" @click="toSettlementCode">
					<view class="menu-item-left">
						<image src="/static/img/mine/icon-mine-qr.png" class="menu-icon"></image>
						<text class="menu-text">到付月结码</text>
					</view>
					<image src="/static/img/arrow-right.png" class="arrow-icon"></image>
				</view>

				<!-- 联系客服 -->
				<view class="menu-item" @click="makePhoneCall">
					<view class="menu-item-left">
						<image src="/static/img/mine/icon-mine-server.png" class="menu-icon"></image>
						<text class="menu-text">联系客服</text>
					</view>
					<image src="/static/img/arrow-right.png" class="arrow-icon"></image>
				</view>

				<!-- 隐私政策 -->
				<view class="menu-item" @click="toPrivacyPolicy">
					<view class="menu-item-left">
						<image src="/static/img/mine/icon-mine-policy.png" class="menu-icon"></image>
						<text class="menu-text">隐私政策</text>
					</view>
					<image src="/static/img/arrow-right.png" class="arrow-icon"></image>
				</view>

				<!-- 关于我们 -->
				<view class="menu-item" @click="toAboutUs">
					<view class="menu-item-left">
						<image src="/static/img/mine/icon-mine-about.png" class="menu-icon"></image>
						<text class="menu-text">关于我们</text>
					</view>
					<image src="/static/img/arrow-right.png" class="arrow-icon"></image>
				</view>

				<!-- 退出登录（仅登录后显示） -->
				<view 
					class="menu-item logout-item" 
					v-if="isLoggedIn"
					@click="userLogoutFn">
					<text class="menu-text logout-text">退出登录</text>
				</view>
			</view>
		</view>
		
		<!-- 加载提示 -->
		<u-loading-page :loading="pageLoading" bg-color="transparent"></u-loading-page>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import headerInfo from "@/components/headerInfo.vue";
import { userLogout } from "@/api/user.js";
import { getAdServicePhone } from "@/api/home.js";
import { checkLoginShowModal, quickLogin } from "@/utils/util.js";
import { onLoad, onShow, onShareAppMessage } from '@dcloudio/uni-app'
import { useAppStore } from "@/stores/app";

const appStore = useAppStore();

// 响应式数据
const isLogging = ref(false);
const isProcessing = ref(false);
const pageLoading = ref(false);
const phoneNumber = ref('');

// 计算属性
const isLoggedIn = computed(() => {
	return !!(appStore.userInfo?.phonenumber && appStore.token);
});

const userAvatar = computed(() => {
	return appStore.userInfo?.avatar || '/static/img/default-avatar.png';
});

const displayName = computed(() => {
	return appStore.userInfo?.nickName || appStore.userInfo?.userName;
});
const dept = computed(() => {
	return appStore.userInfo?.dept?.deptName || "";
});

const userAccount = computed(() => {
	return  appStore.userInfo?.userName || appStore.userInfo?.phonenumber || '';
});

const loginButtonText = computed(() => {
	if (isLogging.value) return '登录中...';
	if (isProcessing.value) return '处理中...';
	return '请点击登录';
});

onShareAppMessage((res) => {
	return appStore.onShareAppMessageObj;
});

onLoad(() => {
	getAdServicePhoneFn();
	// 检查用户登录状态
	checkUserStatus();
});

onShow(() => {
	// 页面显示时检查是否需要重新获取用户信息
	if (appStore.token && !appStore.userInfo?.userPhone) {
		appStore.USERINFO();
	}
});

// 检查用户状态
async function checkUserStatus() {
	if (appStore.token && !appStore.userName) {
		pageLoading.value = true;
		try {
			await appStore.USERINFO();
		} catch (error) {
			console.error('获取用户信息失败:', error);
		} finally {
			pageLoading.value = false;
		}
	}
}

// 获取客服电话
function getAdServicePhoneFn() {
	getAdServicePhone({}).then(res => {
		phoneNumber.value = res.data?.servicePhone || '';
	}).catch(err => {
		console.log(err);
	});
}

// 跳转到用户信息页
async function toUser() {
	if (!await checkLoginShowModal()) return;
	uni.navigateTo({
		url: '/pages/user/user'
	});
}

// 跳转到订单列表
async function toOrderList() {
	if (!await checkLoginShowModal()) return;
	uni.navigateTo({
		url: '/pages/order/index'
	});
}

// 跳转到地址簿
async function toAddressBook() {
	if (!await checkLoginShowModal()) return;
	uni.navigateTo({
		url: '/pages/address/address_list'
	});
}

// 跳转到月结码
async function toSettlementCode() {
	if (!await checkLoginShowModal()) return;
	uni.navigateTo({
		url: '/pages/mine/settlementCode'
	});
}

// 跳转到隐私政策
async function toPrivacyPolicy() {
	uni.navigateTo({
		url: '/pages/webview/webview?url=' + encodeURIComponent('https://your-domain.com/privacy')
	});
}

// 跳转到关于我们
async function toAboutUs() {
	uni.navigateTo({
		url: '/pages/about/index'
	});
}

// 处理获取手机号登录 - 使用优化后的quickLogin
async function handleGetPhoneNumber(e) {
	if (isLogging.value || isProcessing.value) return;
	
	isLogging.value = true;
	isProcessing.value = true;
	
	// 先隐藏loading（如果有）
	uni.hideLoading();
	
	try {
		// 显示加载提示
		uni.showLoading({
			title: '登录中...',
			mask: true
		});
		
		// 调用快速登录，并传入自定义回调
		await quickLogin(e, {
			onSuccess: (result) => {
				console.log('页面登录成功回调:', result);
		        appStore.UPDATE_USERINFO(result.data)
			},
			onFail: (error) => {
				console.log('页面登录失败回调:', error);
				// 页面特定的失败逻辑
				let errorMessage = error.message || '登录失败，请重试';
				
				if (error.type === 'auth_denied') {
					errorMessage = '您拒绝了授权，无法登录';
					// 如果是授权拒绝，可以显示引导重新授权的提示
					uni.showModal({
						title: '提示',
						content: '需要手机号授权才能正常使用，请点击右上角菜单，选择「重新进入小程序」后重新授权',
						showCancel: false,
						confirmText: '知道了'
					});
				} else if (error.type === 'auth_code_missing') {
					errorMessage = '授权信息不完整';
				} else if (error.type === 'login_failed') {
					errorMessage = error.originalError || error.message;
				}
				
				// 只在需要时显示Toast（非授权拒绝的情况）
				if (error.type !== 'auth_denied') {
					uni.showToast({
						title: errorMessage,
						icon: 'none',
						duration: 3000
					});
				}
			},
			redirectUrl: '/pages/mine/mine'
		});
		
	} catch (error) {
		console.error('登录处理异常:', error);
		// 这里是未在onFail中捕获的错误（应该是很少出现的）
		uni.showToast({
			title: error,
			icon: 'none'
		});
	} finally {
		isLogging.value = false;
		isProcessing.value = false;
		// 确保loading被隐藏
		setTimeout(() => {
			uni.hideLoading();
		}, 300);
	}
}

// 拨打电话
const makePhoneCall = () => {
	if (!phoneNumber.value) {
		uni.showToast({
			title: '客服电话暂时无法接通',
			icon: 'none'
		});
		return;
	}
	
	uni.makePhoneCall({
		phoneNumber: phoneNumber.value,
		success: () => {
			console.log('成功唤起拨号界面');
		},
		fail: (err) => {
			console.error('唤起拨号界面失败', err);
			uni.showToast({
				title: '拨号失败',
				icon: 'none'
			});
		}
	});
};

// 退出登录
function userLogoutFn() {
	uni.showModal({
		title: '提示',
		content: '确认要退出登录吗？',
		success: function(res) {
			if (res.confirm) {
				// uni.showLoading({
				// 	title: '正在退出...'
				// });
				appStore.LOGOUT();
				// userLogout({}).then(res => {
				// 	appStore.LOGOUT();
				// 	uni.hideLoading();
				// 	uni.showToast({
				// 		title: '已退出登录',
				// 		icon: 'success'
				// 	});
					
				// 	// 延迟刷新页面状态
				// 	setTimeout(() => {
				// 		uni.$emit('userLogoutSuccess');
				// 	}, 500);
				// }).catch(err => {
				// 	uni.hideLoading();
				// 	uni.showToast({
				// 		title: '退出失败',
				// 		icon: 'none'
				// 	});
				// });
			}
		}
	});
}
</script>

<style lang="less" scoped>
.mine-container {
	height: 100vh;
	background: linear-gradient(135deg, #CFE9FF 0%, #F5F7FA 50.86%);
	position: relative;

	// 用户信息区域
	.user-header {
		padding: 0rpx 24rpx;

		.user-info-section {
			margin-top: 32rpx;
			display: flex;
			flex-direction: column;
			gap: 20rpx;

			.avatar-section {
				display: flex;
				align-items: center;
				min-height: 144rpx; // 添加最小高度防止闪烁

				.user-text-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: center;
					min-height: 144rpx; // 添加最小高度防止闪烁
				}

				.user-name-section {
					margin-left: 16rpx;
					min-height: 100rpx; // 固定高度防止闪烁
					display: flex;
					flex-direction: column;
					justify-content: center;
					
					.name-section {
						width: 530rpx;
						height: 52rpx;
						display: flex;
						align-items: center;
						margin-bottom: 8rpx;
					}
					
					.user-name {
						font-weight: bold;
						font-size: 36rpx;
						color: #333333;
						text-align: center;
						line-height: 1;
						white-space: nowrap; // 强制文本在一行内显示
						overflow: hidden; // 隐藏溢出部分
						text-overflow: ellipsis; // 用省略号代替被隐藏的文本
					}

					.login-button {
						background: transparent;
						font-size: 40rpx;
						font-weight: 600;
						color: #333;
						line-height: 56rpx;
						padding: 0;
						margin: 0;
						text-align: left;
						height: auto;
						min-height: 56rpx;
						display: flex;
						align-items: center;
						justify-content: flex-start;

						&::after {
							border: none;
						}
						
						&[disabled] {
							opacity: 0.7;
						}
					}
				}

				.user-account {
					height: 44rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
					line-height: 44rpx;
					margin-top: 4rpx;
				}
			}

			.department-badge {
				background: #1B64F0;
				border-radius: 8rpx;
				font-size: 24rpx;
				color: #FFFFFF;
				text-align: center;
				margin-left: 8rpx;
				padding: 7rpx 16rpx;
				line-height: 1;
				flex-shrink: 0;
				max-width: 250rpx;
				white-space: nowrap; // 强制文本在一行内显示
				overflow: hidden; // 隐藏溢出部分
				text-overflow: ellipsis; // 用省略号代替被隐藏的文本
			}
		}
	}

	// 菜单区域
	.menu-section {
		padding: 0 20rpx;
		margin-top: 20rpx;

		.menu-card {
			overflow: hidden;
		}

		.menu-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 32rpx;
			background: #FFFFFF;
			border-radius: 24rpx;
			margin-bottom: 20rpx;
			min-height: 112rpx; // 固定高度防止闪烁

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

			.menu-item-left {
				display: flex;
				align-items: center;
				gap: 24rpx;
				flex: 1;
			}

			.menu-icon {
				width: 48rpx;
				height: 48rpx;
				flex-shrink: 0;
			}

			.menu-text {
				font-size: 32rpx;
				font-weight: 500;
				color: #333333;
				line-height: 45rpx;
			}

			.arrow-icon {
				width: 48rpx;
				height: 48rpx;
				opacity: 0.5;
				flex-shrink: 0;
			}

			&.logout-item {
				height: 88rpx;
				background: #F52929;
				border-radius: 32rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				.logout-text {
					font-weight: 400;
					font-size: 32rpx;
					color: #FFFFFF;
					text-align: center;
				}
			}
		}
	}
}

// 动画效果
.menu-item {
	transition: all 0.3s ease;
	opacity: 1;

	&:active {
		background-color: rgba(66, 133, 244, 0.05);
		transform: translateX(8rpx);
	}
	
	&[disabled] {
		opacity: 0.6;
		pointer-events: none;
	}
}

.department-badge {
	transition: all 0.3s ease;

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

// 响应式适配
@media (max-width: 375px) {
	.menu-section {
		padding: 0 20rpx !important;
	}

	.menu-card {
		padding: 0 20rpx !important;
	}

	.menu-text {
		font-size: 30rpx !important;
	}
}

// 防止闪烁的全局样式
view, text, image {
	will-change: auto;
	backface-visibility: hidden;
	-webkit-backface-visibility: hidden;
}
</style>