import { defineComponent, onMounted, reactive, ref } from "vue";
import { getQuery } from "/src/utils/queryString";
import request from "/src/utils/request";
import { storeData } from "/src/store";
import state, { handleSetSpeed, hanldeDirectSelection } from "/src/state";
import { handleCloseModeMode } from "../../header-top";
import { handleStartEvaluat } from "/src/view/evaluating";

interface IquestionExtendsInfo {
	/** 评测难度 */
	difficulty?: "ONE" | "TWO" | "THREE" | "1" | "2" | "3" | "";
	/** 开始小节 */
	start?: string | number;
	/** 结束小节 */
	end?: string | number;
	/** 速度 */
	speed?: number;
}
const difficultyData: { [_: string]: any } = {
	ONE: "BEGINNER",
	TWO: "ADVANCED",
	THREE: "PERFORMER",
	"1": "BEGINNER",
	"2": "ADVANCED",
	"3": "PERFORMER",
};

export const unitTestData = reactive({
	/** 是否是选段模式 */
	isSelectMeasureMode: false,
});

export default defineComponent({
	name: "unitTest",
	setup() {
		const questionExtendsInfo = ref<IquestionExtendsInfo>({ difficulty: "" });
		/** 隐藏评测功能 */
		const handleHide = (list: string[]) => {
			const ids = list;
			for (let i = 0; i < ids.length; i++) {
				const speedBtn = document.getElementById(ids[i]);
				if (speedBtn) {
					speedBtn.style.pointerEvents = "none";
					if (ids[i] != "selectionBox") {
						speedBtn.style.opacity = ".7";
					}
				}
			}
		};
		/**
		 * 如果是课后训练或者单元测验,获取数据
		 * @param xml 获取的xml数据
		 * @returns 格式化的xml数据
		 */
		const getUnitData = async () => {
			const search = getQuery();
			if (!search.questionId) return "";
			handleHide(["tips-step-0", "tips-step-2", "selectionBox"]);
			handleStartEvaluat();
			handleCloseModeMode();
			try {
				const res: any = await request.get(`/examinationQuestion/detail?examinationQuestionId=${search.questionId}`);
				questionExtendsInfo.value = JSON.parse(res?.data?.questionExtendsInfo) || {};
				questionExtendsInfo.value.start = Number(questionExtendsInfo.value.start);
				questionExtendsInfo.value.end = Number(questionExtendsInfo.value.end);
			} catch (error) {
				console.error("解析单元测验曲谱题目失败", error);
			}
			setSection();
		};

		const getlessonTrainingData = async () => {
			const search = getQuery();
			if (!search.lessonTrainingId) return;
			handleHide(["tips-step-3", "selectionBox"]);
			try {
				const res: any = await request.post(`/studentLessonTraining/trainingRecord/${search.courseScheduleId}?userId=${storeData.user?.id}`);
				if (Array.isArray(res?.data?.trainings)) {
					const train = res.data.trainings.find((n: any) => n.materialId == search.materialId);
					const info = JSON.parse(train.trainingContent);
					// console.log("🚀 ~ info", info)
					questionExtendsInfo.value.start = Number(info.startSection);
					questionExtendsInfo.value.end = Number(info.endSection);
					questionExtendsInfo.value.speed = isNaN(info.speed) ? 0 : Number(info.speed);
				}
			} catch (error) {
				console.error("解析课后训练曲谱题目失败", error);
			}
			setSection();
		};

		/**设置小节 */
		const setSection = () => {
			const startNotes = state.times.filter((n: any) => n.MeasureNumberXML == questionExtendsInfo.value.start);
			const endNotes = state.times.filter((n: any) => n.MeasureNumberXML == questionExtendsInfo.value.end);
			const startNote = startNotes[0];
			const endNote = endNotes[endNotes.length - 1];
			// console.log('🚀 ~ activeNote', startNote, endNote, questionExtendsInfo.value.end)
			if (startNote && endNote) {
				state.isSelectMeasureMode = true;
				// 设置小节
				hanldeDirectSelection([startNote, endNote]);
				// 设置评测难度
				if (difficultyData[questionExtendsInfo.value.difficulty!]) {
					state.setting.evaluationDifficulty = difficultyData[questionExtendsInfo.value.difficulty!];
				}
				//设置速度
				if (questionExtendsInfo.value.speed) {
					handleSetSpeed(questionExtendsInfo.value.speed);
				}
			}
		};
		onMounted(() => {
			getUnitData();
			getlessonTrainingData();
		});
		return () => "";
	},
});
