<template>
	<view class="my-activities-page">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-back" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<view class="navbar-title">我的活动</view>
			<view class="navbar-placeholder"></view>
		</view>
		
		<!-- 标签页切换 -->
		<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>
			<view class="tab-item" :class="{ active: currentTab === 'favorite' }" @click="switchTab('favorite')">
				<text class="tab-text">我的收藏</text>
			</view>
		</view>
		
		<!-- 活动列表 -->
		<view class="activities-list">
			<view class="activity-card" v-for="activity in filteredActivities" :key="activity.id" @click="goToActivityDetail(activity)">
				<image :src="activity.coverImage || 'http://115.190.125.125:9001/static-images/login-bg.png'" class="activity-cover" mode="aspectFill"></image>
				<view class="activity-info">
					<view class="activity-header">
						<text class="activity-name">{{ activity.name }}</text>
						<el-tag :type="getStatusType(activity.status)" size="small">{{ getStatusText(activity.status) }}</el-tag>
					</view>
					
					<view class="activity-meta">
						<view class="meta-item">
							<text class="meta-icon">📅</text>
							<text class="meta-text">{{ formatDate(activity.startTime) }}</text>
						</view>
						<view class="meta-item" v-if="activity.location">
							<text class="meta-icon">📍</text>
							<text class="meta-text">{{ activity.location }}</text>
						</view>
						<view class="meta-item">
							<text class="meta-icon">👥</text>
							<text class="meta-text">{{ activity.actualParticipants }}/{{ activity.maxParticipants }}人</text>
						</view>
					</view>
					
					<view class="activity-footer">
						<text class="activity-price">¥{{ activity.price || 0 }}</text>
						<view class="activity-actions">
							<button class="action-btn" size="mini" v-if="currentTab === 'registered'" @click.stop="cancelActivity(activity)">取消报名</button>
							<button class="action-btn primary" size="mini" @click.stop="goToActivityDetail(activity)">查看详情</button>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view class="empty-state" v-if="filteredActivities.length === 0">
				<text class="empty-icon">📭</text>
				<text class="empty-text">{{ getEmptyText() }}</text>
				<button class="browse-btn" @click="goToActivityList">浏览活动</button>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			currentTab: 'registered',
			registeredActivities: [],
			joinedActivities: [],
			favoriteActivities: [],
			registeredCount: 0
		}
	},
	
	computed: {
		filteredActivities() {
			if (this.currentTab === 'registered') {
				return this.registeredActivities
			} else if (this.currentTab === 'joined') {
				return this.joinedActivities
			} else {
				return this.favoriteActivities
			}
		}
	},
	
	onLoad() {
		this.loadMyActivities()
	},
	
	methods: {
		// 加载我的活动
		async loadMyActivities() {
			try {
				const userInfo = uni.getStorageSync('userInfo')
				console.log('userInfo:', userInfo)
				
				if (!userInfo || !userInfo.userId) {
					console.warn('用户未登录')
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}
				
				const baseUrl = 'http://localhost:8083' // 本地开发
				// const baseUrl = 'http://115.190.125.125:8083' // 生产环境
				
				console.log('开始查询我的活动, userId:', userInfo.userId)
				
				// 获取已报名的活动（status=1）
				const [error1, registeredRes] = await uni.request({
					url: `${baseUrl}/api/activity-registration/my-activities?userId=${userInfo.userId}&status=1`,
					method: 'GET'
				})
				
				console.log('已报名活动响应:', registeredRes)
				
				if (error1) {
					console.error('查询已报名活动失败:', error1)
				}
				
				if (registeredRes && registeredRes.data && registeredRes.data.code === 200) {
					console.log('已报名活动数据:', registeredRes.data.data)
					this.registeredActivities = (registeredRes.data.data || []).map(item => ({
						id: item.id,
						activityId: item.activityId,
						name: item.activityName,
						coverImage: item.coverImage,
						startTime: item.startTime,
						endTime: item.endTime,
						location: item.location,
						price: item.price,
						actualParticipants: item.actualParticipants,
						maxParticipants: item.maxParticipants,
						status: this.getActivityStatusByTime(item.startTime, item.endTime)
					}))
					this.registeredCount = this.registeredActivities.length
				}
				
				// 获取已签到的活动（status=3）
				const [error2, joinedRes] = await uni.request({
					url: `${baseUrl}/api/activity-registration/my-activities?userId=${userInfo.userId}&status=3`,
					method: 'GET'
				})
				
				console.log('已参加活动响应:', joinedRes)
				
				if (error2) {
					console.error('查询已参加活动失败:', error2)
				}
				
				if (joinedRes && joinedRes.data && joinedRes.data.code === 200) {
					this.joinedActivities = (joinedRes.data.data || []).map(item => ({
						id: item.id,
						activityId: item.activityId,
						name: item.activityName,
						coverImage: item.coverImage,
						startTime: item.startTime,
						endTime: item.endTime,
						location: item.location,
						price: item.price,
						actualParticipants: item.actualParticipants,
						maxParticipants: item.maxParticipants,
						status: 3
					}))
				}
				
				// 收藏功能暂时为空
				this.favoriteActivities = []
				
			} 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 // 已结束
		},
		
		// 切换标签页
		switchTab(tab) {
			this.currentTab = tab
		},
		
		// 格式化日期
		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 '时间待定'
			}
		},
		
		// 获取状态类型
		getStatusType(status) {
			const types = { 1: 'info', 2: 'success', 3: 'default' }
			return types[status] || 'info'
		},
		
		// 获取状态文本
		getStatusText(status) {
			const texts = { 1: '未开始', 2: '进行中', 3: '已结束' }
			return texts[status] || '未知'
		},
		
		// 获取空状态文本
		getEmptyText() {
			const texts = {
				registered: '暂无报名的活动',
				joined: '暂无参加过的活动',
				favorite: '暂无收藏的活动'
			}
			return texts[this.currentTab] || '暂无数据'
		},
		
		// 取消报名
		async cancelActivity(activity) {
			uni.showModal({
				title: '提示',
				content: '确定要取消报名吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const userInfo = uni.getStorageSync('userInfo')
							const baseUrl = 'http://localhost:8083'
							
							console.log('取消报名, activity:', activity)
							console.log('userId:', userInfo.userId)
							
							const [error, result] = await uni.request({
								url: `${baseUrl}/api/activity-registration/cancel?id=${activity.id}&userId=${userInfo.userId}`,
								method: 'PUT'
							})
							
							console.log('取消报名响应:', result)
							console.log('取消报名错误:', error)
							
							if (error) {
								console.error('取消报名请求失败:', error)
								uni.showToast({
									title: '网络错误，请重试',
									icon: 'none'
								})
								return
							}
							
							if (result && result.data && result.data.code === 200) {
								uni.showToast({
									title: '已取消报名',
									icon: 'success'
								})
								this.loadMyActivities()
							} else {
								uni.showToast({
									title: (result && result.data && result.data.msg) || '取消失败',
									icon: 'none'
								})
							}
						} catch (error) {
							console.error('取消报名失败:', error)
							uni.showToast({
								title: '取消失败',
								icon: 'none'
							})
						}
					}
				}
			})
		},
		
		// 跳转到活动详情
		goToActivityDetail(activity) {
			uni.navigateTo({
				url: `/pages/activities/detail?id=${activity.id}`
			})
		},
		
		// 跳转到活动列表
		goToActivityList() {
			uni.navigateTo({
				url: '/pages/activities/list'
			})
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		}
	}
}
</script>

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

/* 自定义导航栏 */
.custom-navbar {
	height: 88rpx;
	background: #E91E63;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 20rpx;
	color: white;
}

.navbar-back {
	padding: 10rpx 20rpx;
}

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

.navbar-title {
	font-size: 32rpx;
	font-weight: bold;
	position: absolute;
	left: 50%;
	transform: translateX(-50%);
}

.navbar-placeholder {
	width: 80rpx;
}

/* 标签页 */
.tabs {
	display: flex;
	background: white;
	padding: 0 30rpx;
}

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

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

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

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 60rpx;
	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 {
	padding: 20rpx;
}

.activity-card {
	background: white;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

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

.activity-info {
	padding: 24rpx;
}

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

.activity-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	flex: 1;
	margin-right: 16rpx;
}

.activity-meta {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
	margin-bottom: 20rpx;
}

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

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

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

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

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

.activity-actions {
	display: flex;
	gap: 16rpx;
}

.action-btn {
	padding: 8rpx 24rpx;
	background: #F5F5F5;
	color: #666;
	border-radius: 20rpx;
	font-size: 24rpx;
	border: none;
}

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

/* 空状态 */
.empty-state {
	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>

