<template>
	<view class="container">
		<view class="header-box">
			<u-search @search="toSearch" :show-action="false" shape="round" placeholder="搜索您想要的内容"
				v-model="searchForm.keyword"></u-search>
			<!-- tabs -->
			<view class="tabs-container">
				<u-tabs
				:list="tabsList" 
				:is-scroll="true" 
				font-size="32" 
				:bold="false"
				inactive-color="#000000" 
				active-color="#ffffff"
				:bar-style="{'background-color': '#2979ff'}"
				:active-item-style="{'background-color': '#2979ff', 'border-radius':'30rpx'}"
				:gutter="40" 
				height="55" 
				v-model="currentTab" 
				:show-bar="false"
				duration="0"
				@change="changeTab"></u-tabs>
				<!-- <scroll-view scroll-x="true" style="width:100%;" :scroll-with-animation="true" :show-scrollbar="true">
					
				</scroll-view> -->
				<!-- <u-icon name="list" style="flex: 0 0 auto;padding-left: 20rpx;"></u-icon> -->
			</view>
		</view>
		<!-- 搜索 -->

		<!-- 列表 -->
		<view class="course-list">
			<view v-for="(course,index) in filterCourses" :key="course.id" class="course-list-item">
				<view class="course-item">
					<view class="course-item-image">
						<image class="course-image" :src="course.thumImg ? course.thumImg 
						: (course.cover ? course.cover 
						: `${FILE_URL}/peixunyugao.jpg`)"
							mode="aspectFit" @click="toPage(course)"></image>
					</view>
					<view class="course-item-content">
						<view class="course-title">
							<text @click="toPage(course)">{{ course.title }}</text>
							<!-- 1.隐藏收藏功能 -->
							<!-- <image style="width: 25rpx;height: 25rpx;padding-left: 20rpx;"
								:src="course.hasFavi ? `${FILE_URL}/edu-icon/favi-icon.png` : `${FILE_URL}/edu-icon/no-favi-icon.png`"
								@click.stop="collectCourse(course.id, index, course.hasFavi)">
							</image> -->
						</view>
						<view class="course-type">{{ course.type }}</view>
						<view class="course-teacher">
							<u-icon name="account" size="28"></u-icon>
							{{ course.lecturer }}
						</view>
						<view class="course-date">
							<u-icon name="clock" size="28"></u-icon>
							{{ getDateWeek(course.date) }}
						</view>
						<!-- <view class="course-price"
							v-if=" (course.viewMode === '3') || (isMember && course.viewMode==='2')">
							￥{{ isMember ? course.priceMember : course.price }}元
						</view>
						<view v-else style="height: 30rpx;width: 100%;"></view> -->
						<!-- 如果没结束 -->
						<view class="func" v-if="course.status !== '2' && course.status !== '3'"
							@click="toPage(course)">
							<!-- 如果是免费，直接显示免费 -->
							<view v-if="course.viewMode==='1'" class="func-box" style="justify-content: flex-end;">
								<view class="button free">免费</view>
							</view>
							<view v-else-if="course.viewMode==='2' && isMember" class="func-box">
								<view class="price">￥{{ course.price }}元</view>
								<view class="button member-free">会员免费</view>
							</view>
							<view v-else-if="course.viewMode==='2' && !isMember" class="func-box">
								<view style="flex: 0 0 auto;display: flex;align-items: center;">
									<view class="member-free">
										会员免费
									</view>
									<view class="not-member-price">
										非会员：￥{{course.price}}元
									</view>
								</view>
								<view :class="['button', course.hasBuy ? 'free' : 'buy']">
									{{course.hasBuy ? '已购买' : '立即购买'}}
								</view>
							</view>
							<view v-else-if="course.viewMode==='3' && course.price===course.priceMember"
								class="func-box">
								<view class="price">￥{{ course.price }}元</view>
								<view :class="['button', course.hasBuy ? 'free' : 'buy']">
									{{course.hasBuy ? '已购买' : '立即购买'}}
								</view>
							</view>
							<view v-else-if="course.viewMode==='3' && course.price!==course.priceMember"
								class="func-box">
								<view style="flex: 0 0 auto;display: flex;align-items: center;">
									<view class="member-free">
										{{`会员：${course.priceMember}元`}}
									</view>
									<view class="not-member-price">
										非会员：￥{{course.price}}元
									</view>
								</view>
								<view :class="['button', course.hasBuy ? 'free' : 'buy']">
									{{course.hasBuy ? '已购买' : '立即购买'}}
								</view>
							</view>
						</view>
						<!-- <button :class="['button', getButtonClass(course)]">{{ getButtonText(course) }}</button> -->
						<!-- 如果课程结束了 -->
						<view class="func" v-else>
							<!-- regType： 0 线下 ；1 线上 -->
							<view v-if="course.regType==='0' && course.status === '2'" class="func-box"
								style="justify-content: flex-end;">
								<view class="button over" @click="toPage(course)">已结束</view>
							</view>
							<view v-if="course.regType==='0' && course.status === '3' && !course.actId" class="func-box"
								style="justify-content: flex-end;">
								<view class="button over" @click="toPage(course)">已结束</view>
							</view>
							<view v-if="course.regType==='0' && course.status === '3' && course.actId" class="func-box"
								style="justify-content: flex-end;">
								<view class="button-long over" @click="toAct(course.actId)">已结束，点击查看活动</view>
							</view>
							<view v-if="course.regType==='1'" class="func-box" style="justify-content: flex-end;">
								<view class="button-long over" @click="toPage(course)">已结束，点击查看回放</view>
							</view>
						</view>
					</view>
				</view>
				<u-line />
			</view>
		</view>
		<view style="margin: 20rpx 0;">
			<u-loadmore :status="loadMoreStatus" @loadmore="loadmore" :load-text="loadText" />
			<!-- <uni-load-more :status="loadMoreStatus" :load-text="loadText" @loadmore="loadmore"></uni-load-more> -->
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		watch,
	} from 'vue';
	import {
		onReachBottom
	} from '@dcloudio/uni-app'
	import {
		loadCourseCate,
		loadCourseList,
		courseFavi,
		courseCancelFavi
	} from "@/api/edu.js"
	import {
		useCourseStore
	} from "@/store/courseStore.js"
	import {
		useAuthStore
	} from '@/store/authStore.js';
	import configService from '@/utils/baseurl.js'
	const FILE_URL = configService.FILE_URL;
	const courseStore = useCourseStore();
	const authStore = useAuthStore();
	const isMember = ref(false);
	const tabsList = ref([]);
	const currentTab = ref(courseStore.currentTab);
	const searchForm = ref({
		keyword: "",
		pageNumber: 1,
		pageSize: 10,
		type: ""
	})
	const pageNumber = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const loadMoreStatus = ref('loadmore')

	const courseMember = {
		1: "免费",
		2: "会员免费",
		3: "付费",
	}
	const loadText = {
		loadmore: '点击或上拉加载更多',
		loading: '努力加载中',
		nomore: '已加载全部数据'
	}
	// 展示的课程
	const filterCourses = ref([]);
	const courses = ref([{
		id: 1,
		title: "前端开发基础前端开发基础前端开发基础",
		type: "精英训练营",
		name: "张老师",
		date: "2023-10-01",
		imgUrl: "https://tse3-mm.cn.bing.net/th/id/OIP-C.YKoZzgmubNBxQ8j-mmoTKAHaEK?rs=1&pid=ImgDetMain",
		price: 99.00,
		hasBuy: false,
		hasFavi: true,
		viewMode: "免费" // 新增字段，标识课程的付费类型
	}, ]);

	// 列表样式-按钮的文字
	function getButtonText(course) {
		console.log(course)
		// const currentDate = new Date();
		// const classDate = new Date(formatDateS(course.date));
		// if(currentDate > classDate) {

		// }
		if (course.viewMode === '1') {
			return "免费";
		}
		if (course.viewMode === '2') {
			if (isMember.value) return "会员免费";
			if (!course.hasBuy && !isMember.value) return "会员免费";
			if (course.hasBuy) {
				// return currentDate < classDate ? "点击查看" : "点击查看回放";
				return "点击查看";
			}
		}

		if (course.viewMode === '3') {
			if (!course.hasBuy) return "点击购买";
			return currentDate < classDate ? "点击查看" : "点击查看回放";
		}

		return "error"; // 默认返回
	}

	// 列表样式-按钮的样式
	function getButtonClass(course) {
		if (courseMember[course.viewMode] === '免费') return 'free';
		if (courseMember[course.viewMode] === '会员免费') {
			if (isMember.value) return 'member-free';
			return course.hasBuy ? (new Date() < new Date(course.date) ? 'purchased' : 'replay') :
				'member-free';
		}
		if (courseMember[course.viewMode] === '付费') {
			return course.hasBuy ? (new Date() < new Date(course.date) ? 'purchased' : 'replay') : 'purchase';
		}
		return 'error';
	}

	function formatDateS(dateStr) {
		return dateStr.replace(" ", "T");
	}

	// 日期格式：xxxx年xx月xx日（星期x）
	function getDateWeek(dateStr) {
		// 将日期字符串转换为 Date 对象
		const date = new Date(dateStr.replace(/-/g, '/'));
		// 检查日期是否有效
		if (isNaN(date.getTime())) {
			return dateStr; // 如果无效，返回原字符串
		}
		// 获取年月日
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		// 获取星期几
		const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
		const weekday = weekdays[date.getDay()];
		// 获取时分
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		// 组合成新格式
		return `${year}-${month}-${day}(星期${weekday}) ${hours}:${minutes}`;
	}

	// 切换搜索框下面的tab
	function changeTab(index) {
		// 0618重写，切换时，pageNumber为1
		currentTab.value = index;
		courseStore.setCurrentTab(index)
		pageNumber.value = 1
		search(searchForm.value.keyword)
	}
	// 搜索
	function toSearch(e) {
		// 搜索时pageNumber为1
		pageNumber.value = 1
		search(e)
	}
	// 获取列表数据
	function search(e) {
		// 如果是全部，则不传type这个值
		searchForm.value = {
			keyword: e,
			pageNumber: pageNumber.value,
			pageSize: pageSize.value,
			...(tabsList.value[currentTab.value].code && {
				courseType: tabsList.value[currentTab.value].code
			})
		}
		loadMoreStatus.value = 'loading'
		loadCourseList(searchForm.value).then(res => {
			if (res?.data) {
				total.value = res.count;
				// 如果pageNumber为1，清空courses
				courses.value = pageNumber.value == 1 ? [] : courses.value
				courses.value = [...courses.value, ...res.data];
				filterCourses.value = courses.value
				loadMoreStatus.value = total.value === courses.value.length ? 'nomore' : 'loadmore';
				pageNumber.value++;
			}
		})
	}
	// 收藏
	async function collectCourse(id, index, hasFavi) {
		try {
			let res;
			if (hasFavi) {
				res = await courseCancelFavi({
					id
				})
			} else {
				res = await courseFavi({
					id
				})
			}
			if (res.code == 0) {
				courses.value[index].hasFavi = !courses.value[index].hasFavi
			}
		} catch (err) {
			courses.value[index].hasFavi = courses.value[index].hasFavi
		}
	}
	// 初始化：获取分类数据和列表数据
	async function init() {
		const res = await loadCourseCate()
		if (res?.data) {
			tabsList.value = [{
				code: '',
				name: '全部',
			}, ...res.data]
			pageNumber.value = 1;
			search("");
		}
	}
	// 跳转到课程详情页
	function toPage(course) {
		uni.navigateTo({
			url: `/pages/goOnEdu/course/courseDetail/courseDetail?id=${course.id}&title=${course.title}`
		});
	}
	// 加载更多
	function loadmore() {
		if (courses.value.length === total.value) {
			return;
		}
		search(searchForm.value.keyword);
	}

	function toAct(actId) {
		// console.log(actId);
		uni.navigateTo({
			url: `/pages/dynamic/dynamicDetail/dynamicDetail?id=${actId}`
		})
	}

	onMounted(() => {
		isMember.value = authStore.userInfo.isMember === 1 ? true : false
		init();
		watch(currentTab, (newValue) => {
			courseStore.setCurrentTab(newValue); // 如果需要在切换时更新 Pinia 状态
		}); 
	});
	onReachBottom(() => {
		loadmore()
	})
