import {
	useUserCache
} from "@/utils/userCache.js"
import * as kcApi from "@/api/kecheng.js"

export function useKechengTools() {
	const {
		saveCache,
		getCache,
		removeCache
	} = useUserCache();

	function getCurKjIndex(kjId, operId) {
		const arrKecheng = getKechengDataFromHistory(operId);
		for (let zi = 0; zi < arrKecheng.length; zi++) {
			for (let ji = 0; ji < arrKecheng[zi].jieList.length; ji++) {
				if (arrKecheng[zi].jieList[ji].kejianList.some(kj => kj.kjId == kjId)) {
					return {
						zhangIndex: zi,
						jieIndex: ji
					}
				}
			}
		}
	}

	function mergeProgress(backData, historyData) {
		const curData = JSON.parse(JSON.stringify(historyData));
		backData.forEach((item, zhangIndex) => {
			item.jieList.forEach((jieItem, jieIndex) => {
				jieItem.kejianList.forEach((kjItem, kjIndex) => {
					const backCurJie = backData[zhangIndex].jieList[jieIndex].kejianList[
						kjIndex];

					// 大于等于100 的进度以后台为准
					if (kjItem.maxProcess >= 100) {
						curData[zhangIndex].jieList[jieIndex].kejianList[kjIndex] = backCurJie;
					} else if (curData[zhangIndex].jieList[jieIndex].kejianList[kjIndex]
						.maxProcess == 100) {
						// 前台缓存进度为100 使用后台进度
						//   alert('前台缓存进度为100 使用后台进度')
						curData[zhangIndex].jieList[jieIndex].kejianList[kjIndex] = backCurJie;
					}
					curData[zhangIndex].jieList[jieIndex].kejianList[kjIndex].lockFlag =
						backCurJie.lockFlag;
				})
			})
		})
		return curData;
	}

	function saveKechengData(operId, data) {
		saveCache('SectionInfo' + operId, 'arrKecheng', data)
	}

	function getKechengDataFromHistory(operId) {
		return getCache('SectionInfo' + operId, 'arrKecheng')
	}

	function saveKechengSectionPage(operId, data) {
		saveCache('SectionInfo' + operId, 'sectionPage', data)
	}

	function getKechengSectionPageFromHistory(operId) {
		return getCache('SectionInfo' + operId, 'sectionPage')
	}

	function initCourseProgressAll(operId) {
		let arrKecheng = getCache('SectionInfo' + operId, 'arrKecheng');
		// 判断是否有课程信息
		if (!arrKecheng || arrKecheng.length === 0) {
			throw new Error('initCourseProgress业务逻辑错误: arrKecheng 异常');
		}

		for (const chapter of arrKecheng) {
			for (const section of chapter.jieList) {
				let kejianArr = section.kejianList;
				if (kejianArr && kejianArr.length > 0) {
					for (const kejian of kejianArr) {
						if (!kejian.maxProcess) {
							kejian.curProcess = 0;
							kejian.maxProcess = 0;
							kejian.hasFinished = false;
						} else if (kejian.maxProcess < 100) {
							kejian.hasFinished = false;
						}
					}
				}
			}
		}
		saveCache('SectionInfo' + operId, 'arrKecheng', arrKecheng);
		return arrKecheng;
	}

	function saveCourseProgress(cur, total, operId, code, type) {
		let sectionPage = getCache('SectionInfo' + operId, 'sectionPage');
		let arrKecheng = getCache('SectionInfo' + operId, 'arrKecheng');
		
		let section = arrKecheng[sectionPage.iChapter].jieList[sectionPage.iSection];

		for (const kejian of section.kejianList) {
			if (kejian.kjId === sectionPage.kjId) {
				// video或audio的end为100，其他情况最大99
				if (code === 'end') {
					kejian['curProcess'] = 100;
					kejian['maxProcess'] = 100;
				} else if (type === 'other') {
					// 除了音视频以外的课件
					kejian['curProcess'] = 100;
					kejian['maxProcess'] = 100;
				} else {
					// 0 ~ 99
					kejian['curProcess'] = parseInt(cur / total * 100) >= 100 ?
						99 :
						parseInt(cur / total * 100);

					kejian['maxProcess'] = kejian['curProcess'] > kejian['maxProcess'] ?
						kejian['curProcess'] :
						kejian['maxProcess'];
				}
				break;
			}
		}

		saveCache('SectionInfo' + operId, 'arrKecheng', arrKecheng);
	}

	function getCourseProgress(total) {
		let sectionPage = getCache('SectionInfo', 'sectionPage');
		let arrKecheng = getCache('SectionInfo', 'arrKecheng');
		let section = getSection(arrKecheng, sectionPage.iChapter, sectionPage.iSection);

		for (const kejian of section.kejianList) {
			if (kejian.kjId === sectionPage.kjId) {
				return {
					cur: total * parseFloat(kejian['curProcess']) / 100,
					max: total * parseFloat(kejian['maxProcess']) / 100,
				};
			}
		}
	}

	function updateSectionProgress(operId, code, type, callback) {

		let sectionPage = getCache('SectionInfo' + operId, 'sectionPage');
		let arrKecheng = getCache('SectionInfo' + operId, 'arrKecheng');

		if (sectionPage && sectionPage.finish) {
			console.log('已经结束，不再保存进度')
			return;
		}

		let kejianList = arrKecheng[sectionPage.iChapter].jieList[sectionPage.iSection].kejianList;
		let kejianIndex = kejianList.findIndex(item => item.kjId === sectionPage.kjId);

		const optX = {
			zhangIndex: sectionPage.iChapter,
			jieIndex: sectionPage.iSection,
			kejianIndex: kejianIndex,
			kjId: sectionPage.kjId,
			operId: sectionPage.operId,
			process: kejianList[kejianIndex].maxProcess,
			customLoadingSwitch: false,
		};

		saveCache('SectionInfo' + operId, 'arrKecheng', arrKecheng);
		const saveOpt = {
			kejianList: kejianList,
			kejianIndex: kejianIndex,
			arrKecheng: arrKecheng,
			optX: optX,
		};
		// 音视频end
		if (code === 'end') {
			kcApi.getClientKechengSave(optX).then(res => {
				// 接口正常执行
				if (res.code === 0) {
					// 音视频end事件
					kejianList[kejianIndex].curProcess = 100;
					kejianList[kejianIndex].maxProcess = 100;
					arrKecheng[optX.zhangIndex].jieList[optX.jieIndex].kejianList[optX.kejianIndex]
						.hasFinished = true;
					saveCache('SectionInfo' + operId, 'arrKecheng', arrKecheng);
					if (res.data.finish === true) {
						// 整个课程学完 data为true
						uni.showToast({
							title: "课程已学完！"
						})
						sectionPage.finish = true;
						saveCache('SectionInfo' + operId, 'sectionPage', sectionPage);
					}
				} else {
					saveInterfaceAbnormal(saveOpt, 99);
					callback(99)
				}
			}).catch(err => {
				saveInterfaceAbnormal(saveOpt, 99);
				callback(99)
			});
		} else {
			// 其他情况（音视频一秒一保存）
			kcApi.getClientKechengSave(optX).then(res => {
				if (res.code === 0) {
					if (res.data.finish === true) {
						uni.showToast({
							title: "课程已学完！"
						})
						sectionPage.finish = true;
						saveCache('SectionInfo' + operId, 'sectionPage', sectionPage);
					}
				}
			});
		}
	}

	function saveInterfaceAbnormal(saveOpt, jindu) {
		const {
			kejianList,
			kejianIndex,
			arrKecheng,
			optX,
			operId
		} = saveOpt;
		kejianList[kejianIndex].curProcess = jindu;
		kejianList[kejianIndex].maxProcess = jindu;
		arrKecheng[optX.zhangIndex].jieList[optX.jieIndex].kejianList[optX.kejianIndex].hasFinished = false;
		saveCache('SectionInfo' + operId, 'arrKecheng', arrKecheng);
		uni.redirectTo({
			url:"/pages/client/Kecheng/list"
		})
	}

	return {
		getCurKjIndex,
		saveKechengData,
		getKechengDataFromHistory,
		saveKechengSectionPage,
		getKechengSectionPageFromHistory,
		mergeProgress,
		initCourseProgressAll,
		saveCourseProgress,
		getCourseProgress,
		updateSectionProgress,
		saveInterfaceAbnormal
	}
}