<template>
	<view class="profile-page">
		<view v-if="loading" class="loading-bar">同步中…</view>
		<!-- 个人信息卡片（只读，数据来自 GET /users/me） -->
		<view class="card">
			<view class="row">
				<text class="label">头像</text>
				<view class="row-right">
					<view class="avatar-wrap">
						<UserAvatar
							:name="user.name"
							:id="user.id"
							:src="user.avatar"
							:size="80"
							unit="rpx"
						/>
					</view>
				</view>
			</view>
			<view class="row">
				<text class="label">姓名</text>
				<view class="row-right">
					<text class="value">{{ user.name || '—' }}</text>
				</view>
			</view>
			<view class="row">
				<text class="label">账号名</text>
				<view class="row-right">
					<text class="value" :class="{ placeholder: !user.alias }">{{ user.alias || '—' }}</text>
				</view>
			</view>
		</view>
		<view class="card">
			<view class="row no-arrow">
				<text class="label">企业</text>
				<text class="value">{{ displayOrg }}</text>
			</view>
		</view>
		<text class="hint">信息由服务端维护，暂不支持在应用内修改。</text>

		<view class="card qr-entry-card">
			<view class="row qr-row" @click="onOpenIdentityQr">
				<text class="label">我的二维码</text>
				<view class="row-right">
					<text class="value sub">身份核验</text>
					<text class="chevron">›</text>
				</view>
			</view>
		</view>

		<view class="logout-section">
			<view
				v-if="isAndroid"
				class="action-btn check-update-btn"
				@click="onCheckUpdate"
			>
				检测更新
			</view>
			<view class="action-btn app-settings-btn" @click="onAppSettings">应用设置</view>
			<view class="action-btn change-pwd-btn" @click="onChangePassword">修改密码</view>
			<view class="action-btn switch-account-btn" @click="onOpenSwitchAccount">切换账号</view>
			<view class="logout-btn" @click="onLogout">退出登录</view>
		</view>
		<text v-if="appVersionLabel" class="version-footer">当前版本 {{ appVersionLabel }}</text>

		<view v-if="accountPickerVisible" class="account-picker-mask" @click="closeAccountPicker">
			<view class="account-picker-sheet" @click.stop>
				<text class="account-picker-title">选择要切换的账号</text>
				<scroll-view scroll-y class="account-picker-list" :show-scrollbar="false">
					<view
						v-for="(item, idx) in accountPickerList"
						:key="idx"
						class="account-picker-item"
						@click="onPickSwitchAccount(item)"
					>
						<text class="account-picker-item-text">{{ savedAccountLabel(item) }}</text>
					</view>
				</scroll-view>
				<view class="account-picker-cancel" @click="closeAccountPicker">
					<text>取消</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import UserAvatar from '../../components/UserAvatar.vue'
	import { getToken, getCurrentUserInfo, normalizeUserPayload, setToken } from '../../utils/api'
	import {
		loadSavedAccounts,
		formatSavedAccountLabel,
		setPendingSwitchAccount
	} from '../../utils/loginAccounts'
	// #ifdef APP-PLUS
	import { manualCheckAndroidApkUpdate } from '../../utils/appUpgrade'
	// #endif

	const USER_KEY = 'current_user'
	const DEFAULT_ORG = '韫珠科技'

	export default {
		components: { UserAvatar },
		data() {
			return {
				isAndroid: false,
				loading: false,
				appVersionLabel: '',
				user: {
					name: '',
					id: '',
					avatar: '',
					alias: '',
					orgName: ''
				},
				accountPickerVisible: false,
				accountPickerList: []
			}
		},
		computed: {
			displayOrg() {
				return this.user.orgName || DEFAULT_ORG
			}
		},
		onLoad() {
			this.applyFromStorage()
			this.refreshAndroidFlag()
			this.refreshAppVersion()
		},
		onShow() {
			this.applyFromStorage()
			this.refreshAndroidFlag()
			this.refreshAppVersion()
			this.refreshFromServer()
		},
		methods: {
			refreshAppVersion() {
				let v = ''
				// #ifdef APP-PLUS
				try {
					if (typeof plus !== 'undefined' && plus.runtime) {
						const name = plus.runtime.version
						if (name) v = String(name)
					}
				} catch (e) {}
				// #endif
				if (!v) {
					try {
						const si = uni.getSystemInfoSync()
						v = String(si.appVersion || si.appWgtVersion || '').trim()
					} catch (e) {}
				}
				this.appVersionLabel = v
			},
			refreshAndroidFlag() {
				// #ifdef APP-PLUS
				try {
					this.isAndroid = uni.getSystemInfoSync().platform === 'android'
				} catch (e) {
					this.isAndroid = false
				}
				// #endif
			},
			applyFromStorage() {
				try {
					const raw = uni.getStorageSync(USER_KEY)
					const u = normalizeUserPayload(raw)
					if (u) {
						this.user = {
							name: u.name,
							id: u.id,
							avatar: u.avatar,
							alias: u.alias,
							orgName: u.orgName || u.org_name || ''
						}
					}
				} catch (e) {}
			},
			async refreshFromServer() {
				const token = getToken()
				if (!token) return
				this.loading = true
				try {
					const me = await getCurrentUserInfo(token)
					const u = normalizeUserPayload(me)
					if (!u) return
					const orgName = u.orgName || u.org_name || DEFAULT_ORG
					this.user = {
						name: u.name,
						id: u.id,
						avatar: u.avatar,
						alias: u.alias,
						orgName
					}
					try {
						const prev = uni.getStorageSync(USER_KEY)
						const base = prev && typeof prev === 'object' ? prev : {}
						uni.setStorageSync(USER_KEY, {
							...base,
							...u,
							orgName,
							org_name: orgName
						})
					} catch (e) {}
				} catch (e) {
					// 网络失败时保留本地/缓存展示
				} finally {
					this.loading = false
				}
			},
			onCheckUpdate() {
				// #ifdef APP-PLUS
				manualCheckAndroidApkUpdate()
				// #endif
			},
			onAppSettings() {
				uni.navigateTo({ url: '/pages/app-settings/index' })
			},
			onChangePassword() {
				uni.navigateTo({ url: '/pages/change-password/index' })
			},
			onOpenIdentityQr() {
				uni.navigateTo({ url: '/pages/identity-qr/index' })
			},
			savedAccountLabel(acc) {
				return formatSavedAccountLabel(acc)
			},
			closeAccountPicker() {
				this.accountPickerVisible = false
			},
			onOpenSwitchAccount() {
				let accounts = loadSavedAccounts().filter((a) => a && a.password)
				if (!accounts.length) {
					uni.showToast({ title: '暂无可切换的已记住密码账号', icon: 'none' })
					return
				}
				try {
					const raw = uni.getStorageSync(USER_KEY)
					const u = normalizeUserPayload(raw)
					const curMobile =
						raw && raw.mobile != null ? String(raw.mobile).trim() : ''
					if (u && u.name && curMobile) {
						accounts = accounts.map((a) =>
							String(a.mobile) === curMobile && !(a.name && String(a.name).trim())
								? { ...a, name: u.name }
								: a
						)
					}
					if (curMobile) {
						accounts = accounts.filter((a) => String(a.mobile).trim() !== curMobile)
					}
				} catch (e) {}
				if (!accounts.length) {
					uni.showToast({ title: '暂无其他已记住密码账号', icon: 'none' })
					return
				}
				this.accountPickerList = accounts
				this.accountPickerVisible = true
			},
			onPickSwitchAccount(acc) {
				this.closeAccountPicker()
				if (!acc || !acc.mobile || !acc.password) return
				setToken('')
				try {
					uni.removeStorageSync(USER_KEY)
				} catch (e) {}
				setPendingSwitchAccount({ mobile: acc.mobile, password: acc.password })
				uni.reLaunch({ url: '/pages/login/index' })
			},
			onLogout() {
				uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (!res.confirm) return
						setToken('')
						try {
							uni.removeStorageSync(USER_KEY)
						} catch (e) {}
						this.user = {
							name: '',
							id: '',
							avatar: '',
							alias: '',
							orgName: ''
						}
						uni.reLaunch({ url: '/pages/login/index' })
					}
				})
			}
		}
	}
