<template>
	<view class="course-filter-page">
		<!-- 自定义导航栏 -->
		<view class="navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="nav-content">
				<view class="nav-left" @click="goBack">
					<uni-icons type="left" size="24" color="#FF4757"></uni-icons>
				</view>
				<view class="nav-title">{{ special_name?special_name:'肝病精品课' }}</view>
				<view class="nav-right" @click="goSearch">
					<uni-icons type="search" size="24" color="#FF4757"></uni-icons>
				</view>
			</view>
		</view>

		<!-- 页面内容 -->
		<view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
			<!-- 主横幅（自动轮播） -->
			<view class="main-banner">
				<swiper 
					class="banner-swiper"
					:autoplay="true"
					:interval="4000"
					:duration="500"
					:circular="true"
					:indicator-dots="true"
					indicator-color="#d8d8d8"
					indicator-active-color="#FF4757"
				>
					<swiper-item v-for="(banner, idx) in bannerList" :key="banner.id || idx">
						<image :src="banner.sroll_img || banner.image || '/static/lunbo_bg.png'" mode="aspectFill" class="banner-image"></image>
						<view class="banner-content">
							<text class="banner-title">{{ banner.title || '' }}</text>
							<text class="banner-subtitle">{{ banner.subtitle || '' }}</text>
						</view>
					</swiper-item>
				</swiper>
			</view>

			<!-- 筛选栏 -->
			<view class="filter-bar">
				<view class="filter-item">
					<uni-data-select 
						v-model="selectedCategory"
						:localdata="categoryOptions"
						:clear="false"
						placeholder="全部课程"
						@change="onCategoryChange"
					>
						<template v-slot:selected="{selectedItems}">
							<view class="filter-display">
								<text>{{ selectedItems.length > 0 ? selectedItems[0].text : '全部课程' }}</text>
								<uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
							</view>
						</template>
					</uni-data-select>
				</view>
				<view class="filter-item">
					<uni-data-select 
						v-model="selectedSort"
						:localdata="sortOptions"
						:clear="false"
						placeholder="默认排序"
						@change="onSortChange"
					>
						<template v-slot:selected="{selectedItems}">
							<view class="filter-display">
								<text>{{ selectedItems.length > 0 ? selectedItems[0].text : '默认排序' }}</text>
								<uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
							</view>
						</template>
					</uni-data-select>
				</view>
				<view v-if="special_type == 0" class="separator"></view>
				<view v-if="special_type == 0" class="filter-item" :class="{ active: filters.limitedOffer }" @click="toggleLimitedOffer">
					<text>限时优惠</text>
				</view>
				<view v-if="special_type == 0" class="separator"></view>
				<view v-if="special_type == 0" class="filter-item" :class="{ active: filters.freeCourses }" @click="toggleFreeCourses">
					<text>免费课程</text>
				</view>
			</view>

			<!-- 课程列表 -->
			<view class="course-list">
				<!-- 空状态 -->
				<view v-if="courseList.length === 0" class="empty-state">
					<image src="/static/empty_course.png" mode="aspectFit" class="empty-image"></image>
					<text class="empty-text">暂无相关课程</text>
					<text class="empty-tip">试试调整筛选条件吧</text>
				</view>
				
				<!-- 课程列表 -->
				<view 
					v-else
					class="course-item" 
					v-for="(course, index) in courseList" 
					:key="course.id"
					@click="goToCourseDetail(course)"
				>
					<view class="course-image">
						<image :src="course.image" mode="aspectFill"></image>
						<view class="learner-count" v-if="course.learnerCount">
							{{ course.learnerCount }}人学
						</view>
						<!-- <view class="video-count" v-if="course.videoNum">
							{{ course.videoNum }}课时
						</view> -->
					</view>
					<view class="course-info">
						<view class="course-title">{{ course.title }}</view>
						<view class="course-instructor" v-if="course.instructor">
							{{ course.instructor }}
						</view>
						<view class="course-tags" v-if="course.tags && course.tags.length > 0">
							<text class="tag" v-for="tag in course.tags.slice(0, 2)" :key="tag">{{ tag }}</text>
						</view>
						<view class="course-price">
							<text class="current-price">¥{{ course.price }}</text>
							<text class="original-price" v-if="course.originalPrice">¥{{ course.originalPrice }}</text>
						</view>
						<view class="course-bonuses" v-if="course.backBonus > 0 || course.welfareBonus > 0">
							<text class="bonus back-bonus" v-if="course.backBonus > 0">返现{{ course.backBonus }}积分</text>
							<text class="bonus welfare-bonus" v-if="course.welfareBonus > 0">福利{{ course.welfareBonus }}积分</text>
						</view>
						<view class="limited-offer" v-if="course.limitedOffer">限时优惠</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部导航栏 -->
		<view class="bottom-nav">
			<view class="nav-item active">
				<uni-icons type="book" size="24" color="#FF4757"></uni-icons>
				<text>精品课</text>
			</view>
			<view class="nav-item" @click="goToMyCourses">
				<uni-icons type="play" size="24" color="#999"></uni-icons>
				<text>我的课程</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import course_api from '@/api/course_api'
