import { defineComponent, onMounted, reactive, watch } from "vue";
import styles from "./index.module.less";
// import { verifyMembershipServices } from "../vip-verify";
import { api_lessonTrainingSubmitTraining, api_lessonTrainingTrainingStudentDetail } from "../../api";
import state, { handleSetSpeed, hanldeDirectSelection, setSection } from "/src/state";

export default defineComponent({
	name: "HomeWork",
	props: {
		workeData: {
			type: Object,
			default: () => ({}),
		}
	},
	emits: ["change"],
	setup(props, {expose}) {
		const training = reactive({
			trainingTimes: "",
			trainingSpeed: 0,
			times: 0,
			workRecord: "",
			isAddOk: 0,
			starTime: 0,
			start: "" as any,
			end: "" as any,
		});

		/** 隐藏评测功能 */
		const handleHide = () => {
			const ids = ["studnetT-0", "studnetT-2", "studnetT-4"];
			for (let i = 0; i < ids.length; i++) {
				const speedBtn = document.getElementById(ids[i]);
				if (speedBtn) {
					speedBtn.style.pointerEvents = "none";
					speedBtn.style.opacity = ".5";
				}
			}
		};
		/** 获取作业详情 */
		const getWorkData = async () => {
			const workeData = props.workeData;
			if (workeData.id) {
				let trainingContent: any = {};
				try {
					trainingContent = JSON.parse(workeData.trainingContent);
				} catch (error) {
					console.log("🚀 ~ error:", error);
				}
				training.times = trainingContent.trainingTimes || 0;
				training.trainingTimes = (workeData.trainingTimes / 60).toFixed(1) || "0";
				training.trainingSpeed = trainingContent.practiceSpeed;
				training.start = Number(trainingContent.practiceChapterBegin);
				training.end = Number(trainingContent.practiceChapterEnd);
				state.userChooseEndIndex = training.end
				if (training.isAddOk === 0) {
					// 设置小节
					setSection(training.start, training.end, training.trainingSpeed);
				}
			}
		};

		const getWorkDetail = async () => {
			const res = await api_lessonTrainingTrainingStudentDetail(props.workeData.id);
			if (res?.code === 200) {
				training.trainingTimes = (res.data.trainingTimes / 60).toFixed(1) || "0";
			}
		};

		/** 添加作业记录 */
		const addHomeworkRecored = async () => {
			let total = Math.ceil((Date.now() - training.starTime) / 1000);
			try {
				const res = await api_lessonTrainingSubmitTraining({
					id: props.workeData.id,
					trainingTimes: total,
				});
				if (res?.code == 200) {
					getWorkDetail();
				}
			} catch (error) {}
		};

		watch(
			() => state.playState,
			() => {
				if (state.playState === "play") {
					training.starTime = Date.now();
				} else {
					addHomeworkRecored();
				}
			}
		);
		const handleAdd = () => {
			if (state.playState === "play") {
				console.log("退出");
				addHomeworkRecored();
			}
		}
		onMounted(() => {
			handleHide();
			getWorkData();
			// verifyMembershipServices();
		});
		expose({
			handleAdd,
			getWorkData
		})
		return () => (
			<div class={styles.homework}>
				{training.trainingTimes} / {training.times} 分钟
			</div>
		);
	},
});
