<template>
	<view class="container">
		<!-- 搜索 -->
		<u-search @search="toSearch" :show-action="false" shape="round" placeholder="搜索您想要的内容"
			v-model="searchForm.keyword"></u-search>
		<!-- tabs -->
		<view style="padding-top: 20rpx;display: flex;">
			<u-tabs style="flex: 1;" :list="tabsList" :is-scroll="true" font-size="24" :bold="false"
				inactive-color="#000000" active-color="#000000" :bar-style="{'background-color': '#2979ff'}"
				:gutter="30" height="45" v-model="currentTab" @change="changeTab"></u-tabs>
			<!-- <u-icon name="list" style="flex: 0 0 auto;padding-left: 20rpx;"></u-icon> -->
		</view>
		<!-- 列表 -->
		<view class="course-list">
			<view v-for="(course,index) in filterCourses" :key="course.id" @click="toPage(course)">
				<view class="course-item">
					<view class="course-item-image">
						<image class="course-image" :src="course.cover" mode="aspectFill"></image>
					</view>
					<view class="course-item-content">
						<view class="course-title">
							<text>{{ course.courseName }}</text>
							<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.courseType }}</view>
						<view class="course-teacher">
							<u-icon name="account" size="28"></u-icon>
							{{ course.name }}
						</view>
						<view class="course-date">
							<u-icon name="clock" size="28"></u-icon>
							{{ getDateWeek(course.courseDate) }}
						</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>
						<button :class="['button', getButtonClass(course)]">{{ getButtonText(course) }}</button>
					</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,
	})
	const pageNumber = ref(1)
	const pageSize = ref(20)
	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,
		courseName: "前端开发基础前端开发基础前端开发基础",
		courseType: "精英训练营",
		name: "张老师",
		courseDate: "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) {
		const currentDate = new Date();
		const classDate = new Date(course.courseDate);

		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 ? "点击查看" : "点击查看回放";
			}
		}

		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.courseDate) ? 'purchased' : 'replay') :
				'member-free';
		}
		if (courseMember[course.viewMode] === '付费') {
			return course.hasBuy ? (new Date() < new Date(course.courseDate) ? 'purchased' : 'replay') : 'purchase';
		}
		return 'error';
	}


	// 日期格式：xxxx年xx月xx日（星期x）
	function getDateWeek(val) {
		const date = new Date(val);
		const daysOfWeek = ['日', '一', '二', '三', '四', '五', '六'];
		const year = date.getFullYear();
		const month = date.getMonth() + 1; // 注意：月份从0开始
		const day = date.getDate();
		const dayOfWeek = daysOfWeek[date.getUTCDay()];
		// const result = `${year}年${month}月${day}日（星期${dayOfWeek}）`
		return `${year}年${month}月${day}日（星期${dayOfWeek}）`
	}

	// 切换搜索框下面的tab
	function changeTab(index) {
		currentTab.value = index;
		courseStore.setCurrentTab(index)
		if (index === 0) {
			filterCourses.value = courses.value
			return
		}
		filterCourses.value = courses.value.filter(item => item.courseType == tabsList.value[index].name)
	}

	function toSearch(e) {
		pageNumber.value = 1
		search(e)
	}
	// 搜索
	function search(e) {
		searchForm.value.keyword = e
		searchForm.value.pageNumber = pageNumber.value
		searchForm.value.pageSize = pageSize.value
		courses.value = pageNumber.value == 1 ? [] : courses.value
		loadMoreStatus.value = 'loading'
		loadCourseList(searchForm.value).then(res => {
			if (res?.data) {
				total.value = res.count;
				courses.value = [...courses.value, ...res.data];
				const i = currentTab.value
				if (i == 0) {
					filterCourses.value = [...courses.value];
				} else {
					filterCourses.value = courses.value.filter(item => item.courseType == tabsList.value[i].name)
				}
				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
		}
	}
	// 初始化
	function init() {
		loadCourseCate().then(res => {
			if (res?.data) {
				tabsList.value = [{
					code: '',
					name: '全部'
				}, ...res.data]
			}
		})
		pageNumber.value = 1;
		search("");
		// 初始化页面，获取数据
		// filterCourses.value = courses.value
	}

	function toPage(course) {
		uni.navigateTo({
			url: `/pages/goOnEdu/course/courseDetail/courseDetail?id=${course.id}&name=${course.courseName}`
		});
	}

	function loadmore() {
		if (courses.value.length === total.value) {
			return;
		}
		search(searchForm.value.keyword);
	}
	onMounted(() => {
		isMember.value = authStore.userInfo.isMember === 1 ? true : false
		// console.log(authStore.userInfo.isMember)
		init();
		watch(currentTab, (newValue) => {
			courseStore.setCurrentTab(newValue); // 如果需要在切换时更新 Pinia 状态
		});
	});
	onReachBottom(() => {
		loadmore()
	})
</script>

<style lang="scss" scoped>
	.container {
		// padding: 20px;
	}

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

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

		}

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

			.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('http://www.gzrea.org.cn:8543/icon/wxmp/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>