import { Button, Popup } from "vant";
import styles from "./index.module.less";
import { defineComponent, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import { api_toggleTune, getEarphone, removeResult, sendResult, addCheckPlayEnd, removeCheckPlayEnd } from "/src/helpers/communication";
import { Vue3Lottie } from "vue3-lottie";
// import bg from "./json/bg.json";
// import bg1 from "./json/bg1.json";
import l1 from "./json/l1.json";
import f1 from "./json/f1.json";
import f2 from "./json/f2.json";
import f3 from "./json/f3.json";
import f4 from "./json/f4.json";
import f5 from "./json/f5.json";
import f6 from "./json/f6.json";
import f7 from "./json/f7.json";
import bg_pp from "./json/bg_pp.json";
import r1 from "./image/r1.png";
import icon_1 from "./image/icon_1.png";
import icon_1_1 from "./image/icon_1_1.png";
import icon_2_1 from "./image/icon_2_1.png";
import icon_2_2 from "./image/icon_2_2.png";
import icon_2_3 from "./image/icon_2_3.png";
import icon_2_4 from "./image/icon_2_4.png";
import icon_4_0 from "./image/icon_4_0.png";
import icon_4_1 from "./image/icon_4_1.png";
import icon_4_2 from "./image/icon_4_2.png";
import icon_3_0 from "./image/icon_3_0.png";
import icon_3_1 from "./image/icon_3_1.png";
import icon_3_2 from "./image/icon_3_2.png";
import iconBack from "./image/icon-back.png";
import { evaluatingData, startCheckDelay } from "/src/view/evaluating";
import { IPostMessage } from "/src/utils/native-message";
import state from "/src/state";


export default defineComponent({
	name: "delay-check",
	emits: ["close", "back"],
	props: {
		/** 是否是预加载 */
		isPreLoad: {
			type: Boolean,
			default: false,
		},
	},	
	setup(props, { emit }) {
		const modules = import.meta.glob('./json/**', {
			import: 'default',
			eager: true
		});
		const getJson = (name: string): string => {
			const src: any = modules[`./${name}`] || '';
			return src;
		};		
		// startTune定时器
		let startTuneTimer: any = null
		let checkErjiTimer: any = null
		const anim = ref();
		const data = reactive({
			show: false,
			/** 检测状态 */
			checkStatus: "init" as "init" | "ing" | "finish" | "end",
			count: 0,
			step: 1,
			startTimer: null as any,
			stopTimer: null as any,
			volumeTimer: null as any,
			earPhoneType: "" as "" | "有线耳机" | "蓝牙耳机",
			startAbnormalTimer: null as any, // 发送startTune后，超过10秒没有收到sendResult回调，处理这类异常的定时器
			startTuneResult: false, // 发送startTune后，能否收到正常的result回调
			abnormalPopShow: false, // 异常弹窗
			bg: null as any,
			jsonDone: false,
		});

		const initJson = async () => {
			// console.log('开始加载')
			// const bg = await import(`./json/bg.json`);
			// const bg1 = await import(`./json/bg1.json`);
			/* @vite-ignore */
			data.bg = await import(`./json/bg_new.json`);
			// data.bg = getJson('bg_new.json');
			data.jsonDone = true;
			evaluatingData.jsonLoadDone = true;
			// console.log('延迟检测资源加载完成')
		}

		// 调用'isWiredHeadsetOn'最小时间间隔，1秒
		let minInterval = 0;
		/** 获取耳机状态 */
		const getEarphoneState = async () => {
			const res = await getEarphone();
			data.earPhoneType = res?.content?.type || "";
			return res?.content?.checkIsWired || false;
		};
		/** 持续检测耳机状态 */
		const keepCheckEarphone = async () => {
			if (data.step >= 7 || !data.show) return;
			let momentTime = +new Date()
			// console.log('间隔123',momentTime - minInterval)
			if (momentTime - minInterval < 1000) {
			  return
			}
			minInterval = momentTime
			evaluatingData.earphone = await getEarphoneState();
			// console.log('erji',evaluatingData.earphone,data.step)
			if (evaluatingData.earphone) {
				clearTimeout(data.startTimer);
				clearTimeout(data.stopTimer);
				clearTimeout(startTuneTimer);
				if (data.step <= 5) {
					data.checkStatus = "init"
					data.step = 3
				}
			} else {
				if (data.step === 3) {
					data.step = 2
					data.checkStatus = "init"
				}
			}
			checkErjiTimer = setTimeout(() => {
				keepCheckEarphone();
			}, 1000);
		};
		const listenerResult = (res?: IPostMessage) => {
			console.log("🚀 ~ res:", res);
			if (res?.content) {
				const { header, body } = res.content;
				if (header?.commond === "recordEnd") {
					if (data.checkStatus !== "ing") return;
					data.count++;
					if (data.count >= 2) {
						toggleTune("finishTune");
						return;
					}
					data.startTimer = setTimeout(() => {
						toggleTune("start");
					}, 100);
				}
			}
		};

		// 监听到校音音频播放完成
		const checkAudioPlayEnd = (res?: IPostMessage) => {
			console.log("🚀 ~ res:校音音频", res);
			// startTune效音通过返回后，调用endTune
			if (res) {
				clearTimeout(data.startAbnormalTimer);
				data.startTuneResult = true
				toggleTune("stop");
			}
		}

		onMounted(async () => {
			if (props.isPreLoad) {
				await initJson();
			} else {
				clearTimeout(checkErjiTimer)
				data.show = true;
				sendResult(listenerResult);
				addCheckPlayEnd(checkAudioPlayEnd);
				keepCheckEarphone();
			}
		});
		onUnmounted(() => {
			clearTimeout(checkErjiTimer)
			data.show = false;
			removeResult(listenerResult);
			removeCheckPlayEnd(checkAudioPlayEnd);
		});

		const handleStartTune = async () => {
			// 检测APP端socket状态
			const res: any = await startCheckDelay();
			if (res?.checked) {
				// data.step = evaluatingData.earphone ? 4 : 3;
				if (evaluatingData.earphone) {
					if (data.step <= 5) {
						if (data.checkStatus === "ing") {
							data.count = 0;
							clearTimeout(data.startTimer);
							clearTimeout(data.stopTimer);
							// toggleTune("stop");
						}
						data.step = 3;
					}
				} else {
					if (data.step === 2 || data.step === 3) {
						data.step = 4;
						startTuneTimer = setTimeout(() => {
							data.step = 5;
							data.checkStatus = "ing";
							data.count = 0;
							toggleTune("start");
						}, 2000);
					}
				}
			}
			
		};
		const hanldeEndTune = () => {
			console.log('设置soundEffect')
			data.step = 7;
			anim.value?.play();
			// state.setting.soundEffect = false;
		};

		const toggleTune = async (state: "start" | "stop" | "finishTune") => {
			if (state === "start") {
				const res = await api_toggleTune("start", data.count);
				// 用户没有授权，需要重置状态
				if (res?.content?.reson) {
					data.step = 2
					data.checkStatus = 'init'
					data.count = 0
				} else {
					// data.stopTimer = setTimeout(() => {
					// 	api_toggleTune("stop");
					// }, 2000);
					data.startTuneResult = false
					data.startAbnormalTimer = setTimeout(() => {
						/** startTune发出后，超过10秒没有收到回调，异常处理 */
						if (!data.startTuneResult) {
							api_toggleTune("stop");
							// 给出异常提示，再来一次
							data.abnormalPopShow = true
						}
					}, 10000);
				}
			} else if (state === "finishTune") {
				data.checkStatus = "finish";
				data.step = 6;
				api_toggleTune("finishTune");
			} else if (state === "stop") {
				api_toggleTune("stop");
			}
		};

		const resetCheck = () => {
			if (data.step > 5 && evaluatingData.accompanyErrorType === 'playError') {
				return
			}
			api_toggleTune("stop");
			clearTimeout(startTuneTimer)
			clearTimeout(data.startAbnormalTimer);
			data.abnormalPopShow = false
			data.step = 2
			data.checkStatus = 'init'
			data.count = 0
			data.startTuneResult = false
		}
		watch(
			() => evaluatingData.delayCheckSocketError,
			() => {
				// 监听到网络异常，重置延迟检测状态
				if (evaluatingData.delayCheckSocketError) {
					resetCheck()
				}
			}
		);
		return () => (
			<Popup
				teleport="body"
				overlay={false}
				class={["popup-custom", styles.popup]}
				transition="van-fade"
				v-model:show={data.show}
			>
				<div class={styles.delayBox}>
					{/*返回按钮*/}
					{/* <div class={styles.delayTest}>步骤：{data.step}{evaluatingData.accompanyErrorType}</div> */}
					{
						data.step > 1 && 
						<img class={styles.delayBackBtn} src={iconBack} onClick={() => {
							clearTimeout(startTuneTimer)
							api_toggleTune("stop");
							emit("back")
						}} />						
					}
					{/* 异常提示弹窗 */}
					{
						data.abnormalPopShow && 
						<div class={styles.tipBox}>
							<div class={styles.tipContent}>检测失败，请确保设备麦克风、扬声器正常，重新开始检测</div>
							<div class={styles.tipBtn} onClick={resetCheck}>再来一次</div>
						</div>
					}
					<div class={[styles.item, data.step !== 7 && styles.show]}>
						{data.bg && <Vue3Lottie animationData={data.bg}></Vue3Lottie>}
					</div>
					<div class={[styles.item, data.step === 7 && styles.show]}>
						{data.bg && <Vue3Lottie animationData={data.bg}></Vue3Lottie>}
					</div>
					<div class={[styles.bgpp]}>
						<Vue3Lottie animationData={bg_pp}></Vue3Lottie>
					</div>
					<div class={[styles.l1]}>
						<Vue3Lottie animationData={l1}></Vue3Lottie>
					</div>
					<img class={styles.r1} src={r1} />

					<div
						style={{ left: "10px", top: "-11px", transform: "rotate(-2deg)" }}
						class={[styles.item, data.step == 1 && styles.show]}
					>
						<Vue3Lottie
							animationData={f1}
							loop={false}
							onOnComplete={() => {
								data.step = 2;
							}}
						></Vue3Lottie>
					</div>

					<div
						style={{ left: "10px", top: "-11px", transform: "rotate(-2deg)" }}
						class={[styles.item, data.step === 2 && styles.show]}
					>
						<Vue3Lottie animationData={f2}></Vue3Lottie>
					</div>

					<div class={[styles.item, data.step === 3 && styles.show]}>
						<Vue3Lottie animationData={f3}></Vue3Lottie>
					</div>

					<div class={[styles.item, data.step === 4 && styles.show]}>
						<Vue3Lottie animationData={f4}></Vue3Lottie>
					</div>
					<div class={[styles.item, data.step === 5 && styles.show]}>
						<Vue3Lottie animationData={f5}></Vue3Lottie>
					</div>
					<div class={[styles.item, data.step === 6 && styles.show]}>
						<Vue3Lottie animationData={f6}></Vue3Lottie>
					</div>
					<div class={[styles.item, data.step === 7 && styles.show]}>
						<Vue3Lottie
							ref={anim}
							animationData={f7}
							autoPlay={false}
							loop={false}
							onOnComplete={() => {
								emit("close");
							}}
						></Vue3Lottie>
					</div>

					<div style={{ opacity: data.step > 1 ? "" : "0" }} class={styles.btnBox}>
						<div class={[styles.baseBtn, styles.btn1, data.step <= 2 ? "" : styles.btnDisabled]}>
							<img src={icon_2_2} />
							<img class={styles.btn0} src={icon_1} onClick={() => handleStartTune()} />
						</div>
						<div class={[styles.baseBtn, styles.btn2, data.step == 3 ? "" : styles.btnDisabled]}>
							<img src={icon_2_1} />
						</div>
						<div class={[styles.baseBtn, styles.btn3, data.step == 4 ? "" : styles.btnDisabled]}>
							<img src={icon_2_3} />
						</div>
						<div class={[styles.baseBtn, styles.btn4, data.step == 5 ? "" : styles.btnDisabled]}>
							<img src={icon_2_4} />
						</div>

						<div
							class={[
								styles.baseBtn,
								styles.btn5,
								data.step >= 6 && !evaluatingData.earphone ? "" : styles.btnDisabled,
							]}
						>
							<img src={icon_3_0} />
							<img class={styles.btn0} src={icon_1_1} onClick={() => hanldeEndTune()} />
						</div>
						<div
							class={[
								styles.baseBtn,
								styles.btn6,
								data.step >= 6 && evaluatingData.earphone && data.earPhoneType !== "有线耳机"
									? ""
									: styles.btnDisabled,
							]}
						>
							<img src={icon_3_1} />
							<img class={styles.btn0} src={icon_1_1} onClick={() => hanldeEndTune()} />
						</div>
						<div
							class={[
								styles.baseBtn,
								styles.btn7,
								data.step >= 6 && evaluatingData.earphone && data.earPhoneType === "有线耳机"
									? ""
									: styles.btnDisabled,
							]}
						>
							<img src={icon_3_2} />
							<img class={styles.btn0} src={icon_1_1} onClick={() => hanldeEndTune()} />
						</div>
						<div class={styles.dotbox}>
							<div class={styles.dotLine}>
								<div class={styles.dot}>
									<img
										style={{
											display:
												data.step >= 3 && evaluatingData.earphone && data.checkStatus !== "finish"
													? ""
													: "none",
										}}
										class={styles.dotWraning}
										src={icon_4_1}
									/>
									<img
										style={{
											display:
												data.step >= 3 && (!evaluatingData.earphone || data.checkStatus === "finish")
													? ""
													: "none",
										}}
										src={icon_4_2}
									/>
								</div>
								<div class={styles.dot}>
									<img style={{ display: data.step >= 4 ? "" : "none" }} src={icon_4_2} />
								</div>
								<div class={styles.dot}>
									<img
										style={{ display: data.step >= 5 && data.checkStatus === "ing" ? "" : "none" }}
										class={styles.dotWraning}
										src={icon_4_1}
									/>
									<img
										style={{ display: data.step >= 5 && data.checkStatus === "finish" ? "" : "none" }}
										src={icon_4_2}
									/>
								</div>
								<div class={styles.dot}>
									<img
										style={{ display: data.step >= 6 && !evaluatingData.earphone ? "" : "none" }}
										class={styles.dotWraning}
										src={icon_4_1}
									/>
									<img
										style={{ display: data.step >= 6 && evaluatingData.earphone ? "" : "none" }}
										src={icon_4_2}
									/>
								</div>
							</div>
						</div>
					</div>
				</div>
			</Popup>
		);
	},
});
