<template>
	<view class="plaza-page">
		<!-- 顶部标题栏 -->
		<view class="header">
			<view class="header-background">
				<view class="feather feather-left">🪶</view>
				<view class="feather feather-right">🪶</view>
			</view>
			<view class="header-content">
				<text class="header-subtitle">两只羽毛</text>
				<text class="header-title">💕 缘分广场</text>
				<text class="header-desc">两只羽毛相遇，编织爱情故事</text>
			</view>
		</view>
		
		<!-- 动态列表 -->
		<scroll-view
			class="dynamic-list"
			scroll-y
			@scrolltolower="loadMore"
			refresher-enabled
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<!-- 列表内容 -->
			<view class="list-content">
				<!-- 动态卡片 -->
				<view 
					v-for="item in dynamicList" 
					:key="item.dynamicId" 
					class="dynamic-card"
					@click="goToDetail(item.dynamicId)"
					@longpress="showReportMenu(item)"
				>
					<!-- 用户信息 -->
					<view class="user-info">
                        <image 
                            :src="getAvatar(item)" 
							class="avatar"
							mode="aspectFill"
						></image>
						<view class="user-details">
                            <text class="nickname">{{ getNickname(item) }}</text>
							<text class="time">{{ formatTime(item.createdAt) }}</text>
						</view>
					</view>
					
					<!-- 动态内容 -->
					<view class="dynamic-content">
						<text class="content-text">{{ item.content }}</text>
					</view>
					
					<!-- 媒体内容（图片） -->
					<view v-if="item.mediaUrls && item.mediaUrls.length > 0" class="media-container">
                        <view 
                            :class="['image-grid', getGridClass(item)]"
                        >
							<image 
								v-for="(url, index) in item.mediaUrls.slice(0, 9)" 
								:key="index"
								:src="url" 
								class="media-image"
								mode="aspectFill"
								@click.stop="previewImage(item.mediaUrls, index)"
							></image>
						</view>
					</view>
					
					<!-- 互动栏 -->
					<view class="action-bar">
						<view class="action-item" @click.stop="handleLike(item)">
							<text :class="['icon', item.isLiked ? 'icon-liked' : '']">
								{{ item.isLiked ? '❤️' : '🤍' }}
							</text>
							<text class="action-text">{{ item.likeCount || 0 }}</text>
						</view>
						
						<view class="action-item">
							<text class="icon">💬</text>
							<text class="action-text">{{ item.commentCount || 0 }}</text>
						</view>
						
						<view class="action-item" @click.stop="handleFavorite(item)">
							<text :class="['icon', item.isFavorited ? 'icon-favorited' : '']">
								{{ item.isFavorited ? '⭐' : '☆' }}
							</text>
							<text class="action-text">{{ item.favoriteCount || 0 }}</text>
						</view>
					</view>
				</view>
				
				<!-- 加载提示 -->
				<view class="loading-tip" v-if="loading">
					<text>加载中...</text>
				</view>
				
				<!-- 没有更多数据 -->
				<view class="loading-tip" v-if="noMore && dynamicList.length > 0">
					<text>没有更多了~</text>
				</view>
				
				<!-- 空状态 -->
				<view class="empty-state" v-if="!loading && dynamicList.length === 0">
					<view class="empty-feathers">
						<text class="feather-icon">🪶</text>
						<text class="feather-icon">🪶</text>
					</view>
				<text class="empty-text">还没有缘分动态</text>
				<text class="empty-hint">快来分享你的美好时光，遇见有趣的灵魂吧～</text>
					<view class="empty-action" @click="goToPublish">
						<text>💕 发布第一条动态</text>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 发布按钮 -->
		<view class="publish-btn" @click="goToPublish">
			<view class="publish-bg">
				<text class="publish-icon">💕</text>
				<text class="publish-text">分享心动</text>
			</view>
		</view>
		
		<!-- 举报菜单弹窗 -->
		<view v-if="showMenu" class="report-menu-popup">
			<view class="menu-mask" @click="hideReportMenu"></view>
			<view class="menu-content">
				<view class="menu-item" @click="handleReport">
					<text class="menu-icon">🚩</text>
					<text class="menu-text">举报此动态</text>
				</view>
				<view class="menu-item cancel" @click="hideReportMenu">
					<text class="menu-text">取消</text>
				</view>
			</view>
		</view>
		
		<!-- 底部导航栏 -->
		<view class="tabbar">
			<view class="tabbar-item" @click="switchTab('index')">
				<text class="tabbar-icon">🏠</text>
				<text class="tabbar-text">首页</text>
			</view>
			<view class="tabbar-item active" @click="switchTab('plaza')">
				<text class="tabbar-icon">💕</text>
				<text class="tabbar-text">动态</text>
			</view>
			<view class="tabbar-item" @click="switchTab('recommend')">
				<text class="tabbar-icon">👍</text>
				<text class="tabbar-text">推荐</text>
			</view>
			<view class="tabbar-item" @click="switchTab('message')">
				<text class="tabbar-icon">💬</text>
				<text class="tabbar-text">消息</text>
				<view v-if="unreadCount > 0" class="tabbar-badge">{{ unreadCount }}</view>
			</view>
			<view class="tabbar-item" @click="switchTab('mine')">
				<text class="tabbar-icon">👤</text>
				<text class="tabbar-text">我的</text>
			</view>
		</view>
	</view>
