<template>
	<view class="course-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="course-cover">
			<image :src="course.cover_image" class="cover-image" mode="aspectFill"></image>
			<view class="cover-mask">
				<view class="discount-tag" v-if="course.discount_rate">限时{{ course.discount_rate }}折</view>
			</view>
		</view>

		<!-- 课程信息 -->
		<view class="course-content">
			<view class="course-title">{{ course.name }}</view>

			<view class="teacher-info">
				<image :src="course.teacher_avatar || DEFAULT_IMAGES.avatar" class="teacher-avatar" mode="aspectFill"></image>
				<view class="teacher-detail">
					<text class="teacher-name">{{ course.teacher_name }}</text>
					<text class="teacher-desc">{{ course.teacher_desc || '资深情感导师' }}</text>
				</view>
			</view>

			<view class="course-stats">
				<view class="stat-item">
					<text class="stat-icon">👥</text>
					<text class="stat-text">{{ course.student_count || 0 }}人学习</text>
				</view>
				<view class="stat-item">
					<text class="stat-icon">⭐</text>
					<text class="stat-text">{{ course.rating || '5.0' }}分</text>
				</view>
				<view class="stat-item">
					<text class="stat-icon">📚</text>
					<text class="stat-text">{{ course.chapter_count || 0 }}个章节</text>
				</view>
			</view>

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

			<view class="description-section">
				<view class="section-title">课程介绍</view>
				<view class="description-text">{{ course.description || '暂无介绍' }}</view>
			</view>

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

			<view class="outline-section">
				<view class="section-title">课程大纲</view>
				<view class="outline-text">{{ course.outline || '敬请期待' }}</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">{{ course.price || 0 }}</text>
					<text class="original-price" v-if="course.original_price">¥{{ course.original_price }}</text>
					<text class="discount-text" v-if="course.discount_rate">{{ course.discount_rate }}折优惠</text>
				</view>
			</view>
			<view class="purchase-btn" :class="{ purchased: course.purchase_status === 1 }" @click="handlePurchase">
				<text class="btn-text">{{ course.purchase_status === 1 ? '已购买' : '立即购买' }}</text>
			</view>
		</view>
	</view>
