<template>
	<view class="ezy-exam-page" :style="{backgroundImage: 'url(' + courseBjFun() + ')'}">
		<view class="ezy-navBar-box">
			<view @click="handleBack" class="nav-bar-icon"></view>
			<text class="nav-bar-title">学习</text>
		</view>
		<view>
			<template v-for="item in data.wordList">
				<mainCardVue :active-word="activeWord" :active-words="activeWords" v-if="item.id == data.activeId"
					:key="item.id">
				</mainCardVue>
			</template>
		</view>
		<view>
			底部
			<view>收藏</view>
			<view @click="prevWord" v-if="!isFirst">上一词</view>
			<view @click="nextWord" v-if="!isLast">下一词</view>
			<view v-if="isLast">完成</view>
		</view>
	</view>
</template>

<script setup>
	import mainCardVue from "./components/mainCard.vue";
	import {
		ref,
		reactive,
		computed
	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import * as httpApi from "@/api/word.js"

	function courseBjFun() {
		return 'static/images/course/couse-shuxue-bj.png'
	}

	function chunkArray(arr, chunkSize) {
		const result = [];
		for (let i = 0; i < arr.length; i += chunkSize) {
			result.push(arr.slice(i, i + chunkSize));
		}
		return result;
	}

	function handleBack() {}

	const data = reactive({
		jieId: null, // 节/单元ID
		activeId: null, // 当前单词
		subjectId: null, // 学科ID
		levelId: null, // 等级
		jieName: '', // 节/单元名称
		count: 0, // 单词总数
		title: '', // 版本+年级+学期
		studyCount: 0, // 已学习总数
		wordList: [], // 单词列表
		arrayList: [], // 整合数据
    wordInfo: null, // 单词详情数据
	})

	onLoad(({
		jieId,wordId
	}) => {
		data.jieId = jieId;
    data.activeId = wordId;
		// 获取单词列表数据
    initWordInfo();
	})

	// 当前单词
	const activeWord = computed(() => {
		if (!data.activeId) {
			return null
		}
		return data.wordList.find(item => item.id == data.activeId)
	})

	// 是否是最后一题
	const isLast = computed(() => {
		if (!data.wordList.length) {
			return false
		}
		return data.activeId == data.wordList[data.count - 1].id;
	})
	const isFirst = computed(() => {
		if (!data.wordList.length) {
			return false
		}
		return data.activeId == data.wordList[0].id;
	})

	const activeWords = computed(() => {
		if (!data.activeId) {
			return null
		}
		return data.arrayList.find(item => item.some(cit => cit.id == data.activeId))
	})

	function nextWord() {
		const index = data.wordList.findIndex(item => item.id == data.activeId);
		if (index < data.count - 1) {
			data.activeId = data.wordList[index + 1].id;
		}
	}

	function prevWord() {
		const index = data.wordList.findIndex(item => item.id == data.activeId);
		if (index > 0) {
			data.activeId = data.wordList[index - 1].id;
		}
	}


	function initWordInfo() {
		httpApi.getWordInfo({
			jieId: data.jieId,
			wordId: data.activeId
		}).then(res => {
			data.wordInfo = res.data;
			data.levelId = res.data.levelId;
			data.subjectId = res.data.subjectId;
			data.wordList = res.data.danciList;
			if (data.wordList.length) {
				data.arrayList = chunkArray(data.wordList, 5); // 将1维单词数组转换为2维数组
			}
		})
	}
</script>

<style>

</style>