import { onLoad } from '@dcloudio/uni-app'


// 响应式数据
const statusBarHeight = ref(0)
const navBarHeight = ref(88)
// 轮播横幅
const bannerList = ref([])

const getIndexBanners = async () => {
	try {
		const res = await course_api.index()
		if (res.code === 200 && res.data && res.data.scroll_list) {
			bannerList.value = res.data.scroll_list
		}
	} catch (e) {
		console.error('获取横幅失败:', e)
	}
}
// 筛选条件
const filters = ref({
	limitedOffer: false,
	freeCourses: false
})
// 选中的分类和排序
const selectedCategory = ref('')
const selectedSort = ref('0')
// 分类选项
const categoryOptions = ref([
	{ value: '', text: '全部课程' }
])
// 排序选项
const sortOptions = ref([
	{ value: '0', text: '默认排序' },
	{ value: '0', text: '最新上架' },
	{ value: '1', text: '人气最高' },
	{ value: '2', text: '课时数' },
	{ value: '3', text: '价格升序' },
	{ value: '4', text: '价格降序' }
])
// 课程列表
const courseList = ref([])

// 方法
const getSystemInfo = () => {
	const systemInfo = uni.getSystemInfoSync()
	statusBarHeight.value = systemInfo.statusBarHeight
	// #ifdef MP-WEIXIN
	navBarHeight.value = systemInfo.statusBarHeight + 44
	// #endif
	// #ifdef APP-PLUS
	navBarHeight.value = systemInfo.statusBarHeight + 44
	// #endif
}

const goBack = () => {
	uni.navigateBack()
}

const goSearch = () => {
	uni.navigateTo({
		url: '/pages_course/search/search'
	})
}

const goToMyCourses = () => {
	uni.navigateTo({
		url: '/pages_course/my_courses/my_courses'
	})
}

const goToCourseDetail = (course) => {
	uni.navigateTo({
		url: `/pages_course/course_detail/course_detail?id=${course.id}`
	})
}

// 分类选择已通过uni-data-select组件处理

// 切换限时优惠
const toggleLimitedOffer = () => {
	filters.value.limitedOffer = !filters.value.limitedOffer
	filterCourses()
}

// 切换免费课程
const toggleFreeCourses = () => {
	filters.value.freeCourses = !filters.value.freeCourses
	filterCourses()
}

// 筛选课程
const filterCourses = () => {
	// 这里实现课程筛选逻辑
	console.log('筛选条件:', filters.value, selectedCategory.value, selectedSort.value)

	let data = {
		first_type: type_id.value,
		second_type: selectedCategory.value,
		sort: selectedSort.value,
		page: 1
	}
	if(filters.value.limitedOffer){
		data.discount_type = 1
	}
	if(filters.value.freeCourses){
		data.free = 1
	}

	course_api.excellencourseList(data).then(res => {
		console.log(res)
		if (res.code === 200 && res.data && res.data.list) {
			// 转换API数据为课程列表格式
			courseList.value = res.data.list.map(item => ({
				id: item.id,
				title: item.title,
				instructor: item.special_type_name || '专业讲师',
				price: ((item.discount_price || item.account || 0) / 100).toFixed(2), // 分转元
				originalPrice: item.discount_price && item.account && item.discount_price !== item.account ? (item.account / 100).toFixed(2) : null, // 分转元
				image: item.index_img || '/static/placeholder_doctor.png',
				learnerCount: item.study_num || 0,
				limitedOffer: item.discount_type === 1,
				videoNum: item.video_num || 0,
				backBonus: item.back_bon || 0,
				welfareBonus: item.fuli_bon || 0,
				tags: item.tags ? item.tags.split(',') : []
			}))
		}
	})
}

