<template>
	<view class="grades-terms-page">
		<view class="grades-body">
			<view class="grades-change-title"></view>
			<text class="grades-title-desc">我们会根据您选择，为您匹配对应的学习内容</text>
			<view class="grades-terms-title terms-title-img"></view>
			<view class="grade-item-box">
				<view v-for="item in xueke_list" :key="item.id" @click="handleSelectXueke(item)"
					:class="['grade-item',{active: item.id == activeXueke}]">{{item.label}}</view>
			</view>
			<view class="grades-terms-title grades-title-img"></view>
			<view class="grade-item-box">
				<view v-for="item in nianji_list" :key="item.id" @click="handleSelectGrade(item)"
					:class="['grade-item', {active: item.id == activeNianji}]">{{item.label}}</view>
			</view>
			<view class="grade-line"></view>
			<button class="grade-confirm-btn" @click="handleConfirm"></button>
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		toRefs
	} from "vue";
	import {
		nianji_list,
		xueke_list,
	} from "@/utils/constant.js";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {getUserIdentity} from "@/utils/common.js"
	import cacheManager from "@/utils/cacheManager.js"
		
	function useSelectGrade() {
		const userCode = getUserIdentity();
		const data = reactive({
			activeNianji: null, // 当前年级
			activeXueke: null, // 当前学期
		});

		onLoad((nianji,cardId) => {
			if (userCode !== 'Visitor') {
				const {
					nianji: nianji_,
					cardId: cardId_
				} = cacheManager.get('auth');
				data.activeNianji = nianji_;
				data.activeXueke = cardId_;
			} else {
				data.activeNianji = nianji;
				data.activeXueke = cardId;
			}
	
		});

		// 选择 年级+学期
		function handleConfirm() {
			if (!data.activeNianji) {
				uni.showToast({
					title: "请选择年级",
					duration: 2000,
				});
				return;
			}

			if (!data.activeXueke) {
				uni.showToast({
					title: "请选择学科",
					duration: 2000,
				});
				return;
			}

			goDAOToStudy();
		}

		// 跳转 岛 学习
		function goDAOToStudy() {
			if (userCode !== 'Visitor') {
				const auth = cacheManager.get('auth');
				cacheManager.updateObject('auth', {
					nianji: data.activeNianji,
					zhangId: data.activeNianji == auth.nianji && data.activeXueke == auth.cardId ? auth.zhangId: 0,
					cardId: data.activeXueke,
				})
				// 数序
				uni.redirectTo({
					url: `/pages/study/index?flag=selectGrades`
				})
			} else {
				// 数序
				uni.redirectTo({
					url: `/pages/study/index?nianji=${data.activeNianji}&cardId=${data.activeXueke}&zhangId=0&flag=selectGrades`
				})
			}

		}

		return {
			...toRefs(data),

			// 方法
			handleConfirm, // 选择年级+学科
		};
	}

	const {
		activeNianji,
		activeXueke,
		handleConfirm
	} = useSelectGrade()

	function handleSelectGrade(item) {
		activeNianji.value = item.id;
	}

	function handleSelectXueke(item) {
		activeXueke.value = item.id;
	}
</script>