<template>
	<view class="word-view-page" :style="{backgroundImage: 'url(' + courseBjFun() + ')'}">
		<view class="icon-title-navBar-box">
			<view @click="handleBack" class="nav-bar-icon"></view>
			<text class="nav-bar-title">学习</text>
		</view>
		<view class="ezy-tab-border">
			<view class="ezy-border-body">
				<template v-for="item in data.wordList">
					<mainCardVue :active-word="data.activeWord" :pageData="data" :active-words="activeWords"
						@play-audio="handlePlayAudio" v-if="item.id == data.activeId" :key="item.id">
					</mainCardVue>
				</template>
			</view>
		</view>
		<view class="word-view-bottom">
			<view class="collect-btn" v-if="userCode != 'Visitor'" @click="handleShouCang">
				<icon :class="{active: data.collectFlag}"></icon>
				<view>收藏</view>
			</view>
			<view class="bottom-btn-box">
				<view class="word-view-btn" @click="prevWord" v-if="!isFirst&&isLearnRecord!=0">上一词</view>
				<view class="word-view-btn" @click="nextWord" v-if="!isLast&&isLearnRecord!=0">下一词</view>
				<view class="word-view-btn" v-if="isLast&&isLearnRecord!=0" @click="handleComplete">完成</view>
			</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"
	import {
		getUserIdentity,
	} from "@/utils/common.js"
	import {
		useAudioCache,
		audioPlayer
	} from "./components/useAudio.js"

	const userCode = getUserIdentity();

	const {
		cacheAudio,
		clearAudioCache
	} = useAudioCache();

	const AudioP = new audioPlayer();
	const isLearnRecord = ref(null)
	const isLearnStatus = ref(null)

	function courseBjFun() {
		return 'static/images/course/course-cjdc-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;
	}

	const data = reactive({
		jieId: null, // 节/单元ID
		activeId: null, // 当前单词
		wordList: [], // 单词列表
		arrayList: [], // 整合数据
		activeWord: null, // 单词详情数据
		collectFlag: 0, // 收藏状态
		subjectId: null, // 学科ID
		levelId: null, // 等级
		typeId: null, // 类型
		tipFlag: null, // 提示
		zhangId: null, // 章ID
		isLearnStatus: null, // 学习记录状态
	})

	onLoad(({
		jieId,
		wordId,
		subjectId,
		levelId,
		typeId,
		tipFlag,
		isLearnStatus,
		zhangId
	}) => {
		data.jieId = jieId;
		isLearnRecord.value = jieId;
		data.activeId = wordId;
		data.isLearnStatus = isLearnStatus;
		data.subjectId = subjectId;
		data.levelId = levelId;
		data.typeId = typeId;
		data.tipFlag = tipFlag;
		data.zhangId = zhangId;
		// 获取单词列表数据
		initWordInfo();
		// 清理过期文件
		clearAudioCache();
	})

	// 是否是最后一题
	const isLast = computed(() => {
		if (!data.wordList.length) {
			return false
		}
		return data.activeId == data.wordList[data.wordList.length - 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.wordList.length - 1) {
			uni.redirectTo({
				url: `/pages/newEnglish/index?jieId=${data.jieId}&wordId=${data.wordList[index + 1].id }`
			})
		}
	}

	function prevWord() {
		const index = data.wordList.findIndex(item => item.id == data.activeId);
		if (index > 0) {
			uni.redirectTo({
				url: `/pages/newEnglish/index?jieId=${data.jieId}&wordId=${data.wordList[index - 1].id }`
			})
		}
	}

	function handleBack() {
		// 返回单词列表
		if (userCode !== 'Visitor') {
			if (data.jieId == 0) {
				uni.redirectTo({
					url: `/pages/my/learnRecord?jieId=${data.jieId}&isLearnStatus=${data.isLearnStatus}`
				})
			} else {
				uni.redirectTo({
					url: `/pages/wordList/wordList?jieId=${data.jieId}`
				})
			}
		} else {
			const youkePageData = JSON.stringify({
				subjectId: data.subjectId,
				levelId: data.levelId,
				typeId: data.typeId,
				tipFlag: data.tipFlag,
				youkeZhangId: data.zhangId,
				jieId: data.jieId
			})
			uni.redirectTo({
				url: `/pages/wordList/wordList?youkePageData=${youkePageData}`
			})
		}
	}

	function handleComplete() {
		// 返回岛
		if (userCode !== 'Visitor') {
			uni.redirectTo({
				url: `/pages/study/index`
			})
		} else {
			uni.redirectTo({
				url: `/pages/study/index?levelId=${data.levelId}&typeId=${data.typeId}&subjectId=${data.subjectId}&tipFlag=${data.tipFlag}&youkeZhangId=${data.zhangId}&jieId=${data.jieId}`
			})
		}
	}

	function handleShouCang() {
		httpApi.getWordShouCang({
			wordId: data.activeId
		}).then(res => {
			if (res.data) {
				uni.showToast({
					title: '收藏成功'
				})
				data.collectFlag = 1;
			} else {
				uni.showToast({
					title: '收藏取消'
				})
				data.collectFlag = 0;
			}
		})
	}

	function initWordInfo() {

		if (userCode !== 'Visitor') {
			httpApi.getWordInfo({
				jieId: data.jieId,
				wordId: data.activeId
			}).then(res => {
				data.activeWord = res.data;
				data.wordList = res.data.danciList; // 单词组
				data.collectFlag = res.data.collectFlag; // 收藏状态
				if (data.wordList.length) {
					data.arrayList = chunkArray(data.wordList, 5); // 将1维单词数组转换为2维数组
				}
				// console.log('res.data',res.data)
				handleCacheAudio()

			})
		} else {
			httpApi.getCommonWordInfo({
				jieId: data.jieId,
				wordId: data.activeId
			}).then(res => {
				data.activeWord = res.data;
				data.wordList = res.data.danciList; // 单词组
				data.collectFlag = res.data.collectFlag; // 收藏状态
				if (data.wordList.length) {
					data.arrayList = chunkArray(data.wordList, 5); // 将1维单词数组转换为2维数组
				}

				handleCacheAudio()
			})
		}
	}

	function handleCacheAudio() {

		const arr = []
		// yinpin
		arr.push(data.activeWord.yinpin);
		// yinjie
		data.activeWord.yinjie.forEach(item => {
			arr.push(item.yinpin)
		})
		// pindu
		data.activeWord.pindu.forEach(item => {
			arr.push(item.yinpin)
		})
		// 缓存音频
		arr.map(item => cacheAudio(item));
		// console.log('arr',arr)
	}

	async function handlePlayAudio({
		url,
		code
	}) {
	 console.log('播放', url)
	 console.log('播放', code)
		const cachedPath = await cacheAudio(url);
		if (cachedPath.includes('.mp3')) {
			// console.log('地址：', cachedPath)
			AudioP.play(cachedPath, code);
		} else {
			uni.showToast({
				title: '音频加载失败',
				icon: 'none'
			});
		}
	}
</script>

<style>

</style>