import { defineComponent, onMounted, reactive, ref, watch } from "vue";
import WorkHome from "../work-home";
import WorkEaluating from "../work-ealuating";
import { getQuery } from "/src/utils/queryString";
import { api_lessonTrainingTrainingStudentDetail } from "../../api";
import { headTopData } from "../../header-top";
import { evaluatingData } from "/src/view/evaluating";
import state from "/src/state";

const workHomeRef = ref();
const workEvaluatRef = ref();

export const data = reactive({
	/** 作业类型：练习PRACTICE, 评测EVALUATION */
	trainingType: "" as "PRACTICE" | "EVALUATION",
	worke: {} as any,
});

export const HANDLE_WORK_ADD = () => {
	if (data.trainingType === "PRACTICE"){
		workHomeRef.value?.handleAdd();
	}
};

// 刷新谱面后，设置作业选段
export const resetSection = () => {
	console.log('重新设置选段1111')
	if (data.trainingType === "PRACTICE"){
		workHomeRef.value?.getWorkData();
	}
	if (data.trainingType === "EVALUATION") {
		workEvaluatRef.value?.getWorkData();
	}
	state.workSectionNeedReset = false;
};

export default defineComponent({
	name: "workIndex",
	setup(props) {
		const query = getQuery();

		const setModelType = () => {
			if (!data.trainingType) return;
			const type = data.trainingType === "PRACTICE" ? "practise" : "evaluating";
			headTopData.handleChangeModeType(type);
		};
		const getWorkDetail = async () => {
			const workId = query.workRecord ? query.workRecord : query.evaluatingRecord;
			const res = await api_lessonTrainingTrainingStudentDetail(workId, query.workRecord ? 'homeWork' : '');
			if (res?.code === 200) {
				data.trainingType = query.workRecord ? 'PRACTICE' : 'EVALUATION';
				data.worke = res.data;
				setModelType();
			}
		};
		// 评测作业监听评测资源加载完成
		watch(
			() => evaluatingData.jsonLoadDone,
			() => {
				if (data.trainingType === "EVALUATION" && evaluatingData.jsonLoading && evaluatingData.jsonLoadDone) {
					headTopData.handleChangeModeType('evaluating');
				}
			}
		);		
		onMounted(() => {
			getWorkDetail();
		});
		return () => (
			<>
				{/* 课后训练作业 */}
				{data.trainingType === "PRACTICE" && <WorkHome ref={workHomeRef} workeData={data.worke} />}
				{/* 评测作业 */}
				{data.trainingType === "EVALUATION" && (
					<WorkEaluating ref={workEvaluatRef} workeData={data.worke} />
				)}
			</>
		);
	},
});