</script>
<style>
	::v-deep(.u-scroll-box .u-tab-item) {
		margin-right: 20rpx;
	}
</style>
<style lang="scss" scoped>
	.container {
		// padding: 20px;
		// width: 100vw;
		// overflow: hidden;
		.header-box{
			@include topMagnet();
			background: #ffffff;
		}
	}

	.title {
		font-size: 48rpx;
		margin-bottom: 30rpx;
	}

	.tabs-container {
		padding: 40rpx 0 35rpx;
		// display: flex;
		// width: 100%;
		/* 确保宽度足够 */
		// overflow-x: auto;
		/* 横向滚动 */
		// -webkit-overflow-scrolling: touch;
		/* 在iOS上启用流畅滚动 */
	}
	.course-list-item{
		padding: 20rpx 0;
		&:first-child{
			padding: 0 0 20rpx;
		}
	}
	.course-item {
		// margin: 20rpx 0;
		display: flex;
		overflow: hidden;

		.course-item-image {
			width: 200rpx;
			height: 260rpx;
			flex: 0 0 auto;
			margin-right: 20rpx;

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

		}

		.course-item-content {
			flex: 1;
			position: relative;

			view {
				margin-bottom: 15rpx;
			}

			.course-title {
				font-weight: bold;
				margin-right: 10px;
				font-size: 28rpx;
				color: #000;
			}

			.course-type,
			.course-teacher,
			.course-date,
			.course-price {
				font-size: 30rpx;
				color: #000;
			}

			.course-price {
				color: #fe0000;
				letter-spacing: 2rpx;
			}

			.func {
				display: flex;
				justify-content: space-between;
				align-items: flex-end;
				font-size: $uni-font-size-2;
				font-weight: bold;
				margin-top: 10rpx;

				view {
					margin-bottom: 0rpx;
				}

				.func-box {
					display: flex;
					justify-content: space-between;
					width: 100%;
					align-items: center;
				}

				.button {
					text-align: center;
					width: 130rpx;
				}

				.button-long {
					text-align: center;
					width: 270rpx;
				}

				.price {
					color: $uni-color-error;
					font-size: $uni-title-font-size-2;
				}

				.not-member-price {
					font-size: $uni-font-size-3;
					color: $uni-text-color-grey;
					text-align: end;
				}

				.buy {
					padding: 6rpx 25rpx;
					background-color: $uni-color-error;
					border-radius: $uni-card-border-radius;
					color: $uni-text-color-inverse;
				}

				.free {
					padding: 6rpx 25rpx;
					background-color: $uni-color-primary;
					border-radius: $uni-card-border-radius;
					color: $uni-text-color-inverse;
				}

				.over {
					padding: 6rpx 25rpx;
					border-radius: $uni-card-border-radius;
					color: $uni-text-color-inverse;
					background-color: #8f9092;
				}

				.member-free {
					padding: 10rpx 20rpx;
					@include backgroundImg('https://www.gzrea.cn/wxmp/static/icon/bg-label.png');
					color: $uni-text-color;
				}
			}

			.button::after {
				content: none;
				/* 移除内容 */
			}

			// .button {
			// 	position: absolute;
			// 	right: 0;
			// 	bottom: 0;
			// 	min-width: 80px;
			// 	padding: 0 40rpx;
			// 	white-space: nowrap;
			// 	height: 45rpx;
			// 	line-height: 45rpx;
			// 	font-size: 22rpx;
			// 	/* padding: 0; */
			// 	border-radius: 50rpx;
			// 	color: white;
			// 	border: none;
			// }

			// .free {
			// 	background-color: #006af4;
			// }

			// .purchase {
			// 	background-color: #fe0000;
			// }

			// .member-free {
			// 	background-color: transparent;
			// 	background-image: url('https://www.gzrea.cn/wxmp/static/icon/bg-label.png');
			// 	background-size: cover;
			// 	background-repeat: no-repeat;
			// 	color: #000;
			// 	height: initial;
			// 	padding: 6rpx 0 3rpx;
			// 	border-radius: 0;
			// }

			// .replay {
			// 	background-color: #006af4;
			// }

			// .purchased {
			// 	background-color: #006af4;
			// }
		}
	}
</style>