const special_type = ref(0)
const special_name = ref('')
const type_id = ref(0)

const getFirstType = () => {
	course_api.listExcellencourseFirstType().then(res => {
		console.log(res)
		if (res.code === 200 && res.data) {
			// 转换数据结构为uni-data-select需要的格式
			const options = res.data.map(item => ({
				value: item.id.toString(),
				text: item.name
			}))
			// 添加"全部课程"选项
			categoryOptions.value = [
				{ value: '', text: '全部课程' },
				...options
			]
		}
	})
}
const getSecondType = () => {
	course_api.listExcellencourseSecondType(type_id.value).then(res => {
		console.log(res)
		if (res.code === 200 && res.data) {
			// 转换数据结构为uni-data-select需要的格式
			const options = res.data.map(item => ({
				value: item.id.toString(),
				text: item.name
			}))
			// 添加"全部课程"选项
			categoryOptions.value = [
				{ value: '', text: '全部课程' },
				...options
			]
		}
	})
}

const onCategoryChange = (e) => {
	selectedCategory.value = e
	console.log('选择的分类:', e)
	// 自动触发课程筛选
	filterCourses()
}

const onSortChange = (e) => {
	selectedSort.value = e
	console.log('选择的排序:', e)
	filterCourses()
}

onLoad((options) => {
	type_id.value = options.type
	special_type.value = options.special_type
	special_name.value = options.special_name
	console.log('特殊类型ID:', options.special_type)
	console.log('类型ID:', options.type)
})

// 生命周期
onMounted(() => {
	
	getSystemInfo()
	if(type_id.value > 0){
		getSecondType()
	}
	if(special_type.value > 0){
		getFirstType()
	}
	// 获取顶部横幅，与course.vue一致
	getIndexBanners()
	
	// 初始加载课程列表
	filterCourses()
})
</script>

<style lang="scss">
.course-filter-page {
	min-height: 100vh;
	background-color: #fff;
	padding-bottom: 120rpx;
}

// 导航栏
.navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background-color: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	
	.nav-content {
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		
		.nav-left, .nav-right {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.nav-title {
			font-size: 36rpx;
			font-weight: 600;
			color: #FF4757;
		}
	}
}

.page-content {
	background-color: #fff;
}

// 主横幅
.main-banner {
	margin: 0;
	overflow: hidden;
	position: relative;

	.banner-swiper {
		height: 380rpx;
		overflow: hidden;
		position: relative;
	}

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

	.banner-content {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 32rpx 24rpx;
		background: linear-gradient(transparent, rgba(0,0,0,0.6));
		box-sizing: border-box;
	}

	.banner-title {
		display: block;
		font-size: 30rpx;
		color: #fff;
		font-weight: 600;
		margin-bottom: 6rpx;
		text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.4);
	}

	.banner-subtitle {
		display: block;
		font-size: 22rpx;
		color: rgba(255,255,255,0.9);
		line-height: 1.4;
		text-shadow: 0 1rpx 2rpx rgba(0,0,0,0.4);
	}
}

