<template>
	<view class="courses-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-list">
			<view class="course-card" v-for="(item, index) in courseList" :key="index"
				@click="goToDetail(item.id)">
				<image :src="item.cover_image" class="course-image" mode="aspectFill"></image>
				<view class="course-info">
					<view class="course-name">{{ item.name }}</view>
					<view class="course-desc">{{ item.description }}</view>
					<view class="course-meta">
						<text class="course-teacher">👩‍🏫 {{ item.teacher_name }}</text>
						<text class="course-students">👥 {{ item.student_count || 0 }}人学习</text>
					</view>
					<view class="course-footer">
						<view class="course-price">
							<text class="price-symbol">¥</text>
							<text class="price-value">{{ item.price }}</text>
							<text class="original-price" v-if="item.original_price">¥{{ item.original_price }}</text>
						</view>
						<view class="course-btn">立即购买</view>
					</view>
				</view>
				<view class="discount-tag" v-if="item.discount_rate">{{ item.discount_rate }}折</view>
			</view>
		</view>

		<!-- 加载更多 -->
		<view class="load-more" v-if="hasMore">
			<text class="load-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
		</view>
		<view class="no-more" v-else>
			<text class="no-more-text">没有更多了</text>
		</view>
	</view>
</template>

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

	export default {
		data() {
			return {
				courseList: [],  // 从API加载数据，不使用硬编码
				pageNum: 1,
				pageSize: 10,
				total: 0,  // 总记录数
				hasMore: true,
				loading: false,
				DEFAULT_IMAGES
			}
		},

		onLoad() {
			console.log('精品课程列表页面加载')
			this.loadCourseList()
		},

		onReachBottom() {
			if (this.hasMore && !this.loading) {
				this.pageNum++
				this.loadCourseList()
			}
		},

		methods: {
			// 加载课程列表
			async loadCourseList() {
				if (this.loading) return
				this.loading = true

				try {
					console.log('尝试加载精品课程API数据...')
					const response = await api.course.getList({
						page: this.pageNum,
						pageSize: this.pageSize,
						status: 1
					})

					console.log('API返回数据:', response)

					// 处理返回的数据结构
					let courseData = []
					let totalCount = 0

					if (response && response.list) {
						// 如果返回的是 {list: [], total: xx} 格式
						courseData = response.list
						totalCount = response.total || 0
					} else if (Array.isArray(response)) {
						// 如果直接返回数组
						courseData = response
						totalCount = response.length
					}

					console.log('当前页码:', this.pageNum, '返回数据量:', courseData.length, '总数据量:', totalCount)

					if (courseData && courseData.length > 0) {
						// 处理每个课程数据，确保字段完整
						const processedData = courseData.map(item => ({
							...item,
							// 确保必要字段存在
							cover_image: item.cover_image || item.coverImage || DEFAULT_IMAGES.course,
							teacher_name: item.teacher_name || item.instructor || '专业导师',
							student_count: item.student_count || item.participants || 0,
							// 保留其他字段
							id: item.id,
							name: item.name,
							description: item.description,
							price: item.price,
							original_price: item.original_price || item.originalPrice,
							discount_rate: item.discount_rate || item.discountRate,
							rating: item.rating,
							duration: item.duration
						}))

						if (this.pageNum === 1) {
							// 第一页，替换数据
							this.courseList = processedData
							this.total = totalCount
						} else {
							// 后续页，追加数据
							this.courseList = [...this.courseList, ...processedData]
						}

						// 判断是否还有更多数据：当前已加载数量 < 总数量
						this.hasMore = this.courseList.length < totalCount

						console.log('API课程数据加载成功:', processedData.length, '条')
						console.log('已加载总数:', this.courseList.length, '/', totalCount)
						console.log('是否还有更多:', this.hasMore)
						console.log('第一条课程数据:', processedData[0])
					} else {
						this.hasMore = false
						console.log('API返回课程数据为空')
						if (this.pageNum === 1) {
							uni.showToast({
								title: '暂无课程数据',
								icon: 'none'
							})
						}
					}
				} catch (error) {
					console.error('加载课程列表失败:', error)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
					this.hasMore = false
				} finally {
					this.loading = false
				}
			},

			// 跳转到详情
			goToDetail(id) {
				console.log('跳转到课程详情, id:', id)
				uni.navigateTo({
					url: `/pages/courses/detail?id=${id}`,
					success: () => {
						console.log('跳转课程详情成功')
					},
					fail: (err) => {
						console.error('跳转课程详情失败:', err)
						uni.showToast({
							title: '跳转失败',
							icon: 'none'
						})
					}
				})
			},

			// 返回
			goBack() {
				console.log('课程列表返回上一页')
				uni.navigateBack({
					fail: () => {
						// 返回失败时跳转首页
						uni.navigateTo({
							url: '/pages/index/index'
						})
					}
				})
			}
		}
	}
</script>

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

	/* 自定义导航栏 */
	.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-list {
		padding: 20rpx 30rpx;

		.course-card {
			position: relative;
			margin-bottom: 20rpx;
			background-color: #FFFFFF;
			border-radius: 20rpx;
			overflow: hidden;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

			.course-image {
				width: 100%;
				height: 360rpx;
				background-color: #F5F5F5;
			}

			.course-info {
				padding: 30rpx;

				.course-name {
					font-size: 32rpx;
					font-weight: bold;
					color: #333333;
					margin-bottom: 15rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
				}

				.course-desc {
					font-size: 26rpx;
					color: #666666;
					line-height: 1.6;
					margin-bottom: 20rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
				}

				.course-meta {
					display: flex;
					justify-content: space-between;
					font-size: 24rpx;
					color: #999999;
					margin-bottom: 20rpx;
				}

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

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

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

						.price-value {
							font-size: 36rpx;
						}

						.original-price {
							margin-left: 10rpx;
							font-size: 24rpx;
							color: #999999;
							text-decoration: line-through;
						}
					}

					.course-btn {
						padding: 10rpx 30rpx;
						background-color: #E91E63;
						color: #FFFFFF;
						text-align: center;
						border-radius: 30rpx;
						font-size: 24rpx;
					}
				}
			}

			.discount-tag {
				position: absolute;
				top: 20rpx;
				left: 20rpx;
				padding: 8rpx 20rpx;
				background: linear-gradient(135deg, #FF6B6B 0%, #FF9800 100%);
				color: #FFFFFF;
				font-size: 24rpx;
				font-weight: bold;
				border-radius: 10rpx;
			}
		}
	}

	/* 加载更多 */
	.load-more,
	.no-more {
		padding: 30rpx 0;
		text-align: center;

		.load-text,
		.no-more-text {
			font-size: 24rpx;
			color: #999999;
		}
	}
</style>