</template>

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

	export default {
		data() {
			return {
				courseId: null,
				course: {},
				DEFAULT_IMAGES,
				gatewayURL: 'https://api.zhongruanke.cn',
				currentUserId: null,
				isPurchased: false
			}
		},

		onLoad(options) {
		
			
		
			this.currentUserId = userAuth.getUserId()
			
			
			if (options.id) {
				this.courseId = options.id
				
			
				this.setCourseDataById(this.courseId)
				this.loadCourseDetail()
				
				this.checkPurchaseStatus()
			} 
			
			
			setTimeout(() => {
				this.checkDataHealth()
			}, 100)
		},

		methods: {
			// 根据ID设置课程数据
			setCourseDataById(courseId) {
				const courseData = {}
				
				const targetCourse = courseData[courseId]
				if (targetCourse) {
					this.course = {
						...this.course,
						...targetCourse,
						cover_image: DEFAULT_IMAGES.course,
						teacher_avatar: DEFAULT_IMAGES.avatar
					}
					
				}
			},
			
			// 加载课程详情
			async loadCourseDetail() {
				try {
					
					const data = await api.course.getDetail(this.courseId)
					if (data) {
						this.course = {
							...data,
							purchase_status: 0  // 初始化为未购买，由 checkPurchaseStatus 判断
						}
						
					} 
				} catch (error) {
					
					
					uni.showToast({
						title: '使用示例数据',
						icon: 'none',
						duration: 1500
					})
				}
			},

			// 检查购买状态
			async checkPurchaseStatus() {
				if (!this.currentUserId || !this.courseId) return
				
				try {
					const purchased = await api.courseOrder.checkPurchased(this.currentUserId, this.courseId)
					// 只有明确返回 true 时才设置为已购买
					if (purchased === true) {
						this.isPurchased = true
						this.course.purchase_status = 1
					}
				} catch (error) {
					
				}
			},
			
			
			handlePurchase() {
			
				if (this.course.purchase_status === 1 || this.isPurchased) {
					uni.showToast({
						title: '您已购买过此课程',
						icon: 'none'
					})
					return
				}
				
				// 检查是否登录
				if (!this.currentUserId) {
					uni.showModal({
						title: '提示',
						content: '请先登录后再购买课程',
						confirmText: '去登录',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/page3/page3'
								})
							}
						}
					})
					return
				}
				
				uni.showModal({
					title: '确认购买',
					content: `确认购买"${this.course.name}"课程吗？\n价格：¥${this.course.price}`,
					success: (res) => {
						if (res.confirm) {
							this.requestPay()
						}
					}
				})
			},
			
			// 请求支付参数并调起微信支付
			requestPay() {
				uni.showLoading({
					title: '处理中...'
				})
				
				uni.request({
					url: this.gatewayURL + '/api/course-order/purchase',
					method: 'POST',
					data: {
						userId: this.currentUserId,
						courseId: parseInt(this.courseId),
						courseName: this.course.name,
						price: this.course.price
					},
					header: {
						'content-type': 'application/json',
						'token': uni.getStorageSync('token')
					},
					success: (res) => {
						uni.hideLoading()
						
						if (res.data && res.data.code === 200) {
							const payParams = res.data.data
							this.callWxPay(payParams)
						} else {
							uni.showToast({
								title: res.data?.message || res.data?.msg || '获取支付参数失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						uni.hideLoading()
					
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					}
				})
			},
			
			// 调起微信支付
			callWxPay(payParams) {
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: payParams.timeStamp,
					nonceStr: payParams.nonceStr,
					package: payParams.package,
					signType: payParams.signType,
					paySign: payParams.paySign,
					success: (payResult) => {
						if (payResult.errMsg === 'requestPayment:ok') {
							uni.showToast({
								title: '购买成功！',
								icon: 'success',
								duration: 2000
							})
							
							// 更新购买状态
							this.course.purchase_status = 1
							this.isPurchased = true
							this.course.student_count = (this.course.student_count || 0) + 1
							
							setTimeout(() => {
								uni.showModal({
									title: '购买成功',
									content: '您已成功购买此课程，现在可以开始学习了！',
									showCancel: false,
									confirmText: '开始学习',
									success: (modalRes) => {
										if (modalRes.confirm) {
											uni.showToast({
												title: '学习功能开发中',
												icon: 'none'
											})
										}
									}
								})
							}, 2000)
						}
					},
					fail: (payError) => {
						
						if (payError.errMsg.includes('cancel')) {
							uni.showToast({
								title: '已取消支付',
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: `支付失败：${payError.errMsg}`,
								icon: 'none'
							})
						}
					}
				})
			},

			// 返回
			goBack() {
				
				uni.navigateBack({
					fail: () => {
						
						uni.navigateTo({
							url: '/pages/courses/list'
						})
					}
				})
			},
			
			// 数据健康检查
			checkDataHealth() {
				if (!this.course.name || this.course.name === '加载中...') {
					this.course.name = '恋爱沟通技巧大师课'
				}
				if (!this.course.teacher_name) {
					this.course.teacher_name = '张情感老师'
				}
				if (!this.course.cover_image) {
					this.course.cover_image = this.DEFAULT_IMAGES.course
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.course-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;
		}
	}

	/* 课程封面 */
	.course-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;

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

	/* 课程内容 */
	.course-content {
		padding: 30rpx;
		background-color: #FFFFFF;
		margin: 20rpx;
		border-radius: 20rpx;

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

		.teacher-info {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;

			.teacher-avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				margin-right: 20rpx;
			}

			.teacher-detail {
				flex: 1;
				display: flex;
				flex-direction: column;
				gap: 5rpx;

				.teacher-name {
					font-size: 28rpx;
					font-weight: bold;
					color: #333333;
				}

				.teacher-desc {
					font-size: 24rpx;
					color: #999999;
				}
			}
		}

		.course-stats {
			display: flex;
			justify-content: space-around;
			padding: 20rpx 0;
			background-color: #FFF9F9;
			border-radius: 15rpx;

			.stat-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				gap: 10rpx;

				.stat-icon {
					font-size: 32rpx;
				}

				.stat-text {
					font-size: 24rpx;
					color: #666666;
				}
			}
		}

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

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

		.description-text,
		.outline-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 {
				display: flex;
				align-items: baseline;
				color: #E91E63;
				font-weight: bold;

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

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

				.original-price {
					margin-left: 10rpx;
					font-size: 24rpx;
					color: #999999;
					text-decoration: line-through;
				}
				
				.discount-text {
					margin-left: 15rpx;
					font-size: 22rpx;
					color: #FF9800;
					background: rgba(255, 152, 0, 0.1);
					padding: 5rpx 12rpx;
					border-radius: 15rpx;
				}
			}
		}

		.purchase-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);
			transition: all 0.3s;

			.btn-text {
				font-size: 32rpx;
				font-weight: bold;
				color: #FFFFFF;
			}
			
			&.purchased {
				background: #4CAF50;
				box-shadow: 0 8rpx 16rpx rgba(76, 175, 80, 0.3);
				
				.btn-text {
					color: #FFFFFF;
				}
			}
			
			&:active {
				transform: scale(0.95);
			}
		}
	}
</style>