// 筛选栏
.filter-bar {
	display: flex;
	align-items: center;
	padding: 24rpx;
	background: #ffffff;
	border-bottom: 1rpx solid #f1f3f4;
	gap: 8rpx; // 减少间距
	flex-wrap: nowrap; // 不换行
	position: relative; // 添加相对定位
	z-index: 100; // 提高层级
	
	.filter-item {
		display: flex;
		align-items: center;
		padding: 12rpx 0rpx; // 恢复左右内边距
		cursor: pointer;
		transition: all 0.2s ease;
		font-size: 24rpx; // 稍微减小字体
		color: #495057;
		font-weight: 500;
		flex: 1; // 平均分配空间
		min-width: 0; // 允许压缩
		justify-content: center; // 居中显示
		position: relative; // 添加相对定位
		z-index: 101; // 提高层级
		
		// 让选择器组件自适应宽度
		uni-data-select { 
			width: 100%; 
			display: flex; 
			z-index: 102; // 最高层级
		}
		
		&:hover {
			background: #e9ecef;
			border-color: #dee2e6;
		}
		
		&.active {
			background: #FF4757;
			color: #ffffff;
			border-color: #FF4757;
			
			text { color: #ffffff; }
		}
		
		text { 
			color: inherit; 
			font-weight: 500;
			white-space: nowrap; // 文字不换行
			overflow: hidden; // 超出隐藏
			text-overflow: ellipsis; // 显示省略号
		}
		
		.filter-display {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 4rpx; // 减少间距
			width: 100%;
			
			text { 
				font-size: 24rpx; 
				color: inherit; 
				font-weight: 500;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}
	}
	
	.separator {
		width: 1rpx;
		height: 24rpx;
		background: #dee2e6;
		margin: 0 2rpx; // 减少间距
		flex: 0 0 auto; // 分隔符不压缩
	}
}

// 课程列表
.course-list {
	padding: 24rpx;
	background: #f8f9fa;
	position: relative; // 添加相对定位
	z-index: 1; // 降低层级，确保在筛选栏下方
	
	.course-item {
		display: flex;
		padding: 24rpx;
		background: #ffffff;
		border-radius: 12rpx;
		margin-bottom: 16rpx;
		box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.1);
		transition: all 0.2s ease;
		
		&:hover {
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
			transform: translateY(-2rpx);
		}
		
		.course-image {
			position: relative;
			margin-right: 20rpx;
			
			image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 8rpx;
			}
			
			.learner-count {
				position: absolute;
				bottom: 8rpx;
				left: 8rpx;
				background: rgba(0, 0, 0, 0.7);
				color: #fff;
				font-size: 20rpx;
				padding: 4rpx 8rpx;
				border-radius: 4rpx;
			}
			.video-count {
				position: absolute;
				bottom: 8rpx;
				right: 8rpx;
				background: rgba(0, 0, 0, 0.7);
				color: #fff;
				font-size: 20rpx;
				padding: 4rpx 8rpx;
				border-radius: 4rpx;
			}
		}
		
		.course-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			
			.course-title {
				font-size: 28rpx;
				color: #212529;
				line-height: 1.4;
				margin-bottom: 8rpx;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				overflow: hidden;
				font-weight: 600;
			}
			
			.course-instructor {
				font-size: 24rpx;
				color: #6c757d;
				margin-bottom: 12rpx;
			}
			
			.course-tags {
				display: flex;
				flex-wrap: wrap;
				gap: 8rpx;
				margin-bottom: 12rpx;
				
				.tag {
					font-size: 22rpx;
					color: #FF4757;
					background: #FFF5F5;
					padding: 4rpx 12rpx;
					border-radius: 20rpx;
					border: 1rpx solid #FF4757;
				}
			}
			
			.course-price {
				display: flex;
				align-items: center;
				gap: 12rpx;
				margin-bottom: 8rpx;
				
				.current-price {
					font-size: 32rpx;
					color: #FF4757;
					font-weight: 700;
				}
				
				.original-price {
					font-size: 24rpx;
					color: #adb5bd;
					text-decoration: line-through;
				}
			}
			
			.course-bonuses {
				display: flex;
				flex-wrap: wrap;
				gap: 8rpx;
				margin-bottom: 12rpx;
				
				.bonus {
					font-size: 22rpx;
					padding: 4rpx 12rpx;
					border-radius: 20rpx;
					border: 1rpx solid;
				}
				
				.back-bonus {
					color: #FF4757;
					border-color: #FF4757;
					background: #FFF5F5;
				}
				
				.welfare-bonus {
					color: #28a745;
					border-color: #28a745;
					background: #F2FFFC;
				}
			}
			
			.limited-offer {
				background: #FF4757;
				color: #fff;
				font-size: 20rpx;
				padding: 4rpx 12rpx;
				border-radius: 4rpx;
				align-self: flex-start;
			}
		}
	}

	// 空状态
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 0;
		text-align: center;
		
		.empty-image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 32rpx;
			opacity: 0.6;
		}
		
		.empty-text {
			font-size: 32rpx;
			color: #666;
			margin-bottom: 16rpx;
			font-weight: 500;
		}
		
		.empty-tip {
			font-size: 26rpx;
			color: #999;
			line-height: 1.4;
		}
	}
}

// 底部导航栏
.bottom-nav {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background: #ffffff;
	border-top: 1rpx solid #e9ecef;
	display: flex;
	z-index: 999;
	
	.nav-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 4rpx;
		transition: all 0.2s ease;
		
		text {
			font-size: 22rpx;
			color: #6c757d;
			font-weight: 500;
		}
		
		&.active {
			text {
				color: #FF4757;
			}
		}
	}
}
</style>