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: {},
});

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 const selfSubmitWorkHome = () => {
	workEvaluatRef.value?.addEvaluatingWorkRecored(evaluatingData.resultData);
}

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 res = await api_lessonTrainingTrainingStudentDetail(query.workRecord);
			if (res?.code === 200) {
				data.trainingType = res.data.trainingType;
				data.worke = res.data;
				// 评测作业是否已经合格
				if (data.trainingType === 'EVALUATION' && JSON.parse(res.data?.trainingContent)) {
					state.isWorkDone = res.data.trainingTimes >= JSON.parse(res.data.trainingContent).trainingTimes
				}
				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} />
				)}
			</>
		);
	},
});
