<!--学员消息管理页面-->
<template>
	<view class="main_box">
		<!-- 自定义导航栏 -->
		<view class="navbar_section">
			<view class="navbar_back" @click="goBack">
				<text class="back_icon">‹</text>
			</view>
			<view class="navbar_title">消息管理</view>
			<view class="navbar_action">
				<view class="mark_all_read" @click="markAllAsRead" v-if="unreadCount > 0">
					<text class="mark_text">全部已读</text>
				</view>
			</view>
		</view>
		
		<!-- 学员信息 -->
		<view class="student_info_section" v-if="studentInfo">
			<view class="student_name">{{ studentInfo.name }}</view>
			<view class="message_stats">
				<text class="stat_item">未读消息：{{ unreadCount }}条</text>
				<text class="stat_item">总消息：{{ messagesList.length }}条</text>
			</view>
		</view>
		
		<!-- 消息类型筛选 -->
		<view class="filter_section">
			<view class="filter_tabs">
				<view 
					v-for="tab in typeTabs" 
					:key="tab.value"
					:class="['filter_tab', activeType === tab.value ? 'active' : '']"
					@click="changeType(tab.value)"
				>
					{{ tab.text }}
					<view class="tab_badge" v-if="tab.count > 0">{{ tab.count }}</view>
				</view>
			</view>
		</view>
		
		<!-- 消息列表 -->
		<view class="messages_section">
			<view v-if="loading" class="loading_section">
				<view class="loading_text">加载中...</view>
			</view>
			
			<view v-else-if="filteredMessages.length === 0" class="empty_section">
				<view class="empty_icon">💬</view>
				<view class="empty_text">暂无消息</view>
				<view class="empty_hint">新消息会在这里显示</view>
			</view>
			
			<view v-else class="messages_list">
				<view 
					v-for="message in filteredMessages" 
					:key="message.id"
					:class="['message_item', !message.is_read ? 'unread' : '']"
					@click="viewMessage(message)"
				>
					<view class="message_header">
						<view class="message_type" :class="message.type">
							{{ getTypeText(message.type) }}
						</view>
						<view class="message_time">{{ formatTime(message.send_time) }}</view>
						<view class="unread_dot" v-if="!message.is_read"></view>
					</view>
					
					<view class="message_content">
						<view class="message_title">{{ message.title }}</view>
						<view class="message_preview">{{ message.content | truncate(50) }}</view>
					</view>
					
					<view class="message_meta" v-if="message.sender_name">
						<text class="sender_name">来自：{{ message.sender_name }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view class="load_more_section" v-if="!loading && hasMore">
			<fui-button 
				background="transparent" 
				color="#666"
				@click="loadMoreMessages"
				:loading="loadingMore"
			>
				{{ loadingMore ? '加载中...' : '加载更多' }}
			</fui-button>
		</view>
		
		<!-- 消息详情弹窗 -->
		<view class="message_popup" v-if="showMessagePopup" @click="closeMessagePopup">
			<view class="popup_content" @click.stop>
				<view class="popup_header">
					<view class="popup_title">消息详情</view>
					<view class="popup_close" @click="closeMessagePopup">×</view>
				</view>
				
				<view class="popup_message_detail" v-if="selectedMessage">
					<view class="detail_header">
						<view class="detail_type" :class="selectedMessage.type">
							{{ getTypeText(selectedMessage.type) }}
						</view>
						<view class="detail_time">{{ formatFullTime(selectedMessage.send_time) }}</view>
					</view>
					
					<view class="detail_title">{{ selectedMessage.title }}</view>
					
					<view class="detail_content">{{ selectedMessage.content }}</view>
					
					<view class="detail_sender" v-if="selectedMessage.sender_name">
						<text class="sender_label">发送人：</text>
						<text class="sender_value">{{ selectedMessage.sender_name }}</text>
					</view>
					
					<view class="detail_attachment" v-if="selectedMessage.attachment_url">
						<fui-button 
							background="#29d3b4" 
							size="small"
							@click="viewAttachment(selectedMessage.attachment_url)"
						>
							查看附件
						</fui-button>
					</view>
				</view>
				
				<view class="popup_actions">
					<fui-button 
						v-if="selectedMessage && selectedMessage.type === 'homework'"
						background="#f39c12" 
						@click="submitHomework"
					>
						提交作业
					</fui-button>
					
					<fui-button 
						v-if="selectedMessage && selectedMessage.type === 'notification'"
						background="#29d3b4" 
						@click="confirmNotification"
					>
						确认已读
					</fui-button>
					
					<fui-button 
						background="#f8f9fa" 
						color="#666"
						@click="closeMessagePopup"
					>
						关闭
					</fui-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import apiRoute from '@/api/apiRoute.js'
	
	export default {
		filters: {
			truncate(text, length) {
				if (!text) return ''
				if (text.length <= length) return text
				return text.substring(0, length) + '...'
			}
		},
		
		data() {
			return {
				studentId: 0,
				studentInfo: {},
				messagesList: [],
				filteredMessages: [],
				loading: false,
				loadingMore: false,
				hasMore: true,
				currentPage: 1,
				activeType: 'all',
				showMessagePopup: false,
				selectedMessage: null,
				typeTabs: [
					{ value: 'all', text: '全部', count: 0 },
					{ value: 'system', text: '系统消息', count: 0 },
					{ value: 'notification', text: '通知公告', count: 0 },
					{ value: 'homework', text: '作业任务', count: 0 },
					{ value: 'feedback', text: '反馈评价', count: 0 },
					{ value: 'reminder', text: '课程提醒', count: 0 }
				]
			}
		},
		
		computed: {
			unreadCount() {
				return this.messagesList.filter(msg => !msg.is_read).length
			}
		},
		
		onLoad(options) {
			this.studentId = parseInt(options.student_id) || 0
			if (this.studentId) {
				this.initPage()
			} else {
				uni.showToast({
					title: '参数错误',
					icon: 'none'
				})
			}
		},
		
		methods: {
			goBack() {
				uni.navigateBack()
			},
			
			async initPage() {
				await this.loadStudentInfo()
				await this.loadMessages()
				this.updateTypeCounts()
			},
			
			async loadStudentInfo() {
				try {
					// 模拟获取学员信息
					const mockStudentInfo = {
						id: this.studentId,
						name: '小明'
					}
					this.studentInfo = mockStudentInfo
				} catch (error) {
					console.error('获取学员信息失败:', error)
				}
			},
			
			async loadMessages() {
				this.loading = true
				try {
					console.log('加载消息列表:', this.studentId)
					
					// 模拟API调用
					// const response = await apiRoute.getStudentMessages({
					//     student_id: this.studentId,
					//     page: this.currentPage,
					//     limit: 10
					// })
					
					// 使用模拟数据
					const mockResponse = {
						code: 1,
						data: {
							list: [
								{
									id: 1,
									type: 'system',
									title: '欢迎加入运动识堂',
									content: '欢迎您的孩子加入我们的运动训练课程！我们将为您的孩子提供专业的体能训练指导，帮助孩子健康成长。课程安排和相关信息会及时通过消息推送给您，请注意查收。',
									sender_name: '系统管理员',
									send_time: '2024-01-15 09:00:00',
									is_read: false,
									attachment_url: ''
								},
								{
									id: 2,
									type: 'notification',
									title: '本周课程安排通知',
									content: '本周课程安排已更新，请及时查看课程表。周三下午16:00-17:00的基础体能训练课程请准时参加，课程地点：训练馆A。如有疑问请联系教练。',
									sender_name: '张教练',
									send_time: '2024-01-14 15:30:00',
									is_read: true,
									attachment_url: ''
								},
								{
									id: 3,
									type: 'homework',
									title: '体能训练作业',
									content: '请完成以下体能训练作业：1. 每天跳绳100个 2. 俯卧撑10个 3. 仰卧起坐15个。请在下次课程前完成并提交训练视频。',
									sender_name: '李教练',
									send_time: '2024-01-13 18:20:00',
									is_read: false,
									attachment_url: '/uploads/homework/homework_guide.pdf'
								},
								{
									id: 4,
									type: 'feedback',
									title: '上次课程反馈',
									content: '您的孩子在上次的基础体能训练中表现优秀，动作标准，学习积极。建议继续加强核心力量训练，可以适当增加训练强度。',
									sender_name: '王教练',
									send_time: '2024-01-12 20:15:00',
									is_read: true,
									attachment_url: ''
								},
								{
									id: 5,
									type: 'reminder',
									title: '明日课程提醒',
									content: '提醒您的孩子明天下午14:00有专项技能训练课程，请准时到达训练馆B。建议提前10分钟到场进行热身准备。',
									sender_name: '系统提醒',
									send_time: '2024-01-11 19:00:00',
									is_read: true,
									attachment_url: ''
								}
							],
							total: 5,
							has_more: false
						}
					}
					
					if (mockResponse.code === 1) {
						const newList = mockResponse.data.list || []
						if (this.currentPage === 1) {
							this.messagesList = newList
						} else {
							this.messagesList = [...this.messagesList, ...newList]
						}
						
						this.hasMore = mockResponse.data.has_more || false
						this.applyTypeFilter()
						console.log('消息数据加载成功:', this.messagesList)
					} else {
						uni.showToast({
							title: mockResponse.msg || '获取消息列表失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取消息列表失败:', error)
					uni.showToast({
						title: '获取消息列表失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
					this.loadingMore = false
				}
			},
			
			async loadMoreMessages() {
				if (this.loadingMore || !this.hasMore) return
				
				this.loadingMore = true
				this.currentPage++
				await this.loadMessages()
			},
			
			changeType(type) {
				this.activeType = type
				this.applyTypeFilter()
			},
			
			applyTypeFilter() {
				if (this.activeType === 'all') {
					this.filteredMessages = [...this.messagesList]
				} else {
					this.filteredMessages = this.messagesList.filter(message => message.type === this.activeType)
				}
			},
			
			updateTypeCounts() {
				const counts = {}
				this.messagesList.forEach(message => {
					counts[message.type] = (counts[message.type] || 0) + 1
				})
				
				this.typeTabs.forEach(tab => {
					if (tab.value === 'all') {
						tab.count = this.messagesList.length
					} else {
						tab.count = counts[tab.value] || 0
					}
				})
			},
			
			getTypeText(type) {
				const typeMap = {
					'system': '系统消息',
					'notification': '通知公告',
					'homework': '作业任务',
					'feedback': '反馈评价',
					'reminder': '课程提醒'
				}
				return typeMap[type] || type
			},
			
			formatTime(timeString) {
				const now = new Date()
				const msgTime = new Date(timeString)
				const diffHours = (now - msgTime) / (1000 * 60 * 60)
				
				if (diffHours < 1) {
					return '刚刚'
				} else if (diffHours < 24) {
					return Math.floor(diffHours) + '小时前'
				} else if (diffHours < 48) {
					return '昨天'
				} else {
					const month = String(msgTime.getMonth() + 1).padStart(2, '0')
					const day = String(msgTime.getDate()).padStart(2, '0')
					return `${month}-${day}`
				}
			},
			
			formatFullTime(timeString) {
				const date = new Date(timeString)
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				const hours = String(date.getHours()).padStart(2, '0')
				const minutes = String(date.getMinutes()).padStart(2, '0')
				return `${year}-${month}-${day} ${hours}:${minutes}`
			},
			
			viewMessage(message) {
				this.selectedMessage = message
				this.showMessagePopup = true
				
				// 标记为已读
				if (!message.is_read) {
					this.markAsRead(message)
				}
			},
			
			closeMessagePopup() {
				this.showMessagePopup = false
				this.selectedMessage = null
			},
			
			async markAsRead(message) {
				try {
					console.log('标记已读:', message.id)
					
					// 模拟API调用
					await new Promise(resolve => setTimeout(resolve, 200))
					
					// 更新本地状态
					const index = this.messagesList.findIndex(msg => msg.id === message.id)
					if (index !== -1) {
						this.messagesList[index].is_read = true
					}
				} catch (error) {
					console.error('标记已读失败:', error)
				}
			},
			
			async markAllAsRead() {
				if (this.unreadCount === 0) {
					uni.showToast({
						title: '暂无未读消息',
						icon: 'none'
					})
					return
				}
				
				try {
					console.log('标记全部已读')
					
					// 模拟API调用
					await new Promise(resolve => setTimeout(resolve, 500))
					
					// 更新本地状态
					this.messagesList.forEach(message => {
						message.is_read = true
					})
					
					uni.showToast({
						title: '已全部标记为已读',
						icon: 'success'
					})
				} catch (error) {
					console.error('标记全部已读失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			},
			
			viewAttachment(attachmentUrl) {
				console.log('查看附件:', attachmentUrl)
				uni.showModal({
					title: '提示',
					content: '附件下载功能开发中',
					showCancel: false
				})
			},
			
			submitHomework() {
				console.log('提交作业')
				uni.showModal({
					title: '提示',
					content: '作业提交功能开发中',
					showCancel: false
				})
			},
			
			confirmNotification() {
				console.log('确认通知')
				this.closeMessagePopup()
				uni.showToast({
					title: '已确认',
					icon: 'success'
				})
			}
		}
	}
</script>

<style lang="less" scoped>
.main_box {
	background: #f8f9fa;
	min-height: 100vh;
}

// 自定义导航栏
.navbar_section {
	display: flex;
	justify-content: space-between;
	align-items: center;
	background: #29D3B4;
	padding: 40rpx 32rpx 20rpx;
	
	// 小程序端适配状态栏
	// #ifdef MP-WEIXIN
	padding-top: 80rpx;
	// #endif
	
	.navbar_back {
		width: 60rpx;
		
		.back_icon {
			color: #fff;
			font-size: 40rpx;
			font-weight: 600;
		}
	}
	
	.navbar_title {
		color: #fff;
		font-size: 32rpx;
		font-weight: 600;
	}
	
	.navbar_action {
		width: 120rpx;
		display: flex;
		justify-content: flex-end;
		
		.mark_all_read {
			background: rgba(255, 255, 255, 0.2);
			padding: 8rpx 16rpx;
			border-radius: 16rpx;
			
			.mark_text {
				color: #fff;
				font-size: 24rpx;
			}
		}
	}
}

// 学员信息
.student_info_section {
	background: #fff;
	padding: 24rpx 32rpx;
	border-bottom: 1px solid #f0f0f0;
	
	.student_name {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 12rpx;
	}
	
	.message_stats {
		display: flex;
		gap: 24rpx;
		
		.stat_item {
			font-size: 24rpx;
			color: #666;
		}
	}
}

// 类型筛选
.filter_section {
	background: #fff;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 24rpx 32rpx;
	
	.filter_tabs {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		
		.filter_tab {
			position: relative;
			padding: 12rpx 24rpx;
			font-size: 26rpx;
			color: #666;
			background: #f8f9fa;
			border-radius: 20rpx;
			
			&.active {
				color: #fff;
				background: #29D3B4;
			}
			
			.tab_badge {
				position: absolute;
				top: -8rpx;
				right: -8rpx;
				background: #ff4757;
				color: #fff;
				font-size: 18rpx;
				padding: 2rpx 8rpx;
				border-radius: 12rpx;
				min-width: 16rpx;
				text-align: center;
			}
		}
	}
}

// 消息列表
.messages_section {
	margin: 0 20rpx;
	
	.loading_section, .empty_section {
		background: #fff;
		border-radius: 16rpx;
		padding: 80rpx 32rpx;
		text-align: center;
		
		.loading_text, .empty_text {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 12rpx;
		}
		
		.empty_icon {
			font-size: 80rpx;
			margin-bottom: 24rpx;
		}
		
		.empty_hint {
			font-size: 24rpx;
			color: #999;
		}
	}
	
	.messages_list {
		.message_item {
			background: #fff;
			border-radius: 16rpx;
			padding: 24rpx;
			margin-bottom: 16rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
			position: relative;
			
			&.unread {
				background: #f8fdff;
				border-left: 4rpx solid #29D3B4;
			}
			
			.message_header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;
				
				.message_type {
					font-size: 22rpx;
					padding: 4rpx 12rpx;
					border-radius: 12rpx;
					
					&.system {
						color: #3498db;
						background: rgba(52, 152, 219, 0.1);
					}
					
					&.notification {
						color: #f39c12;
						background: rgba(243, 156, 18, 0.1);
					}
					
					&.homework {
						color: #e74c3c;
						background: rgba(231, 76, 60, 0.1);
					}
					
					&.feedback {
						color: #27ae60;
						background: rgba(39, 174, 96, 0.1);
					}
					
					&.reminder {
						color: #9b59b6;
						background: rgba(155, 89, 182, 0.1);
					}
				}
				
				.message_time {
					font-size: 22rpx;
					color: #999;
				}
				
				.unread_dot {
					position: absolute;
					top: 20rpx;
					right: 20rpx;
					width: 12rpx;
					height: 12rpx;
					background: #ff4757;
					border-radius: 50%;
				}
			}
			
			.message_content {
				margin-bottom: 12rpx;
				
				.message_title {
					font-size: 28rpx;
					font-weight: 600;
					color: #333;
					margin-bottom: 8rpx;
				}
				
				.message_preview {
					font-size: 24rpx;
					color: #666;
					line-height: 1.4;
				}
			}
			
			.message_meta {
				.sender_name {
					font-size: 22rpx;
					color: #999;
				}
			}
		}
	}
}

// 加载更多
.load_more_section {
	padding: 40rpx 20rpx 80rpx;
}

// 消息详情弹窗
.message_popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 1000;
	
	.popup_content {
		background: #fff;
		border-radius: 16rpx;
		width: 90%;
		max-height: 80vh;
		overflow: hidden;
		
		.popup_header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 32rpx;
			border-bottom: 1px solid #f0f0f0;
			
			.popup_title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}
			
			.popup_close {
				font-size: 48rpx;
				color: #999;
				font-weight: 300;
			}
		}
		
		.popup_message_detail {
			padding: 32rpx;
			max-height: 60vh;
			overflow-y: auto;
			
			.detail_header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				
				.detail_type {
					font-size: 24rpx;
					padding: 6rpx 16rpx;
					border-radius: 16rpx;
					
					&.system {
						color: #3498db;
						background: rgba(52, 152, 219, 0.1);
					}
					
					&.notification {
						color: #f39c12;
						background: rgba(243, 156, 18, 0.1);
					}
					
					&.homework {
						color: #e74c3c;
						background: rgba(231, 76, 60, 0.1);
					}
					
					&.feedback {
						color: #27ae60;
						background: rgba(39, 174, 96, 0.1);
					}
					
					&.reminder {
						color: #9b59b6;
						background: rgba(155, 89, 182, 0.1);
					}
				}
				
				.detail_time {
					font-size: 24rpx;
					color: #999;
				}
			}
			
			.detail_title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
				margin-bottom: 20rpx;
			}
			
			.detail_content {
				font-size: 28rpx;
				color: #666;
				line-height: 1.6;
				margin-bottom: 20rpx;
			}
			
			.detail_sender {
				margin-bottom: 20rpx;
				padding-top: 20rpx;
				border-top: 1px solid #f8f9fa;
				
				.sender_label {
					font-size: 24rpx;
					color: #999;
				}
				
				.sender_value {
					font-size: 24rpx;
					color: #666;
				}
			}
			
			.detail_attachment {
				margin-bottom: 20rpx;
			}
		}
		
		.popup_actions {
			padding: 24rpx 32rpx;
			display: flex;
			gap: 16rpx;
			border-top: 1px solid #f0f0f0;
			
			fui-button {
				flex: 1;
			}
		}
	}
}
</style>