</script>

<style scoped>
	.profile-page {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding: 24rpx;
		padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
		box-sizing: border-box;
	}
	.loading-bar {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 16rpx;
		padding-left: 8rpx;
	}
	.card {
		background: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		margin-bottom: 24rpx;
	}
	.row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		min-height: 112rpx;
		padding: 0 32rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	.row:last-child {
		border-bottom: none;
	}
	.row.no-arrow {
		border-bottom: none;
	}
	.qr-entry-card {
		margin-top: 8rpx;
	}
	.qr-row {
		border-bottom: none;
	}
	.value.sub {
		color: #999;
		max-width: 280rpx;
	}
	.chevron {
		font-size: 36rpx;
		color: #ccc;
		line-height: 1;
		margin-left: 8rpx;
		font-weight: 300;
	}
	.label {
		font-size: 30rpx;
		color: #333;
		flex-shrink: 0;
	}
	.row-right {
		display: flex;
		align-items: center;
		gap: 16rpx;
		min-width: 0;
	}
	.value {
		font-size: 28rpx;
		color: #333;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		max-width: 400rpx;
	}
	.value.placeholder {
		color: #999;
	}
	.avatar-wrap {
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.hint {
		display: block;
		font-size: 24rpx;
		color: #999;
		line-height: 1.5;
		padding: 0 16rpx;
	}
	.logout-section {
		margin-top: 48rpx;
		padding: 0 0 24rpx;
		display: flex;
		flex-direction: column;
		gap: 24rpx;
	}
	.action-btn {
		background: #fff;
		border-radius: 16rpx;
		min-height: 96rpx;
		line-height: 96rpx;
		text-align: center;
		font-size: 32rpx;
	}
	.check-update-btn {
		color: #259653;
	}
	.app-settings-btn {
		color: #333;
	}
	.change-pwd-btn {
		color: #333;
	}
	.switch-account-btn {
		color: #259653;
	}
	.logout-btn {
		background: #fff;
		border-radius: 16rpx;
		min-height: 96rpx;
		line-height: 96rpx;
		text-align: center;
		font-size: 32rpx;
		color: #e54d42;
	}
	.version-footer {
		display: block;
		text-align: center;
		margin-top: 40rpx;
		font-size: 24rpx;
		color: #999;
		line-height: 1.5;
		padding: 0 16rpx;
	}

	.account-picker-mask {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.45);
		z-index: 999;
		display: flex;
		align-items: flex-end;
		justify-content: center;
	}
	.account-picker-sheet {
		width: 100%;
		max-height: 70vh;
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding: 24rpx 0 env(safe-area-inset-bottom);
		box-sizing: border-box;
	}
	.account-picker-title {
		display: block;
		text-align: center;
		font-size: 30rpx;
		font-weight: 600;
		color: #222;
		padding: 16rpx 32rpx 24rpx;
	}
	.account-picker-list {
		max-height: 50vh;
		padding: 0 24rpx;
		box-sizing: border-box;
	}
	.account-picker-item {
		padding: 28rpx 24rpx;
		border-bottom: 1rpx solid #eee;
	}
	.account-picker-item:active {
		background: #f7f7f7;
	}
	.account-picker-item-text {
		font-size: 30rpx;
		color: #222;
		line-height: 1.4;
		word-break: break-all;
	}
	.account-picker-cancel {
		margin-top: 16rpx;
		padding: 28rpx;
		text-align: center;
		font-size: 30rpx;
		color: #666;
	}
	.account-picker-cancel:active {
		opacity: 0.7;
	}
</style>
