<template>
	<view class="grades-terms-page">
		<view class="icon-title-navBar-box">
			<!-- 返回按钮↓ -->
			<view class="nav-bar-icon" @click="handleBack"></view>
		</view>
		<view class="grade-item-box">
			<view :key="xueke.id" @click="handleSelectXueke(xueke)" v-for="xueke in xuekeData"
				:class="['grade-item',{active: xueke.id == activeXueke}]">{{xueke.lable}}</view>
		</view>
		<view class="subject-body">
			<view class="subject-content-box">
				<!-- 产品 -->
				<view v-for="item in xuekeList" :key="item.id" @click="handleSelectGrade(item)"
					:class="['subject-item', {active: item.id == activeProduct}]">
					<view class="subject-item-border">
						<img :src="item.cover" class="subject-item-img" />
						<view class="subject-item-text">{{item.lable}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="grade-line"></view>
		<button class="grade-confirm-btn" @click="handleConfirm"></button>
	</view>
</template>

<script setup>
	import {
		reactive,
		toRefs,
		computed
	} from "vue";
	import * as httpApi from "@/api/selectGradesTerms.js";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		getUserIdentity,
		findRootNode,
		findTreeNode
	} from "@/utils/common.js"
	import cacheManager from "@/utils/cacheManager.js"
	import {
		getCommonTree,
		getIndexTree
	} from "../../api/selectGradesTerms";

	function useSelectGrade() {
		const userCode = getUserIdentity();

		const data = reactive({
			activeProduct: null, // 当前年级
			activeXueke: 1, // 当前学期
			activeTipFlag: null, // 当前学期
			xuekeData: [], // 学科总数据
		});

		onLoad(({
			productId,
			xuekeId,
			tipFlag
		}) => {
			if (userCode !== 'Visitor') {
				initUserProducts();
			} else {
				data.activeProduct = productId;
				data.activeXueke = xuekeId || 1; // 默认选中数学
				data.activeTipFlag = tipFlag || '0';
				initVisitProducts();
			}
		});

		// 初始化游客产品数据
		function initVisitProducts() {
			httpApi.getCommonTree().then(res => {
				data.xuekeData = res.data || [];
			})
		}

		function initUserProducts() {
			httpApi.getIndexTree().then(res => {
				data.xuekeData = res.data || [];
				const {
					levelId,
				} = cacheManager.get('auth');
				if (levelId) {
					// LevelId 翻找根节点学科，执行选中高亮操作
					const xuekeObj = findRootNode(data.xuekeData, levelId, 'levelId');
					const productObj = findTreeNode(data.xuekeData, levelId, 'children','levelId');
					data.activeProduct = productObj.id;
					data.activeXueke = xuekeObj.id;
				} else {
					data.activeProduct = null;
					data.activeXueke = 1
				}
			})
		}

		// 选择 年级+学期
		function handleConfirm() {
			if (!data.activeXueke) {
				uni.showToast({
					title: "请选择课程类别",
					duration: 2000,
					icon: 'error'
				});
				return;
			}
			if (!data.activeProduct) {
				uni.showToast({
					title: "请选择课程等级",
					duration: 2000,
					icon: 'error'
				});
				return;
			}
			goDAOToStudy();
		}

		// 跳转 岛 学习
		function goDAOToStudy() {
			const Product = data.xuekeData.find(item => item.id == data.activeXueke).children.find(item => item.id == data
				.activeProduct)
			const levelId = Product.levelId;
			const typeId = Product.typeId;
			const subjectId = Product.subjectId;

			if (userCode !== 'Visitor') {
				const auth = cacheManager.get('auth');
				cacheManager.updateObject('auth', {
					typeId: typeId,
					levelId: levelId,
					subjectId: subjectId,
					zhangId: data.activeProduct == auth.nianji && data.activeXueke == auth.cardId ? auth.zhangId :
						0,
					currentZhang: 0
				})
				cacheManager.remove('daoPageCache')
				uni.redirectTo({
					url: `/pages/study/index`
				})
			} else {
				if (typeId == 1) {
					// 新岛
					uni.redirectTo({
						url: `/pages/study/index?levelId=${levelId}&typeId=${typeId}&subjectId=${subjectId}&tipFlag=${data.activeTipFlag}`
					})
				} else {
					// 旧岛
					uni.redirectTo({
						url: `/pages/study/index?levelId=${levelId}&typeId=${typeId}&subjectId=${subjectId}&zhangId=0&tipFlag=${data.activeTipFlag}`
					})
				}

			}

		}

		function handleBack() {
			if (userCode !== 'Visitor') {
				uni.redirectTo({
					url: `/pages/study/index`
				})
			} else {
				uni.redirectTo({
					url: '/pages/login/index'
				})
			}
		}

		return {
			...toRefs(data),
			handleBack,
			// 方法
			handleConfirm, // 选择年级+学科
		};
	}

	const {
		activeProduct,
		activeXueke,
		xuekeData,
		handleConfirm,
		handleBack
	} = useSelectGrade()

	const xuekeList = computed(() => {
		if (!xuekeData.value.length) {
			return []
		}
		const d_id = activeXueke.value;
	
		return xuekeData.value.find(item => item.id == d_id).children
	})

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

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