<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"
			:scroll-top="scrollTopValue"
			:scroll-with-animation="false"
			@scroll="onScroll"
			@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"
					@tap="viewDynamicDetail(item, index)"
				>
					<!-- 动态内容 -->
					<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"
								/>
							</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,
			scrollTopValue: 0,
			savedScrollTop: 0
		}
	},
	
	onLoad(options) {
		if (options.userId) {
			this.userId = parseInt(options.userId)
			this.loadDynamics()
		} else {
			uni.showToast({
				title: '用户ID无效',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	},
	
	onShow() {
		// 页面显示时恢复滚动位置
		if (this.savedScrollTop > 0) {
			// 使用setTimeout确保DOM已更新
			setTimeout(() => {
				// 先设置一个不同的值，再设置回保存的值，强制触发更新
				this.scrollTopValue = this.savedScrollTop + 1
				setTimeout(() => {
					this.scrollTopValue = this.savedScrollTop
				}, 50)
			}, 100)
		}
	},
	
	onHide() {
		// 页面隐藏时保存滚动位置
		// savedScrollTop 已经在 onScroll 中实时更新
	},
	
	methods: {
		// 监听滚动事件，记录当前滚动位置
		onScroll(e) {
			this.savedScrollTop = e.detail.scrollTop
		},
		// 加载动态
		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)
				
				
				// 处理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 => {
					// 确保 dynamicId 存在
					if (!item.dynamicId && item.id) {
						item.dynamicId = item.id
					}
					if (!item.dynamicId && item.dynamic_id) {
						item.dynamicId = item.dynamic_id
					}
					
					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, index) {
			
			
			// 如果 item 无效，尝试从列表中根据索引获取
			if (!item && typeof index === 'number' && this.dynamicList && this.dynamicList[index]) {
				item = this.dynamicList[index]
				
			}
			
			if (!item) {
				console.error('动态项为空，无法获取')
				uni.showToast({
					title: '动态信息为空',
					icon: 'none'
				})
				return
			}
			
			// 尝试多种可能的字段名
			const dynamicId = item.dynamicId || item.id || item.dynamic_id
		
			
			if (!dynamicId) {
				console.error('动态ID无效，item 内容:', item)
				uni.showToast({
					title: '动态ID无效',
					icon: 'none'
				})
				return
			}
			
			const url = `/pages/plaza/detail?dynamicId=${dynamicId}`
			
			uni.navigateTo({
				url: url,
				success: (res) => {
				
				},
				fail: (err) => {
					console.error('跳转失败:', err)
					uni.showToast({
						title: '跳转失败: ' + (err.errMsg || '未知错误'),
						icon: 'none',
						duration: 2000
					})
				}
			})
		},
		
		// 预览媒体
		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;
	cursor: pointer;
	transition: background-color 0.2s;
	position: relative;
	z-index: 1;
	-webkit-tap-highlight-color: transparent;
}

.dynamic-card:active {
	background: #F8F9FA;
	opacity: 0.8;
}

.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;
	pointer-events: none;
	-webkit-user-select: none;
	user-select: none;
}

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

.comment-stat {
	cursor: pointer;
	transition: opacity 0.2s;
}

.comment-stat:active {
	opacity: 0.6;
}

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

