<template>
	<view class="my-activities-page">
		<!-- 标签页切换 -->
		<view class="tabs">
			<view class="tab-item" :class="{ active: currentTab === 'registered' }" @click="switchTab('registered')">
				<text class="tab-text">我的活动</text>
				<view class="tab-badge" v-if="registeredCount > 0">{{ registeredCount }}</view>
			</view>
			<view class="tab-item" :class="{ active: currentTab === 'joined' }" @click="switchTab('joined')">
				<text class="tab-text">我的课程</text>
				<view class="tab-badge" v-if="purchasedCourses.length > 0">{{ purchasedCourses.length }}</view>
			</view>
		</view>
		
		<!-- 活动/课程列表 -->
		<view class="activities-list">
			<!-- 活动卡片 -->
			<view class="activity-card" v-for="item in registeredActivities" :key="`activity-${item.id}`" @click="goToActivityDetail(item.activityId)" v-if="currentTab === 'registered'">
				<image :src="item.coverImage" class="activity-cover" mode="aspectFill"></image>
				<view class="activity-info">
					<view class="activity-header">
						<text class="activity-name">{{ item.name }}</text>
						<!-- 修复：改用数组+字符串拼接的合法 :class 格式 -->
						<view class="status-tag" :class="['status-' + getStatusType(item.status)]">{{ getStatusText(item.status) }}</view>
					</view>
					
					<view class="activity-meta activity-meta--activity">
						<view class="meta-item">
							<text class="meta-icon">📅</text>
							<text class="meta-text">{{ formatDate(item.startTime) }}</text>
						</view>
						<view class="meta-item" v-if="item.location">
							<text class="meta-icon">📍</text>
							<text class="meta-text">{{ item.location }}</text>
						</view>
						<view class="meta-item">
							<text class="meta-icon">👥</text>
							<text class="meta-text">{{ item.actualParticipants }}/{{ item.maxParticipants }}人</text>
						</view>
					</view>
					
					<view class="activity-footer">
						<text class="activity-price">¥{{ item.price || 0 }}</text>
						<view class="activity-actions">
							<button class="action-btn primary" size="mini" @click.stop="goToActivityDetail(item.activityId,item)">查看详情</button>
							<!-- <button class="action-btn cancel" size="mini" @click.stop="cancelActivity(item)" v-if="item.status === 1">取消报名</button> -->
						</view>
					</view>
				</view>
			</view>
			
			<!-- 课程卡片 -->
			<view class="course-card" v-for="item in purchasedCourses" :key="`course-${item.id}`" @click="goToDetail(item.id,item)" v-if="currentTab === 'joined'">
				<image :src="item.cover_image" class="course-cover" mode="aspectFill"></image>
				<view class="course-info">
					<view class="course-header">
						<text class="course-name">{{ item.name }}</text>
						<view class="course-rating" v-if="item.rating">
							<text class="meta-icon">⭐</text>
							<text class="rating-text">{{ item.rating }}</text>
						</view>
					</view>
					
					<view class="course-meta">
						<view class="meta-item">
							<text class="meta-icon">👤</text>
							<text class="meta-text">讲师: {{ item.teacher_name || '未知讲师' }}</text>
						</view>
						<view class="meta-item">
							<text class="meta-icon">⭐</text>
							<text class="meta-text">{{item.rating}}</text>
						</view>
						<view class="meta-item">
							<text class="meta-icon">👥</text>
							<text class="meta-text">{{ item.student_count || 0 }}人已学习</text>
						</view>
					</view>
					
					<view class="course-footer">
						<text class="course-price">¥{{ item.price || 0 }}</text>
						<view class="course-actions">
							<button class="action-btn primary course-btn"  @click.stop="goToDetail(item.id,item)">查看详情</button>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 活动空状态 -->
			<view class="empty-state" v-if="currentTab === 'registered' && registeredActivities.length === 0">
				<text class="empty-icon">📅</text>
				<text class="empty-text">暂无已报名的活动</text>
				<button class="browse-btn" @click="goToActivityList">浏览活动</button>
			</view>
			
			<!-- 课程空状态 -->
			<view class="empty-state" v-if="currentTab === 'joined' && purchasedCourses.length === 0">
				<text class="empty-icon">📚</text>
				<text class="empty-text">暂无已购买的课程</text>
				<button class="browse-btn" @click="goToCourseList">浏览课程</button>
			</view>
		</view>
	</view>
</template>

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

