<template>
	<view class="user-dynamics-page">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<view class="navbar-title">用户动态</view>
			<view class="navbar-right"></view>
		</view>

		<scroll-view 
			scroll-y 
			class="page-content"
			@scrolltolower="loadMore"
			refresher-enabled
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<!-- 动态列表 -->
			<view v-if="loading && dynamicList.length === 0" class="loading-container">
				<text>加载中...</text>
			</view>
			<view v-else-if="dynamicList.length === 0" class="empty-container">
				<text class="empty-icon">📝</text>
				<text class="empty-text">该用户还没有发布动态</text>
			</view>
			<view v-else class="dynamic-list">
				<view 
					v-for="(item, index) in dynamicList" 
					:key="item.dynamicId || index" 
					class="dynamic-card"
					@click="viewDynamicDetail(item)"
				>
					<!-- 动态内容 -->
					<view class="dynamic-content" v-if="item.content">
						<text class="dynamic-text">{{ item.content }}</text>
					</view>
					
					<!-- 动态媒体（照片/视频） -->
					<view class="dynamic-media" v-if="item.mediaUrls && item.mediaUrls.length > 0">
						<view :class="['media-grid', getGridClass(item)]">
							<image 
								v-for="(url, idx) in item.mediaUrls.slice(0, 9)" 
								:key="idx"
								:src="url" 
								class="media-image"
								mode="aspectFill"
								@click.stop="previewMedia(item.mediaUrls, idx)"
							/>
						</view>
					</view>
					
					<!-- 动态信息 -->
					<view class="dynamic-info">
						<text class="dynamic-time">{{ formatTime(item.createdAt) }}</text>
						<view class="dynamic-stats">
							<text class="stat-item">❤️ {{ item.likeCount || 0 }}</text>
							<text class="stat-item">💬 {{ item.commentCount || 0 }}</text>
							<text class="stat-item">⭐ {{ item.favoriteCount || 0 }}</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 加载更多 -->
			<view v-if="loading && dynamicList.length > 0" class="loading-tip">
				<text>加载中...</text>
			</view>
			<view v-if="noMore && dynamicList.length > 0" class="loading-tip">
				<text>没有更多了~</text>
			</view>
		</scroll-view>
	</view>
</template>

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

