<template>
	<view class="container">
		<!-- 搜索 -->
		<u-search @search="search" :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.imgUrl" 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 ? 'https://sylwt.top/api/visitor/resources/image?name=/ydl/menber-center/edu-icon/favi-icon.png' : 'https://sylwt.top/api/visitor/resources/image?name=/ydl/menber-center/edu-icon/no-favi-icon.png'"
								@click.stop="collectCourse(course.id, index)">
							</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">￥{{ course.price }}元</view>
						<button :class="['button', getButtonClass(course)]">{{ getButtonText(course) }}</button>
					</view>
				</view>
				<u-line />
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,onMounted,watch
	} from 'vue';
	import {
	} from '@dcloudio/uni-app'
	import { loadCourseCate, loadCourseList } from "@/api/edu.js"
	import { useCourseStore } from "@/store/courseStore.js"
	const courseStore = useCourseStore();
	const isMember = ref(false);
	const tabsList = ref([]);
	const currentTab = ref(courseStore.currentTab); 
	const searchForm = ref({
		keyword: "",
		pageNumber: 1,
		pageSize: 10,
	})
	const courseMember = {
		1: "免费",
		2: "会员免费",
		3: "付费",
	}
	// 展示的课程
	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,
			payType: "免费" // 新增字段，标识课程的付费类型
		},
		{
			id: 2,
			courseName: "Vue.js 从入门到精通",
			courseType: "领袖锻造营",
			name: "李老师",
			courseDate: "2023-09-15",
			imgUrl: "https://pic3.zhimg.com/v2-e52354ffdbd94a8e0a7649eacd34a788_r.jpg?source=1940ef5c",
			price: 199.00,
			hasBuy: false,
			hasFavi: false,
			payType: "会员免费"
		},
		{
			id: 3,
			courseName: "React 开发实战",
			courseType: "领袖锻造营",
			name: "王老师",
			courseDate: "2023-11-05",
			imgUrl: "https://desk-fd.zol-img.com.cn/t_s960x600c5/g4/M03/00/0C/Cg-4zFS8bC-Ie9zBADCvovJAqiEAATJ8wDX__cAMK-6184.jpg",
			price: 149.00,
			hasBuy: false,
			hasFavi: false,
			payType: "付费"
		},
		{
			id: 4,
			courseName: "Node.js 全栈开发",
			courseType: "合规专训营",
			name: "赵老师",
			courseDate: "2023-08-20",
			imgUrl: "https://pic3.zhimg.com/v2-e52354ffdbd94a8e0a7649eacd34a788_r.jpg?source=1940ef5c",
			price: 299.00,
			hasBuy: true,
			hasFavi: false,
			payType: "付费"
		},
		{
			id: 5,
			courseName: "移动端开发技巧",
			courseType: "精英训练营",
			name: "钱老师",
			courseDate: "2025-07-18",
			imgUrl: "https://desk-fd.zol-img.com.cn/t_s960x600c5/g4/M03/00/0C/Cg-4zFS8bC-Ie9zBADCvovJAqiEAATJ8wDX__cAMK-6184.jpg",
			price: 89.00,
			hasBuy: true,
			hasFavi: false,
			payType: "付费"
		},
		{
			id: 6,
			courseName: "11Vue.js 从入门到精通",
			courseType: "领袖锻造营",
			name: "李老师11",
			courseDate: "2023-09-15",
			imgUrl: "https://pic3.zhimg.com/v2-e52354ffdbd94a8e0a7649eacd34a788_r.jpg?source=1940ef5c",
			price: 199.00,
			hasBuy: true,
			hasFavi: false,
			payType: "会员免费"
		},
		{
			id: 7,
			courseName: "113Vue.js 从入门到精通",
			courseType: "领袖锻造营",
			name: "李老师11",
			courseDate: "2025-09-15",
			imgUrl: "https://pic3.zhimg.com/v2-e52354ffdbd94a8e0a7649eacd34a788_r.jpg?source=1940ef5c",
			price: 199.00,
			hasBuy: true,
			hasFavi: false,
			payType: "会员免费"
		},
	]);

	// 按钮的文字
	function getButtonText(course) {
		const currentDate = new Date();
		const classDate = new Date(course.courseDate);

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

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

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


	// 按钮的样式
	function getButtonClass(course) {
		if (courseMember[course.payType] === "免费") return 'free';
		if (courseMember[course.payType] === "会员免费") {
			if (isMember.value) return 'member-free';
			return course.hasBuy ? (new Date() < new Date(course.courseDate) ? 'purchased' : 'replay') :
				'member-free';
		}
		if (courseMember[course.payType] === "付费") {
			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 search(e) {
		console.log(e, "searchForm.keyword")
	}
	// 收藏
	function collectCourse(id,index) {
		// 联调后端，
		// 返回成功后
		courses.value[index].hasFavi = !courses.value[index].hasFavi
	}
	// 初始化
	function init() {
		loadCourseCate().then(res=>{
			if(res?.data){
				tabsList.value = [{ code: '', name: '全部'}, ...res.data]
			}
		})
		searchForm.value.keyword = ""
		loadCourseList(searchForm.value).then(res=>{
			if(res?.data){
				courses.value = res.data;
				filterCourses.value = [...courses.value];
			}
		})
		// 初始化页面，获取数据
		// filterCourses.value = courses.value
	}

	function toPage(course) {
		uni.navigateTo({
			url: `/pages/goOnEdu/course/courseDetail/courseDetail?id=${course.id}&name=${course.courseName}`
		});
	}
	onMounted(() => {
		const userInfo = uni.getStorageSync("userinfo");
		isMember.value = userInfo.isMember
	    init();
	    watch(currentTab, (newValue) => {
	        courseStore.setCurrentTab(newValue); // 如果需要在切换时更新 Pinia 状态
	    });
	});
</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('https://sylwt.top/api/visitor/resources/image?name=/ydl/menber-center/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>