export default {
	data() {
		return {
			currentTab: 'registered',
			// 活动相关
			registeredActivities: [],
			registeredCount: 0,
			// 课程相关
			purchasedCourses: [], // 已购买的课程
		}
	},
	
	onLoad() {
		this.loadMyData()
	},
	
	methods: {
		// 加载我的活动和课程数据
		async loadMyData() {
			try {
				const userInfo = uni.getStorageSync('userInfo')
				
				if (!userInfo || !userInfo.userId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}
				
				// 并行加载活动和课程数据
				await Promise.all([
					this.loadRegisteredActivities(userInfo.userId),
					this.loadPurchasedCourses(userInfo.userId)
				])
				
			} catch (error) {
				console.error('加载数据失败:', error)
				uni.showToast({
					title: '加载数据失败',
					icon: 'none'
				})
			}
		},
		
		// 加载已报名的活动
		async loadRegisteredActivities(userId) {
			const baseUrl = 'https://api.zhongruanke.cn'
			
			try {
				const [error, res] = await uni.request({
					url: `${baseUrl}/api/activity-registration/my-activities?userId=${userId}&status=1`,
					method: 'GET'
				})
				
				if (res && res.data && res.data.code === 200) {
					this.registeredActivities = (res.data.data || []).map(item => ({
						id: item.id,
						activityId: item.activityId,
						name: item.activityName,
						coverImage: item.coverImage || '/static/default-activity.png',
						startTime: item.startTime,
						endTime: item.endTime,
						location: item.location,
						price: item.price,
						actualParticipants: item.actualParticipants || 0,
						maxParticipants: item.maxParticipants || 0,
						status: this.getActivityStatusByTime(item.startTime, item.endTime)
					}))
					this.registeredCount = this.registeredActivities.length
				}
			} catch (error) {
				console.error('加载活动数据失败:', error)
			}
		},
		
		// 加载已购买的课程
		async loadPurchasedCourses(userId) {
			try {
				const coursesRes = await api.courseOrder.getPurchasedCourses(userId)
				console.log(coursesRes)
				this.purchasedCourses = coursesRes
				if (coursesRes.code === 200) {
					this.purchasedCourses = (coursesRes.data || []).map(course => ({
						id: course.id,
						courseId: course.id,
						name: course.courseName,
						coverImage: course.coverImage || '/static/default-course.png',
						teacher: course.teacher,
						price: course.price,
						studentsCount: course.studentsCount || 0,
						rating: course.rating || 4.5,
						chaptersCount: course.chaptersCount || 0, // 课程章节数
						lessonsCount: course.lessonsCount || 0,   // 课程课时数
						learnProgress: course.learnProgress || 0,  // 学习进度
						lastLearnTime: course.lastLearnTime        // 最后学习时间
					}))
					console.log(this.purchasedCourses)
				}
			} catch (error) {
				console.error('加载课程数据失败:', error)
			}
		},
		
		// 根据时间判断活动状态
		getActivityStatusByTime(startTime, endTime) {
			if (!startTime || !endTime) return 1
			
			const now = new Date()
			const start = new Date(startTime)
			const end = new Date(endTime)
			
			if (now < start) return 1 // 未开始
			if (now >= start && now <= end) return 2 // 进行中
			return 3 // 已结束
		},
		
		// 获取活动状态类型（用于样式）
		getStatusType(status) {
			const types = { 1: 'pending', 2: 'ongoing', 3: 'ended' }
			return types[status] || 'pending'
		},
		
		// 获取活动状态文本
		getStatusText(status) {
			const texts = { 1: '未开始', 2: '进行中', 3: '已结束' }
			return texts[status] || '未知'
		},
		
		// 切换标签页
		switchTab(tab) {
			this.currentTab = tab
			// 切换时滚动到顶部
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 300
			})
		},
		
		// 格式化日期
		formatDate(dateStr) {
			if (!dateStr) return '时间待定'
			try {
				const date = new Date(dateStr)
				const month = date.getMonth() + 1
				const day = date.getDate()
				const hours = date.getHours()
				const minutes = date.getMinutes()
				return `${month}月${day}日 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
			} catch (error) {
				return '时间待定'
			}
		},
		
		// 取消活动报名
		async cancelActivity(activity) {
			uni.showModal({
				title: '取消报名',
				content: '确定要取消本次活动报名吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const userInfo = uni.getStorageSync('userInfo')
							const baseUrl = 'https://api.zhongruanke.cn'
							
							const [error, result] = await uni.request({
								url: `${baseUrl}/api/activity-registration/cancel?id=${activity.id}&userId=${userInfo.userId}`,
								method: 'PUT'
							})
							
							if (result && result.data && result.data.code === 200) {
								uni.showToast({
									title: '取消报名成功',
									icon: 'success'
								})
								// 重新加载活动数据
								this.loadRegisteredActivities(userInfo.userId)
							} else {
								uni.showToast({
									title: (result && result.data && result.data.msg) || '取消失败',
									icon: 'none'
								})
							}
						} catch (error) {
							uni.showToast({
								title: '取消失败，请重试',
								icon: 'none'
							})
						}
					}
				}
			})
		},
		
		// 跳转到活动详情
		goToActivityDetail(itemId,item) {
			uni.navigateTo({
				url: `/pages/activities/detail?id=${item.activityId}`
			})
		},
		
		// 跳转到详情
		goToDetail(id,item) {

			uni.navigateTo({
				url: `/pages/courses/detail?id=${item.id}`,
				success: () => {
				
				},
				fail: (err) => {
					
					uni.showToast({
						title: '跳转失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 跳转到活动列表
		goToActivityList() {
			uni.navigateTo({
				url: '/pages/activities/list'
			})
		},
		
		// 跳转到课程列表
		goToCourseList() {
			uni.navigateTo({
				url: '/pages/courses/list'
			})
		}
	}
}
</script>

<style scoped>
.my-activities-page {
	min-height: 100vh;
	background: #FFF9F9;
}

/* 标签页样式 */
.tabs {
	display: flex;
	background: white;
	padding: 0 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.tab-item {
	flex: 1;
	text-align: center;
	padding: 30rpx 0;
	position: relative;
}

.tab-text {
	font-size: 30rpx;
	color: #666;
}

.tab-item.active .tab-text {
	color: #E91E63;
	font-weight: 600;
}

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 80rpx;
	height: 6rpx;
	background: #E91E63;
	border-radius: 3rpx;
}

.tab-badge {
	position: absolute;
	top: 20rpx;
	right: 20%;
	background: #FF4D4F;
	color: white;
	font-size: 20rpx;
	padding: 2rpx 8rpx;
	border-radius: 10rpx;
	min-width: 32rpx;
	text-align: center;
}

/* 列表容器 */
.activities-list {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 20rpx;
	padding: 20rpx;
}

/* 活动卡片样式 */
.activity-card {
	position: relative;
	background: white;
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.activity-cover {
	width: 100%;
	height: 240rpx;
	background: #F5F5F5;
}

.activity-info {
	padding: 20rpx;
}

.activity-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 15rpx;
}

.activity-name {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	flex: 1;
	margin-right: 10rpx;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
	line-height: 1.4;
}

/* 活动状态标签 */
.status-tag {
	font-size: 20rpx;
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
	color: white;
}

.status-pending {
	background-color: #409EFF; /* 未开始-蓝色 */
}

.status-ongoing {
	background-color: #67C23A; /* 进行中-绿色 */
}

.status-ended {
	background-color: #909399; /* 已结束-灰色 */
}

/* 活动元信息 */
.activity-meta--activity {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
	margin-bottom: 20rpx;
}

.meta-item {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.meta-icon {
	font-size: 24rpx;
}

.meta-text {
	font-size: 24rpx;
	color: #666;
	line-height: 1.4;
}

.activity-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.activity-price {
	color: #E91E63;
	font-weight: 600;
	font-size: 32rpx;
}

/* 课程卡片样式 */
.course-card {
	position: relative;
	background: white;
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.course-cover {
	width: 100%;
	height: 240rpx;
	background: #F5F5F5;
}

.course-info {
	padding: 20rpx;
}

.course-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 15rpx;
}

.course-name {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	flex: 1;
	margin-right: 10rpx;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
	line-height: 1.4;
}

.course-rating {
	display: flex;
	align-items: center;
	gap: 4rpx;
	background-color: #FFF8E1;
	padding: 4rpx 10rpx;
	border-radius: 10rpx;
}

.rating-text {
	font-size: 20rpx;
	color: #FF9800;
}

/* 课程元信息 */
.course-meta {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
	margin-bottom: 20rpx;
}

.course-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.course-price {
	color: #9C27B0;
	font-weight: 600;
	font-size: 32rpx;
}

/* 按钮样式 */
.activity-actions {
	display: flex;
	gap: 10rpx;
}

.action-btn {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	border: none;
}

.action-btn.primary {
	background-color: #E91E63;
	color: white;
}

.action-btn.cancel {
	background-color: #F5F5F5;
	color: #666;
}

.course-btn {
	background-color: #9C27B0 !important;
	width: 140rpx;
	text-align: center;
}

/* 空状态样式 */
.empty-state {
	grid-column: 1 / -1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 0;
}

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

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

.browse-btn {
	padding: 16rpx 60rpx;
	background: #E91E63;
	color: white;
	border-radius: 40rpx;
	font-size: 28rpx;
	border: none;
}
</style>