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, togglePlay } from "/src/state";
import { getSecondRPM } from "/src/utils";
import { headImg } from "/src/page-instrument/header-top/image";

export default defineComponent({
	name: "HomeWork",
	props: {
		workeData: {
			type: Object,
			default: () => ({}),
		}
	},
	emits: ["change"],
	setup(props, {expose}) {
		const training = reactive({
			trainingTimes: "", // 已经练习的时长，单位分钟
			trainingSpeed: 0, // 作业规定的速度
			times: 0, // 作业规定的练习时长，单位分钟
			trainingTimeSecond: 0, // 实时更新的练习时长，单位秒
			workRecord: "",
			isAddOk: 0,
			starTime: 0,
			start: "" as any,
			end: "" as any,
			timer: null as any, // 定时器
			showWorkDonePop: false, // 显示需要提交作业弹窗
		});

		/** 隐藏评测功能 */
		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.trainingTimeSecond = workeData.trainingTimes || 0;
				training.trainingSpeed = trainingContent.practiceSpeed;
				training.start = Number(trainingContent.practiceChapterBegin);
				training.end = Number(trainingContent.practiceChapterEnd);
				state.userChooseEndIndex = training.end
				state.isWorkDone = Number(training.trainingTimes) >= Number(training.times);
				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";
				training.trainingTimeSecond = res.data.trainingTimes || 0;
				state.isWorkDone = Number(training.trainingTimes) >= Number(training.times);
			}
		};

		/** 添加作业记录 */
		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) {}
		};

		const handleStart = () => {
			training.timer = setInterval(() => {
				training.trainingTimeSecond += 1;
				// 如果播放中，作业从未达标到达标状态，需要暂停播放，并且弹窗提示作业已达标
				if (!state.isWorkDone && training.trainingTimeSecond >= training.times * 60) {
					togglePlay("paused")
					state.isWorkDone = true
					training.showWorkDonePop = true
				}
				// console.log('练习时长',training.trainingTimeSecond)
			}, 1000);
		};
        const handleStop = () => {
            clearInterval(training.timer)
        }

		watch(
			() => state.playState,
			() => {
				if (state.playState === "play") {
					training.starTime = Date.now();
					handleStart();
				} else {
					addHomeworkRecored();
					handleStop();
				}
			}
		);
		const handleAdd = () => {
			if (state.playState === "play") {
				console.log("退出");
				addHomeworkRecored();
			}
		}
		onMounted(() => {
			handleHide();
			getWorkData();
			// verifyMembershipServices();
		});
		expose({
			handleAdd,
			getWorkData
		})
		return () => (
			<>
				<div class={styles.homework}>
					<i class={state.playState === "play" ? styles.blinkDot : styles.grayDot}></i>
					<span>{getSecondRPM(training.trainingTimeSecond)} / {getSecondRPM(training.times*60)}</span>
				</div>
				{
					training.showWorkDonePop && 
					<div class={styles.workDonePop}>
						<img class={styles.doneBg} src={headImg("workDonePop.png")} />
						<img class={styles.doneBtn} src={headImg("workDoneBtn.png")} onClick={() => {
							training.showWorkDonePop = false
                			addHomeworkRecored();
              			}} />
					</div>
				}
			</>
		);
	},
});
