import {
	onLoad,
	onReady,
} from "@dcloudio/uni-app"
import {
	reactive,
	ref,
	computed,
	toRefs,
	onMounted,
	watch,
	nextTick
} from "vue";
import {
	catchError,
	toast
} from "@/utils/common.js"
import * as httpUnit from "@/api/unitTest.js"
import cacheManager, {
	useUnitTestTishi
} from "@/utils/cacheManager.js"


function useJifen() {
	const data = reactive({
		rightAnswer: 0, // 答对
		wrongAnswer: 0, // 答错
		jifen: 0, // 积分
	})

	function updateJifen({
		rightAnswer,
		wrongAnswer,
		jifen
	}) {
		data.rightAnswer = rightAnswer;
		data.wrongAnswer = wrongAnswer;
		data.jifen = jifen;
	}

	return {
		...toRefs(data),
		updateJifen
	}
}

export function useExam() {
	// 缓存

	const {
		showTishi,
		handleCloseTishi,
		handleShowTishi
	} = useTishiLeftRight()
	const {
		rightAnswer,
		wrongAnswer,
		jifen,
		updateJifen
	} = useJifen();


	const data = reactive({
		count: 0, // 已答题数
		total: 0, // 总题数
		current: 0, // 当前试题序列
		list: [], // 试题列表
		jieId: null, // 节Id
		zhangId: null,
		nianji: null,
		xueke: null,
		haveFlag: false, // 是否有下一章
		activeZhang: null,
		studyFlag: 0, // 是否是第一次答题
	})
	onLoad((options) => {
		const jieId = options.jieId
		const cacheZhangInfo = cacheManager.get('zhangInfo');
		const {
			cardId,
			zhangId,
			nianji
		} = cacheManager.get('auth');

		data.jieId = jieId; // 需要路由参数 节Id
		data.zhangId = zhangId; // 需要路由参数 章Id
		data.nianji = nianji; // 需要年纪Id 来执行返回页面
		data.xueke = cardId; // 需要年纪Id 来执行返回页面
		data.activeZhang = getZhangInfoByJieId(cacheZhangInfo.zhangList,jieId);
		data.haveFlag = data.activeZhang.curZhang ? data.activeZhang.curZhang.haveFlag: 0;
		data.studyFlag = data.activeZhang.curZhang ? data.activeZhang.curZhang.jieList[data.activeZhang.curZhang.jieList.length-1].studyFlag: 0;
		// 初始化页面数据
		initPage();
	})

	watch(() => data.list, (val) => {
		const list = data.list.filter(item => {
			if (item.type == 3) {
				// 填空题 所有试题答完
				return !item.reply.some(citem => citem.trim() == '');
			} else {
				return item.reply !== null
			}
		});
		data.count = list.length;
	}, {
		deep: true
	})


	// 初始化页面数据
	async function initPage() {
		const [err, cdata] = await catchError(httpUnit.getExamData({
			jieId: data.jieId
		}));
		if (err) {
			toast("单元测试数据获取异常");
			return;
		}
		refreshExam(cdata);
	}

	function formatListToUse(list) {
		list.forEach((item, index) => {
			item.mta_show = false;
			item.reply = null;
			if (item.type == 3) {
				item.result = JSON.parse(item.result);
				item.placeholders = item.result.map((item, cindex) => `[bank${cindex+1}]`)
				item.reply = item.reply ? JSON.parse(item.reply): item.result.map(() => '');
			}
			
			if (item.type == 4) {
				// 特殊题型英语题
				const audioList = item.audios ? item.audios.split(',') : [];
				item.placeholders = audioList.map((item, cindex) => `[yingyu${cindex+1}]`)
				item.audioList = audioList;
			}
		})
	}
	
	

	// 数据赋值
	function refreshExam(list) {
		const cList = list;
		formatListToUse(cList)
		data.list = cList;
		data.total = cList.length;

		handleShowTishi();
	}

	// 交卷
	async function handleSubmit(dom) {
		uni.$emit('unitTest-submit')
		const result = [];
		data.list.forEach(item => {
			if (item.type == 1) {
				result.push({
					reply: item.reply,
					stId: item.stId
				})
			} else if (item.type == 2) {
				result.push({
					reply: item.reply ,
					stId: item.stId
				})
			} else if (item.type ==3){
				result.push({
					reply: item.reply ? JSON.stringify(item.reply) : '',
					stId: item.stId
				})
			} else if (item.type == 4) {
				result.push({
					reply: item.reply,
					stId: item.stId
				})
			}
		
		})
		uni.showLoading({
			title: '交卷中...'
		});
		const [error, cdata] = await catchError(httpUnit.getExamSubmit({
			jieId: data.jieId,
			shitiList: result
		}));
		uni.hideLoading()
		if (error) {
			toast("单元测试数据提交异常");
			return;
		}
		
		const cacheCurrentZhangIndex = cacheManager.get('auth').currentZhang;
		cacheManager.updateJieStatus('zhangInfo', cacheCurrentZhangIndex, data.jieId);
		
		dom.showPopup({
			right: cdata.dui,
			wrong: cdata.cuo,
			jifen: cdata.jifen
		});
	}



	return {
		...toRefs(data),
		rightAnswer,
		wrongAnswer,
		jifen,
		showTishi,

		handleSubmit,
		initPage,
		handleCloseTishi,
		handleShowTishi
	}
}

// 提示信息显示隐藏
function useTishiLeftRight() {
	let timer = null;
	const {
		updateTishi,
		getTishi
	} = useUnitTestTishi();
	const showTishi = ref(false);
	// 大鹅关闭追加缓存 --- 单独针对当前手机的缓存提示
	function handleCloseTishi() {
		updateTishi();
		showTishi.value = false;
		clearTimeout(timer);
		timer = null;
	}
	// 大鹅显示追加缓存 --- 单独针对当前手机的缓存提示
	function handleShowTishi() {
		const isNotShow = Boolean(getTishi());
		showTishi.value = !isNotShow;
		timer = setTimeout(() => {
			handleCloseTishi();
		},3000)
	}

	return {
		showTishi,
		handleCloseTishi,
		handleShowTishi
	}
}

function getZhangInfoByJieId(list, jieId) {
	const curZhang = list.find(item => item.jieList.some(cite => cite.jieId == jieId)) || null;
	let nextZhang = null;
	if (curZhang) {
		const nextIndex = list.findIndex(item => curZhang.zhangId == item.zhangId);
		if (nextIndex+1<list.length) {
			nextZhang = list[nextIndex+1];
		}
	}
	return {
		curZhang,
		nextZhang
	};

}