export default {
	data() {
		return {
			userId: null,
			dynamicList: [],
			loading: false,
			refreshing: false,
			noMore: false,
			pageNum: 1,
			pageSize: 10
		}
	},
	
	onLoad(options) {
		if (options.userId) {
			this.userId = parseInt(options.userId)
			this.loadDynamics()
		} else {
			uni.showToast({
				title: '用户ID无效',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	},
	
	methods: {
		// 加载动态
		async loadDynamics(isRefresh = false) {
			if (this.loading) return
			if (isRefresh) {
				this.pageNum = 1
				this.noMore = false
			}
			
			this.loading = true
			try {
				const currentUserId = uni.getStorageSync('userId')
				const params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					currentUserId: currentUserId ? parseInt(currentUserId) : null
				}
				const result = await api.dynamic.getUserDynamics(this.userId, params)
				console.log('用户动态API返回:', result)
				
				// 处理PageResult格式：{ records: [], total: 0, current: 1, size: 10 }
				let list = []
				
				if (result) {
					// PageResult格式：{ records: [], total: 0 }
					if (result.records && Array.isArray(result.records)) {
						list = result.records
					}
					// 兼容格式：{ list: [], total: 0 }
					else if (result.list && Array.isArray(result.list)) {
						list = result.list
					}
					// 直接是数组
					else if (Array.isArray(result)) {
						list = result
					}
				}
				
				// 处理mediaUrls字段（可能是字符串需要解析）
				list = list.map(item => {
					if (item.mediaUrls && typeof item.mediaUrls === 'string') {
						try {
							item.mediaUrls = JSON.parse(item.mediaUrls)
						} catch (e) {
							console.error('解析mediaUrls失败:', e)
							item.mediaUrls = []
						}
					}
					if (!item.mediaUrls || !Array.isArray(item.mediaUrls)) {
						item.mediaUrls = []
					}
					return item
				})
				
				this.noMore = list.length < this.pageSize
				
				if (isRefresh) {
					this.dynamicList = list
				} else {
					this.dynamicList = [...this.dynamicList, ...list]
				}
				
				if (!this.noMore) {
					this.pageNum++
				}
			} catch (e) {
				console.error('获取用户动态失败:', e)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
				this.refreshing = false
			}
		},
		
		// 加载更多
		loadMore() {
			if (!this.noMore && !this.loading) {
				this.loadDynamics()
			}
		},
		
		// 下拉刷新
		onRefresh() {
			this.refreshing = true
			this.loadDynamics(true)
		},
		
		// 查看动态详情
		viewDynamicDetail(item) {
			uni.navigateTo({
				url: `/pages/plaza/detail?dynamicId=${item.dynamicId}`
			})
		},
		
		// 预览媒体
		previewMedia(urls, index) {
			if (!urls || urls.length === 0) return
			uni.previewImage({
				urls: urls,
				current: index
			})
		},
		
		// 获取网格类名
		getGridClass(item) {
			const count = item.mediaUrls ? item.mediaUrls.length : 0
			if (count === 1) return 'grid-1'
			if (count === 2 || count === 4) return 'grid-2'
			return 'grid-3'
		},
		
		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return ''
			const date = new Date(timeStr)
			const now = new Date()
			const diff = now - date
			const minutes = Math.floor(diff / 60000)
			const hours = Math.floor(diff / 3600000)
			const days = Math.floor(diff / 86400000)
			
			if (minutes < 1) return '刚刚'
			if (minutes < 60) return `${minutes}分钟前`
			if (hours < 24) return `${hours}小时前`
			if (days < 7) return `${days}天前`
			return date.toLocaleDateString()
		},
		
		// 返回
		goBack() {
			uni.navigateBack()
		}
	}
}
</script>

<style lang="scss" scoped>
.user-dynamics-page {
	min-height: 100vh;
	background: #F5F5F5;
	padding-top: 90rpx;
}

/* 自定义导航栏 */
.custom-navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	height: 90rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 20rpx;
	background: #FFFFFF;
	border-bottom: 2rpx solid #E0E0E0;
	z-index: 999;
}

.navbar-left,
.navbar-right {
	width: 80rpx;
}

.back-icon {
	font-size: 40rpx;
	color: #333;
	font-weight: bold;
}

.navbar-title {
	flex: 1;
	text-align: center;
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

/* 页面内容 */
.page-content {
	height: calc(100vh - 90rpx);
	padding: 20rpx;
}

.dynamic-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.dynamic-card {
	background: #FFFFFF;
	border-radius: 16rpx;
	padding: 24rpx;
	border: 2rpx solid #E0E0E0;
}

.dynamic-content {
	margin-bottom: 20rpx;
}

.dynamic-text {
	font-size: 28rpx;
	color: #333;
	line-height: 1.8;
}

.dynamic-media {
	margin-bottom: 20rpx;
}

.media-grid {
	display: grid;
	gap: 12rpx;
}

.grid-1 {
	grid-template-columns: 1fr;
}

.grid-2 {
	grid-template-columns: repeat(2, 1fr);
}

.grid-3 {
	grid-template-columns: repeat(3, 1fr);
}

.media-image {
	width: 100%;
	height: 300rpx;
	border-radius: 12rpx;
	background: #F5F5F5;
}

.dynamic-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-top: 16rpx;
	border-top: 1rpx solid #F0F0F0;
}

.dynamic-time {
	font-size: 24rpx;
	color: #999;
}

.dynamic-stats {
	display: flex;
	gap: 24rpx;
}

.stat-item {
	font-size: 24rpx;
	color: #666;
}

.empty-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 40rpx;
}

.empty-icon {
	font-size: 120rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.loading-container {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 100rpx;
	font-size: 28rpx;
	color: #999;
}

.loading-tip {
	text-align: center;
	padding: 40rpx;
	color: #999;
	font-size: 26rpx;
}
</style>

