<template>
	<view class="activity-detail-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>

		<!-- 活动封面 -->
		<view class="activity-cover">
			<image :src="activity.coverImage" class="cover-image" mode="aspectFill" 
				@error="handleImageError" @load="handleImageLoad"></image>
			<view class="cover-mask">
				<view class="activity-tag" v-if="activity.isHot">🔥 热门活动</view>
			</view>
		</view>

		<!-- 活动信息 -->
		<view class="activity-content">
			<view class="activity-title">{{ activity.name }}</view>

			<view class="info-section">
				<view class="info-item">
					<text class="info-icon">⏰</text>
					<text class="info-label">活动时间：</text>
					<text class="info-value">{{ formatActivityTime(activity.startTime, activity.endTime) }}</text>
				</view>
				<view class="info-item">
					<text class="info-icon">📍</text>
					<text class="info-label">活动地点：</text>
					<text class="info-value">{{ activity.location || '待定' }}</text>
				</view>
				<view class="info-item">
					<text class="info-icon">👥</text>
					<text class="info-label">报名人数：</text>
					<text class="info-value">{{ activity.actualParticipants || 0 }} / {{ activity.maxParticipants || '不限' }}</text>
				</view>
				<view class="info-item">
					<text class="info-icon">💰</text>
					<text class="info-label">活动费用：</text>
					<text class="info-value price">¥{{ activity.price || 0 }}</text>
				</view>
			</view>

			<view class="divider"></view>

			<view class="description-section">
				<view class="section-title">活动介绍</view>
				<view class="description-text">{{ activity.description || '暂无介绍' }}</view>
			</view>

			<view class="divider"></view>

			<view class="notes-section">
				<view class="section-title">注意事项</view>
				<view class="notes-text">{{ activity.notes || '请准时参加活动' }}</view>
			</view>
		</view>

		<!-- 底部报名按钮 -->
		<view class="bottom-bar">
			<view class="price-info">
				<text class="price-label">活动费用</text>
				<view class="price-value">
					<text class="price-symbol">¥</text>
					<text class="price-num">{{ activity.price || 0 }}</text>
				</view>
			</view>
			<view class="register-btn" @click="handleRegister">
				<text class="btn-text">立即报名</text>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/utils/api.js'
	import { formatTime } from '@/utils/util.js'
	import { DEFAULT_IMAGES } from '@/config/index.js'
	import userAuth from '@/utils/userAuth.js'

	export default {
		data() {
			return {
				activityId: null,
				activity: {
					name: '加载中...',
					coverImage: DEFAULT_IMAGES.activity,
					price: 0
				}
			}
		},

		onLoad(options) {
			if (options.id) {
				this.activityId = options.id
				this.loadActivityDetail()
			}
		},

		methods: {
			// 加载活动详情
			async loadActivityDetail() {
				try {
					const data = await api.activity.getDetail(this.activityId)
					if (data) {
						// 处理字段映射，确保前端使用的字段名统一
						this.activity = {
							...data,
							coverImage: this.validateImageUrl(data.coverImage || data.cover_image || data.imageUrl || data.image_url),
							startTime: data.startTime || data.start_time || data.startDate || data.start_date || '',
							endTime: data.endTime || data.end_time || data.endDate || data.end_date || '',
							location: data.location || data.address || data.venue || '待定',
							maxParticipants: data.maxParticipants || data.max_participants || null,
							actualParticipants: data.actualParticipants || data.actual_participants || 0,
							price: data.price || data.fee || 0,
							description: data.description || data.desc || '暂无介绍',
							notes: data.notes || data.notice || '请准时参加活动'
						}
						console.log('活动详情加载成功:', this.activity)
					}
				} catch (error) {
					console.error('加载活动详情失败:', error)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				}
			},

			// 验证并修正图片URL
			validateImageUrl(url) {
				if (!url || url === 'null' || url === 'undefined') {
					return DEFAULT_IMAGES.activity || '/static/default-activity.jpg'
				}

				let cleanedUrl = String(url).trim()
				const httpIndex = cleanedUrl.indexOf('http')
				if (httpIndex > 0) {
					cleanedUrl = cleanedUrl.slice(httpIndex)
				}

				if (!cleanedUrl) {
					return DEFAULT_IMAGES.activity || '/static/default-activity.jpg'
				}
				
				// 如果是相对路径，添加协议和域名
				if (cleanedUrl.startsWith('/')) {
					return `http://115.190.125.125:9000${cleanedUrl}`
				}
				
				// 如果已经是完整URL，直接返回
				if (cleanedUrl.startsWith('http://') || cleanedUrl.startsWith('https://')) {
					return cleanedUrl
				}
				
				// 其他情况返回默认图片
				return DEFAULT_IMAGES.activity || '/static/default-activity.jpg'
			},

			// 格式化时间
			formatTime,

			// 格式化活动时间（显示开始和结束时间）
			formatActivityTime(startTime, endTime) {
				if (!startTime) return '时间待定'
				
				try {
					const start = new Date(startTime)
					const startMonth = start.getMonth() + 1
					const startDay = start.getDate()
					const startHour = start.getHours().toString().padStart(2, '0')
					const startMinute = start.getMinutes().toString().padStart(2, '0')
					
					let timeStr = `${startMonth}月${startDay}日 ${startHour}:${startMinute}`
					
					// 如果有结束时间，添加结束时间
					if (endTime) {
						const end = new Date(endTime)
						const endMonth = end.getMonth() + 1
						const endDay = end.getDate()
						const endHour = end.getHours().toString().padStart(2, '0')
						const endMinute = end.getMinutes().toString().padStart(2, '0')
						
						timeStr += ` - ${endMonth}月${endDay}日 ${endHour}:${endMinute}`
					}
					
					return timeStr
				} catch (error) {
					console.error('时间格式化失败:', error)
					return '时间待定'
				}
			},

			// 处理报名
			handleRegister() {
				// 获取当前用户ID
				const userId = userAuth.getUserId()
				if (!userId) {
					uni.showModal({
						title: '需要登录',
						content: '请先登录后再报名活动',
						showCancel: false,
						success: () => {
							uni.navigateTo({
								url: '/pages/page3/page3'
							})
						}
					})
					return
				}
				
				// 检查人数限制（前端预检查，提供更好的用户体验）
				if (this.activity.maxParticipants && 
				    this.activity.actualParticipants >= this.activity.maxParticipants) {
					uni.showModal({
						title: '报名已满',
						content: '当前活动报名人数已达上限，感谢您的关注，敬请期待后续活动～',
						showCancel: false
					})
					return
				}
				
				uni.showModal({
					title: '确认报名',
					content: `确认报名参加"${this.activity.name}"吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								await api.activity.register(this.activityId, userId)
								uni.showModal({
									title: '报名成功',
									content: '恭喜您报名成功！',
									showCancel: false,
									success: () => {
										this.loadActivityDetail()
									}
								})
							} catch (error) {
								console.error('报名失败:', error)
								// 后端会返回友好的错误信息（通过Result类的message字段）
								const errorMsg = error.message || '报名失败，请稍后重试'
								uni.showModal({
									title: '提示',
									content: errorMsg,
									showCancel: false
								})
							}
						}
					}
				})
			},

			// 返回
			goBack() {
				uni.navigateBack()
			},

			// 图片加载错误处理
			handleImageError(e) {
				console.warn('活动封面图片加载失败:', e)
				this.activity.coverImage = DEFAULT_IMAGES.activity || '/static/default-activity.jpg'
			},

			// 图片加载成功
			handleImageLoad(e) {
				console.log('活动封面图片加载成功')
			}
		}
	}
</script>

<style lang="scss" scoped>
	.activity-detail-page {
		min-height: 100vh;
		background-color: #FFF9F9;
		padding-top: 90rpx;
		padding-bottom: 120rpx;
	}

	/* 自定义导航栏 */
	.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-color: #E91E63;
		z-index: 999;

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

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

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

	/* 活动封面 */
	.activity-cover {
		position: relative;
		width: 100%;
		height: 500rpx;

		.cover-image {
			width: 100%;
			height: 100%;
		}

		.cover-mask {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: linear-gradient(to bottom, rgba(0, 0, 0, 0.3), transparent);
			padding: 30rpx;

			.activity-tag {
				display: inline-block;
				padding: 10rpx 20rpx;
				background: linear-gradient(135deg, #FF6B6B 0%, #FF9800 100%);
				color: #FFFFFF;
				font-size: 24rpx;
				font-weight: bold;
				border-radius: 30rpx;
			}
		}
	}

	/* 活动内容 */
	.activity-content {
		padding: 30rpx;
		background-color: #FFFFFF;
		margin: 20rpx;
		border-radius: 20rpx;

		.activity-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333333;
			margin-bottom: 30rpx;
			line-height: 1.5;
		}

		.info-section {
			.info-item {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;
				font-size: 28rpx;

				.info-icon {
					font-size: 32rpx;
					margin-right: 10rpx;
				}

				.info-label {
					color: #666666;
				}

				.info-value {
					color: #333333;
					flex: 1;

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

		.divider {
			height: 1rpx;
			background-color: #F0F0F0;
			margin: 30rpx 0;
		}

		.section-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #333333;
			margin-bottom: 20rpx;
		}

		.description-text,
		.notes-text {
			font-size: 28rpx;
			color: #666666;
			line-height: 1.8;
			white-space: pre-wrap;
		}
	}

	/* 底部报名按钮 */
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		background-color: #FFFFFF;
		border-top: 1rpx solid #F0F0F0;
		z-index: 999;

		.price-info {
			flex: 1;

			.price-label {
				display: block;
				font-size: 24rpx;
				color: #999999;
				margin-bottom: 5rpx;
			}

			.price-value {
				color: #E91E63;
				font-weight: bold;

				.price-symbol {
					font-size: 28rpx;
				}

				.price-num {
					font-size: 40rpx;
				}
			}
		}

		.register-btn {
			padding: 20rpx 60rpx;
			background: linear-gradient(135deg, #E91E63 0%, #FF6B6B 100%);
			border-radius: 50rpx;
			box-shadow: 0 8rpx 16rpx rgba(233, 30, 99, 0.3);

			.btn-text {
				font-size: 32rpx;
				font-weight: bold;
				color: #FFFFFF;
			}
		}
	}
</style>


