<!-- 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"
						default-url="/static/img/default-avatar.png"
						></u-avatar>
					
					<!-- <image
						@click="toUser"
						:src="userAvatar"
						mode="aspectFill"
						class="avatar"
					></image> -->
					<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>
							<!-- 修改点：去掉 open-type，改为点击跳转登录页 -->
							<button v-else
								class="login-button"
								@click="goToLogin"
							>
								请点击登录
							</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="toPrivacyPolicy1">
					<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 } from "@/utils/util.js";  // 移除 quickLogin 导入
import { onLoad, onShow, onShareAppMessage } from '@dcloudio/uni-app'
import { useAppStore } from "@/stores/app";

const appStore = useAppStore();

// 响应式数据（移除了 isLogging, isProcessing）
const pageLoading = ref(false);
const phoneNumber = ref('');

// 计算属性
const isLoggedIn = computed(() => {
	return 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 || "";
});

// 修改 userAccount 脱敏展示
const userAccount = computed(() => {
    const raw = appStore.userInfo?.userName || appStore.userInfo?.phonenumber || '';
    if (!raw) return '';
    // 脱敏处理
    if (/^\d{11}$/.test(raw)) {
        // 手机号：前3后4
        return raw.slice(0, 3) + '****' + raw.slice(-4);
    } else {
        // 其他字符串
        if (raw.length <= 4) {
            return raw;
        } else {
            return raw.charAt(0) + '****' + raw.charAt(raw.length - 1);
        }
    }
});

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

onLoad(() => {
	getAdServicePhoneFn();
	checkUserStatus();
});

onShow(() => {
	if (appStore.token) {
		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.contact || '';
	}).catch(err => {
		console.log(err);
	});
}

// 跳转到登录页（新增）
function goToLogin() {
	uni.navigateTo({
		url: '/pages/mine/login'
	});
}

// 跳转到用户信息页（保留原有逻辑）
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?title=用户协议&url=' + encodeURIComponent('https://rjsd.mychery.com/user_agreement.html')
	});
}

// 跳转到隐私政策
async function toPrivacyPolicy1() {
	uni.navigateTo({
		url: '/pages/webView/webView?title=隐私政策&url=' + encodeURIComponent('https://rjsd.mychery.com/privacy_policy.html')
	});
}

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

// 拨打电话
const makePhoneCall = () => {
	if (!phoneNumber.value) {
		uni.showToast({ title: '客服电话暂时无法接通', icon: 'none' });
		return;
	}
	uni.makePhoneCall({ phoneNumber: phoneNumber.value });
};

// 退出登录
function userLogoutFn() {
	uni.showModal({
		title: '提示',
		content: '确认要退出登录吗？',
		success: function(res) {
			if (res.confirm) {
				appStore.LOGOUT();
			}
		}
	});
}
</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;
				
				.avatar {
					width: 144rpx;
					height: 144rpx;
					border-radius: 50%;
				}

				.user-text-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: center;
					min-height: 144rpx;
					overflow: hidden; /* 防止内部内容溢出 */
				}

				.user-name-section {
					margin-left: 16rpx;
					min-height: 100rpx;
					display: flex;
					flex-direction: column;
					justify-content: center;
					width: 100%; /* 确保占满父容器宽度 */
					
					.name-section {
						display: flex;
						align-items: center;
						margin-bottom: 8rpx;
						width: 540rpx;
						overflow: hidden; /* 隐藏超出部分，避免影响布局 */
					}
					
					.user-name {
						min-width: 0; /* 允许截断 */
						font-weight: bold;
						font-size: 36rpx;
						color: #333333;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						line-height: 1;
					}

					.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;
						}
					}
				}

				.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;
				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;

			.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: #FEEAEA;
				border-radius: 32rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				.logout-text {
					font-weight: 400;
					font-size: 32rpx;
					color: #F52929;
					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>