<template>
	<view class="page">
		<scroll-view scroll-y class="page-scroll">
			<common-hero title="我的">

				<view class="hero-content">
					<view class="profile-card">
						<view class="profile-top">
							<image v-if="profile.avatar" class="avatar-image" :src="profile.avatar" mode="aspectFill" />
							<view v-else class="avatar">{{ avatarText }}</view>
							<view class="profile-main">
								<view class="profile-name">{{ displayName }}</view>
								<view class="profile-role">{{ profileRole }}</view>
							</view>
						</view>
						<view class="profile-stats">
							<view v-for="item in stats" :key="item.label" class="profile-stat">
								<view class="profile-stat-value">{{ item.value }}</view>
								<view class="profile-stat-label">{{ item.label }}</view>
							</view>
						</view>
						<view class="logout-btn" @click="handleLogout">退出登录</view>
					</view>
				</view>
			</common-hero>

			<view class="section">
				<view class="section-title">常用入口</view>
				<view class="entry-grid">
					<view
						v-for="item in visibleEntries"
						:key="item.title"
						class="entry-card"
						@click="openEntry(item)"
					>
						<view class="entry-icon">{{ item.icon }}</view>
						<view class="entry-title">{{ item.title }}</view>
						<view class="entry-desc">{{ item.desc }}</view>
					</view>
				</view>
			</view>

			<view class="section">
				<view class="section-title">最近状态</view>
				<view class="status-list">
					<view v-for="item in statusList" :key="item.title" class="status-card" @click="openStatus(item)">
						<view class="status-main">
							<view class="status-name">{{ item.title }}</view>
							<view class="status-desc">{{ item.desc }}</view>
						</view>
						<view class="status-tag">{{ item.tag }}</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import CommonHero from '../../components/common-hero/common-hero.vue'
	import {
		ensureLoggedIn,
		getCurrentUser,
		getLocalProfileOverride,
		getLocalDeclareRecords,
		getManuscriptStatusMeta,
		getReviewStatusMeta,
		getUserProfile,
		listManuscript,
		logout,
		userPageQmgcForm
	} from './service'
	import { hasReviewListAuthority } from '../../utils/gxmu/review-list-service'

	export default {
		components: {
			CommonHero
		},
		data() {
			return {
				profile: {
					nickname: '',
					realName: '',
					username: '',
					avatar: '',
					organizationName: '',
					tenantName: '',
					merchantName: '',
					roles: []
				},
				manuscriptList: [],
				qingmaList: [],
				declareList: [],
				hasReviewListPermission: false,
				entries: [
					{
						title: '用户资料',
						desc: '查看账号信息、组织身份和联系方式。',
						icon: '资',
						route: '/packageMine/profile'
					},
					{
						title: '我的“青马”',
						desc: '管理学员培养计划、考核与成长档案。',
						icon: '青',
						route: '/packageMine/qingma'
					},
					{
						title: '我的稿件',
						desc: '汇总我创建或参与编辑的全部稿件。',
						icon: '稿',
						route: '/packageMine/manuscripts'
					},
					{
						title: '我的申报',
						desc: '查看项目进度、待补材料与审核状态。',
						icon: '报',
						route: '/packageMine/declare'
					},
					{
						title: '审核列表',
						desc: '聚合查看业务数据、审核流并处理待审事项。',
						icon: '审',
						route: '/pages/gxmu/review-list',
						authority: 'gxmu:reviewList:list'
					}
				]
			}
		},
		computed: {
			displayName() {
				return this.profile.nickname || this.profile.realName || this.profile.username || '未登录用户'
			},
			avatarText() {
				return (this.displayName || '我').slice(0, 2)
			},
			profileRole() {
				const roles = Array.isArray(this.profile.roles) ? this.profile.roles : []
				if (roles.length) {
					return roles.map((item) => item.roleName).filter(Boolean).join(' / ')
				}
				return '校级团委数字工作台'
			},
			profileOrg() {
				return this.profile.organizationName || this.profile.merchantName || this.profile.tenantName || '暂无组织信息'
			},
			stats() {
				return [
					{ value: `${this.manuscriptList.length}`, label: '我的稿件' },
					{ value: `${this.declareList.length}`, label: '我的申报' },
					{ value: `${this.qingmaList.length}`, label: '我的“青马”' }
				]
			},
			visibleEntries() {
				return this.entries.filter((item) => {
					if (item.authority === 'gxmu:reviewList:list') {
						return this.hasReviewListPermission
					}
					return true
				})
			},
			statusList() {
				const manuscript = this.manuscriptList[0]
				const qingma = this.qingmaList[0]
				const declare = this.declareList[0]
				return [
					{
						title: '我的申报',
						desc: declare ? `${declare.title}${declare.year ? ` · ${declare.year}` : ''}，上次保存于 ${declare.savedAt || '刚刚'}` : '当前暂无本地申报记录，可前往五四评优页开始填写。',
						tag: declare ? declare.status : '待创建',
						route: '/packageMine/declare'
					},
					{
						title: '我的“青马”',
						desc: qingma ? `${qingma.name || '当前学员'} · ${qingma.schoolInfo || '暂无院系信息'}` : '当前暂无青马记录，可前往申报页查看开放项目。',
						tag: qingma ? getReviewStatusMeta(qingma.reviewList).text : '待处理',
						route: '/packageMine/qingma'
					},
					{
						title: '我的稿件',
						desc: manuscript ? `${manuscript.title || '未命名稿件'} · 最近更新时间 ${manuscript.updateTime || manuscript.createTime || '-'}` : '当前暂无稿件记录，可前往文稿工作台开始创作。',
						tag: manuscript ? getManuscriptStatusMeta(manuscript).text : '待更新',
						route: '/packageMine/manuscripts'
					}
				]
			}
		},
		onShow() {
			if (!ensureLoggedIn({ redirectUrl: '/pages/mine/index' })) {
				return
			}
			this.loadOverview()
		},
		methods: {
			showToast(title) {
				uni.showToast({
					title,
					icon: 'none'
				})
			},
			async loadOverview() {
				const currentUser = getCurrentUser()
				this.hasReviewListPermission = false
				this.profile = {
					...this.profile,
					...currentUser
				}
				const localOverride = getLocalProfileOverride(currentUser.userId)
				if (localOverride.nickname !== undefined) {
					this.profile.nickname = String(localOverride.nickname || '').trim()
				}
				if (localOverride.realName !== undefined) {
					this.profile.realName = String(localOverride.realName || '').trim()
				}
				if (localOverride.sex !== undefined || localOverride.sexName !== undefined) {
					const nextGender = String(localOverride.sexName || localOverride.sex || '').trim()
					this.profile.sex = nextGender
					this.profile.sexName = nextGender
				}
				this.declareList = getLocalDeclareRecords()
				try {
					const [profile, manuscripts, qingmaResult] = await Promise.all([
						getUserProfile().catch(() => null),
						listManuscript().catch(() => []),
						userPageQmgcForm({ page: 1, limit: 5 }).catch(() => ({ list: [] }))
					])
					if (profile) {
						this.profile = {
							...this.profile,
							...profile
						}
						this.hasReviewListPermission = hasReviewListAuthority(profile)
						const latestOverride = getLocalProfileOverride(this.profile.userId || currentUser.userId)
						if (latestOverride.nickname !== undefined) {
							this.profile.nickname = String(latestOverride.nickname || '').trim()
						}
						if (latestOverride.realName !== undefined) {
							this.profile.realName = String(latestOverride.realName || '').trim()
						}
						if (latestOverride.sex !== undefined || latestOverride.sexName !== undefined) {
							const nextGender = String(latestOverride.sexName || latestOverride.sex || '').trim()
							this.profile.sex = nextGender
							this.profile.sexName = nextGender
						}
					}
					const userId = Number(currentUser.userId || this.profile.userId || 0)
					const list = Array.isArray(manuscripts) ? manuscripts : []
					this.manuscriptList = userId ? list.filter((item) => Number(item.userId) === userId) : list
					this.qingmaList = (qingmaResult && qingmaResult.list) || []
				} catch (error) {
					console.warn('mine overview load failed', error)
				}
			},
			handleLogout() {
				uni.showModal({
					title: '提示',
					content: '确认退出当前登录账号？',
					success: ({ confirm }) => {
						if (!confirm) {
							return
						}
						logout()
						this.showToast('已退出登录')
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/index?redirect=%2Fpages%2Fmine%2Findex'
							})
						}, 300)
					}
				})
			},
			openEntry(item) {
				if (item.route) {
					uni.navigateTo({
						url: item.route
					})
					return
				}
				uni.showToast({
					title: `${item.title}待接入`,
					icon: 'none'
				})
			},
			openStatus(item) {
				if (item.route) {
					uni.navigateTo({
						url: item.route
					})
					return
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background: linear-gradient(180deg, #f8fbff 0%, #edf3f8 32%, #f7f7f8 100%);
	}

	.page-scroll {
		height: 100vh;
		padding-bottom: 40rpx;
	}

	.hero-content {
		position: relative;
		z-index: 2;
		padding: 20rpx 24rpx 0;
	}

	.profile-card {
		padding: 34rpx 30rpx;
		border-radius: 32rpx;
		background: linear-gradient(145deg, #0d6fba 0%, #1496f2 58%, #5bc2ff 100%);
		box-shadow: 0 18rpx 40rpx rgba(20, 118, 194, 0.18);
		color: #fff;
	}

	.profile-top {
		display: flex;
		align-items: center;
	}

	.avatar,
	.avatar-image {
		width: 110rpx;
		height: 110rpx;
		border-radius: 32rpx;
		background: rgba(255, 255, 255, 0.16);
	}

	.avatar {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		font-weight: 700;
	}

	.profile-main {
		margin-left: 22rpx;
		flex: 1;
		min-width: 0;
	}

	.profile-name {
		font-size: 38rpx;
		font-weight: 700;
	}

	.profile-role {
		margin-top: 10rpx;
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.84);
	}

	.profile-org {
		margin-top: 8rpx;
		font-size: 22rpx;
		line-height: 1.6;
		color: rgba(255, 255, 255, 0.8);
	}

	.profile-stats {
		display: grid;
		grid-template-columns: repeat(3, minmax(0, 1fr));
		gap: 16rpx;
		margin-top: 28rpx;
	}

	.logout-btn {
		margin-top: 22rpx;
		height: 76rpx;
		border-radius: 22rpx;
		background: rgba(11, 34, 58, 0.18);
		font-size: 24rpx;
		font-weight: 600;
		line-height: 76rpx;
		text-align: center;
		color: #fff;
	}

	.profile-stat {
		padding: 20rpx 16rpx;
		border-radius: 24rpx;
		background: rgba(255, 255, 255, 0.12);
		text-align: center;
	}

	.profile-stat-value {
		font-size: 34rpx;
		font-weight: 700;
	}

	.profile-stat-label {
		margin-top: 8rpx;
		font-size: 22rpx;
		color: rgba(255, 255, 255, 0.82);
	}

	.section {
		margin-top: 30rpx;
		padding: 0 24rpx;
	}

	.section-title {
		padding: 0 6rpx;
		margin-bottom: 18rpx;
		font-size: 34rpx;
		font-weight: 700;
		color: #1f2329;
	}

	.entry-grid {
		display: grid;
		grid-template-columns: repeat(2, minmax(0, 1fr));
		gap: 18rpx;
	}

	.entry-card,
	.status-card {
		background: rgba(255, 255, 255, 0.92);
		border: 1rpx solid rgba(20, 150, 242, 0.08);
		box-shadow: 0 10rpx 28rpx rgba(34, 94, 142, 0.08);
	}

	.entry-card {
		padding: 24rpx;
		border-radius: 28rpx;
	}

	.entry-icon {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 72rpx;
		height: 72rpx;
		border-radius: 22rpx;
		background: rgba(20, 150, 242, 0.1);
		color: #1496f2;
		font-size: 28rpx;
		font-weight: 700;
	}

	.entry-title {
		margin-top: 18rpx;
		font-size: 28rpx;
		font-weight: 700;
		color: #262a31;
	}

	.entry-desc {
		margin-top: 10rpx;
		font-size: 22rpx;
		line-height: 1.6;
		color: #7a706b;
	}

	.status-list {
		display: flex;
		flex-direction: column;
		gap: 18rpx;
	}

	.status-card {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx;
		border-radius: 28rpx;
	}

	.status-main {
		flex: 1;
		padding-right: 20rpx;
	}

	.status-name {
		font-size: 28rpx;
		font-weight: 700;
		color: #23272f;
	}

	.status-desc {
		margin-top: 10rpx;
		font-size: 22rpx;
		line-height: 1.6;
		color: #7c736e;
	}

	.status-tag {
		padding: 12rpx 18rpx;
		border-radius: 999rpx;
		background: #eaf5ff;
		color: #1496f2;
		font-size: 22rpx;
		white-space: nowrap;
	}
</style>