</template>

<script>
import api from '@/utils/api.js'

export default {
	data() {
		return {
			dynamicList: [],
			pageNum: 1,
			pageSize: 10,
			loading: false,
			refreshing: false,
			noMore: false,
			showMenu: false, // 显示举报菜单
			selectedDynamic: null, // 选中的动态
			currentUserId: 1, // 当前用户ID，实际应从存储获取
			defaultAvatar: 'https://via.placeholder.com/100x100.png?text=头像',
			likingMap: {},  // 记录正在点赞的动态ID，防止重复点击
			favoritingMap: {}  // 记录正在收藏的动态ID，防止重复点击
		}
	},
	computed: {
    unreadCount() {
      return this.$store.getters.getTotalUnread || 0;
    }
  },
	onLoad() {
		this.loadDynamicList()
		// 监听详情页更新事件，实时同步点赞/收藏状态
		uni.$on('dynamic-updated', (payload) => {
			if (!payload || !payload.dynamicId) return
			const idx = this.dynamicList.findIndex(x => x.dynamicId === payload.dynamicId)
			if (idx !== -1) {
				const item = this.dynamicList[idx]
				if (payload.hasOwnProperty('isLiked')) item.isLiked = payload.isLiked
				if (payload.hasOwnProperty('likeCount')) item.likeCount = payload.likeCount
				if (payload.hasOwnProperty('isFavorited')) item.isFavorited = payload.isFavorited
				if (payload.hasOwnProperty('favoriteCount')) item.favoriteCount = payload.favoriteCount
				this.$set(this.dynamicList, idx, item)
			}
		})
		// 监听发布页插入新动态
		uni.$on('dynamic-insert', (d) => {
			if (!d) return
			// 仅在第一页顶部插入
			this.dynamicList = [d, ...this.dynamicList]
		})
	},
	
	onShow() {
		// 返回列表页时自动刷新，确保状态一致
		this.pageNum = 1
		this.noMore = false
		this.dynamicList = []
		this.loadDynamicList()
	},
	
	methods: {
        // 兼容WXML：获取头像
        getAvatar(item) {
            if (item && item.user && item.user.avatarUrl) {
                return item.user.avatarUrl
            }
            return this.defaultAvatar
        },
        // 兼容WXML：获取昵称
        getNickname(item) {
            if (item && item.user && item.user.nickname) {
                return item.user.nickname
            }
            return '匿名用户'
        },
        // 兼容WXML：图片栅格class
        getGridClass(item) {
            const len = (item && item.mediaUrls && item.mediaUrls.length) ? item.mediaUrls.length : 0
            const n = Math.min(len, 3)
            return 'grid-' + n
        },
		// 加载动态列表
		async loadDynamicList() {
			if (this.loading || this.noMore) return
			
			this.loading = true
			
			try {
				const res = await api.dynamic.getRecommendList({
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					userId: this.currentUserId
				})
				
				if (res && res.records) {
					// 处理数据
					const newData = res.records.map(item => ({
						...item,
						isLiked: item.isLiked || false,
						isFavorited: item.isFavorited || false
					}))
					
					if (this.pageNum === 1) {
						this.dynamicList = newData
					} else {
						this.dynamicList = [...this.dynamicList, ...newData]
					}
					
					// 判断是否还有更多数据
					if (res.current >= res.pages) {
						this.noMore = true
					} else {
						this.pageNum++
					}
				}
			} catch (error) {
				console.error('加载动态列表失败：', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
				this.refreshing = false
			}
		},
		
		// 下拉刷新
		onRefresh() {
			this.refreshing = true
			this.pageNum = 1
			this.noMore = false
			this.dynamicList = []
			this.loadDynamicList()
		},
		
		// 上拉加载更多
		loadMore() {
			if (!this.noMore && !this.loading) {
				this.loadDynamicList()
			}
		},
		
		// 处理点赞
		async handleLike(item) {
			// 防止重复点击：如果正在处理该动态的点赞请求，直接返回
			if (this.likingMap[item.dynamicId]) {
				return
			}
			
			try {
				// 标记为正在处理
				this.$set(this.likingMap, item.dynamicId, true)
				
				const isLiked = item.isLiked
				const originalCount = item.likeCount || 0
				
				// 立即更新UI（乐观更新）
				item.isLiked = !isLiked
				item.likeCount = isLiked ? Math.max(0, originalCount - 1) : originalCount + 1
				
				// 发送请求
                if (isLiked) {
					// 取消点赞
					await api.dynamic.unlike(item.dynamicId)
				} else {
					// 点赞
					await api.dynamic.like(item.dynamicId)
				}
			} catch (error) {
				console.error('点赞操作失败：', error)
				// 请求失败，恢复原状态
				item.isLiked = !item.isLiked
				item.likeCount = item.isLiked ? (item.likeCount || 0) + 1 : Math.max(0, (item.likeCount || 0) - 1)
				uni.showToast({
					title: '操作失败，请重试',
					icon: 'none'
				})
			} finally {
				// 延迟300毫秒后释放锁，防止快速点击
				setTimeout(() => {
					this.$set(this.likingMap, item.dynamicId, false)
				}, 300)
			}
		},
		
		// 处理收藏
		async handleFavorite(item) {
			// 防止重复点击：如果正在处理该动态的收藏请求，直接返回
			if (this.favoritingMap[item.dynamicId]) {
				return
			}
			
			try {
				// 标记为正在处理
				this.$set(this.favoritingMap, item.dynamicId, true)
				
				const isFavorited = item.isFavorited
				const originalCount = item.favoriteCount || 0
				
				// 立即更新UI（乐观更新）
				item.isFavorited = !isFavorited
				item.favoriteCount = isFavorited ? Math.max(0, originalCount - 1) : originalCount + 1
				
                if (isFavorited) {
					// 取消收藏
                    await api.dynamic.unfavorite(item.dynamicId)
				} else {
					// 收藏
					await api.dynamic.favorite(item.dynamicId)
					uni.showToast({
						title: '收藏成功',
						icon: 'success'
					})
				}
			} catch (error) {
				console.error('收藏操作失败：', error)
				// 请求失败，恢复原状态
				item.isFavorited = !item.isFavorited
				item.favoriteCount = item.isFavorited ? (item.favoriteCount || 0) + 1 : Math.max(0, (item.favoriteCount || 0) - 1)
				uni.showToast({
					title: '操作失败，请重试',
					icon: 'none'
				})
			} finally {
				// 延迟300毫秒后释放锁，防止快速点击
				setTimeout(() => {
					this.$set(this.favoritingMap, item.dynamicId, false)
				}, 300)
			}
		},
		
		// 预览图片
		previewImage(urls, current) {
			uni.previewImage({
				urls: urls,
				current: current
			})
		},
		
		// 跳转到详情页
		goToDetail(dynamicId) {
			uni.navigateTo({
				url: `/pages/plaza/detail?id=${dynamicId}`
			})
		},
		
		// 跳转到发布页
		goToPublish() {
			uni.navigateTo({
				url: '/pages/plaza/publish'
			})
		},
		
		// 显示举报菜单
		showReportMenu(item) {
			// 震动反馈
			uni.vibrateShort({
				type: 'light'
			})
			this.selectedDynamic = item
			this.showMenu = true
		},
		
		// 隐藏举报菜单
		hideReportMenu() {
			this.showMenu = false
			this.selectedDynamic = null
		},
		
		// 处理举报
		handleReport() {
			this.hideReportMenu()
			if (!this.selectedDynamic || !this.selectedDynamic.dynamicId) {
				uni.showToast({
					title: '动态ID不存在',
					icon: 'none'
				})
				return
			}
			// 跳转到举报页面
			uni.navigateTo({
				url: `/pages/plaza/report?id=${this.selectedDynamic.dynamicId}`
			})
		},
		
		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return ''
			
			const time = new Date(timeStr)
			const now = new Date()
			const diff = now - time
			
			// 1分钟内
			if (diff < 60000) {
				return '刚刚'
			}
			// 1小时内
			if (diff < 3600000) {
				return Math.floor(diff / 60000) + '分钟前'
			}
			// 24小时内
			if (diff < 86400000) {
				return Math.floor(diff / 3600000) + '小时前'
			}
			// 7天内
			if (diff < 604800000) {
				return Math.floor(diff / 86400000) + '天前'
			}
			
			// 超过7天显示日期
			const year = time.getFullYear()
			const month = String(time.getMonth() + 1).padStart(2, '0')
			const day = String(time.getDate()).padStart(2, '0')
			
			if (year === now.getFullYear()) {
				return `${month}-${day}`
			}
			return `${year}-${month}-${day}`
		},
		
		// 切换Tab
		switchTab(tab) {
			if (tab === 'plaza') return
			
			const tabPages = {
				index: '/pages/index/index',
				recommend: '/pages/recommend/index',
				message: '/pages/message/index',
				mine: '/pages/mine/index'
			}
			
			if (tabPages[tab]) {
				uni.redirectTo({
					url: tabPages[tab]
				})
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.plaza-page {
    min-height: 100vh;
    background: #FFF0F5; // 淡淡粉色背景
	
	// 顶部标题栏
    .header {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: 88rpx; // 更紧凑，减小头部占用
        background: transparent; // 移除重色背景，突出可爱风淡粉
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
        padding-top: 0; // 移除顶部安全区额外留白
		z-index: 999;
        box-shadow: none;
        overflow: visible;
        position: relative;
		
            .header-background { display: none; }
		
		.header-content {
			text-align: center;
			z-index: 1;
			
            .header-subtitle {
                font-size: 22rpx;
                color: #E91E63;
				display: block;
				margin-bottom: 8rpx;
				letter-spacing: 2rpx;
			}
			
			.header-title {
				font-size: 36rpx;
				font-weight: 700;
                color: #D81B60;
                text-shadow: none;
				display: block;
                margin-bottom: 2rpx; // 缩小标题与描述间距
			}
			
			.header-desc {
				font-size: 20rpx;
                color: #AD1457;
				display: block;
				letter-spacing: 1rpx;
			}
		}
	}
	
	// 动态列表
    .dynamic-list {
        margin-top: 88rpx; // 同步减少顶部外边距
		padding-bottom: 120rpx;
        height: calc(100vh - 88rpx);
		
        .list-content {
            padding: 12rpx; // 再收紧列表内边距
        }
		
		// 动态卡片
        .dynamic-card {
            background: #FFFFFF; // 纯白卡片
            border-radius: 20rpx;
            padding: 24rpx; // 收紧卡片内边距
            margin-bottom: 14rpx; // 卡片之间更紧凑
            box-shadow: 0 4rpx 12rpx rgba(233, 30, 99, 0.07);
            border: 1rpx solid rgba(255, 182, 193, 0.22);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
			
			// 用户信息
			.user-info {
				display: flex;
				align-items: center;
				margin-bottom: 24rpx;
				
				.avatar {
					width: 88rpx;
					height: 88rpx;
					border-radius: 50%;
					margin-right: 24rpx;
					border: 3rpx solid #FFB3BA;
					box-shadow: 0 4rpx 12rpx rgba(233, 30, 99, 0.2);
				}
				
				.user-details {
					flex: 1;
					
					.nickname {
						display: block;
						font-size: 30rpx;
						font-weight: 600;
						color: #2D1B69;
						margin-bottom: 8rpx;
					}
					
					.time {
						font-size: 24rpx;
						color: #8B5A96;
						opacity: 0.8;
					}
				}
			}
			
			// 动态内容
			.dynamic-content {
				margin-bottom: 20rpx;
				
				.content-text {
					font-size: 28rpx;
					line-height: 1.6;
					color: #333333;
					word-wrap: break-word;
				}
			}
			
			// 媒体容器
            .media-container {
                margin-bottom: 16rpx;
				
				.image-grid {
					display: grid;
					gap: 10rpx;
					
					&.grid-1 {
						grid-template-columns: 1fr;
						
						.media-image {
							height: 400rpx;
							border-radius: 12rpx;
						}
					}
					
					&.grid-2,
					&.grid-3 {
						grid-template-columns: repeat(3, 1fr);
						
						.media-image {
							height: 180rpx;
							border-radius: 12rpx;
						}
					}
					
					.media-image {
						width: 100%;
						background-color: #F5F5F5;
					}
				}
			}
			
			// 互动栏
			.action-bar {
				display: flex;
				align-items: center;
				padding-top: 20rpx;
				border-top: 1rpx solid #F5F5F5;
				
				.action-item {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: center;
					
					.icon {
						font-size: 40rpx;
						margin-right: 8rpx;
						
						&.icon-liked {
							animation: heartBeat 0.3s ease-in-out;
						}
						
						&.icon-favorited {
							animation: starShine 0.3s ease-in-out;
						}
					}
					
					.action-text {
						font-size: 24rpx;
						color: #666666;
					}
				}
			}
		}
		
		// 加载提示
		.loading-tip {
			text-align: center;
			padding: 40rpx 0;
			font-size: 24rpx;
			color: #999999;
		}
		
		// 空状态
		.empty-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 200rpx 60rpx;
			
			.empty-icon {
				font-size: 120rpx;
				margin-bottom: 30rpx;
			}
			
			.empty-text {
				font-size: 32rpx;
				color: #333333;
				margin-bottom: 16rpx;
			}
			
			.empty-hint {
				font-size: 24rpx;
				color: #999999;
			}
		}
	}
	
	// 发布按钮
	.publish-btn {
		position: fixed;
		bottom: 160rpx;
		right: 40rpx;
		z-index: 998;
		
		.publish-bg {
			width: 140rpx;
			height: 140rpx;
			background: linear-gradient(135deg, #FF6B9D 0%, #E91E63 25%, #C2185B 50%, #FF8A95 75%, #FFB3BA 100%);
			border-radius: 50%;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			box-shadow: 0 12rpx 36rpx rgba(233, 30, 99, 0.5);
			transition: all 0.3s ease;
			border: 4rpx solid rgba(255, 255, 255, 0.8);
			animation: pulse-love 3s ease-in-out infinite;
			
			&:active {
				transform: scale(0.9);
			}
			
			.publish-icon {
				font-size: 42rpx;
				margin-bottom: 4rpx;
			}
			
			.publish-text {
				font-size: 18rpx;
				color: rgba(255, 255, 255, 0.9);
				font-weight: 500;
				letter-spacing: 1rpx;
			}
		}
	}
	
	// 举报菜单弹窗
	.report-menu-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 9998;
		
		.menu-mask {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: rgba(0, 0, 0, 0.5);
		}
		
		.menu-content {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #FFFFFF;
			border-radius: 30rpx 30rpx 0 0;
			padding: 20rpx 30rpx;
			padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
			padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
			animation: slideUp 0.3s ease;
			
			.menu-item {
				height: 100rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 12rpx;
				margin-bottom: 16rpx;
				transition: background-color 0.3s ease;
				
				&:not(.cancel) {
					background: #FFF5F7;
					
					&:active {
						background: #FFE8EC;
					}
				}
				
				&.cancel {
					background: #F5F5F5;
					margin-top: 8rpx;
					
					&:active {
						background: #EEEEEE;
					}
				}
				
				.menu-icon {
					font-size: 36rpx;
					margin-right: 12rpx;
				}
				
				.menu-text {
					font-size: 30rpx;
					color: #333333;
					font-weight: 500;
				}
			}
		}
	}
	
	// 底部导航栏
	.tabbar {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			display: flex;
			background-color: #FFFFFF;
			border-top: 1rpx solid #F0F0F0;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
			z-index: 999;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	
			.tabbar-item {
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 15rpx 0;
				position: relative;
	
				.tabbar-icon {
					font-size: 44rpx;
					margin-bottom: 5rpx;
				}
	
				.tabbar-text {
					font-size: 22rpx;
					color: #666666;
				}
	
				&.active {
					.tabbar-text {
						color: #E91E63;
						font-weight: bold;
					}
				}
			}
		}
}

// 动画
@keyframes heartBeat {
	0%, 100% {
		transform: scale(1);
	}
	50% {
		transform: scale(1.2);
	}
}

@keyframes starShine {
	0%, 100% {
		transform: scale(1) rotate(0deg);
	}
	50% {
		transform: scale(1.2) rotate(15deg);
	}
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}

.tabbar-badge {
      position: absolute;
      top: 8rpx;
      right: 50%;
      margin-right: -40rpx;
      min-width: 32rpx;
      height: 32rpx;
      line-height: 32rpx;
      padding: 0 6rpx;
      background-color: #FA5151;
      border-radius: 16rpx;
      font-size: 20rpx;
      color: #FFFFFF;
      text-align: center;
    }
</style>
