import { defineComponent, reactive, ref, watch } from "vue";
import { Popover, Icon } from "vant";
import icons from "../icons/index.json";
import iconChild from "./icons/child.png";
import DotIcon from "./icons/dot.png";
import DotActiveIcon from "./icons/dot-active.png";
import DotErrorIcon from "./icons/dot-error.png";

import styles from "./index.module.less";
import state from "/src/state";
import { evaluatingData } from "/src/view/evaluating";
import { getScoreData } from "./data";

export default defineComponent({
	name: "sound-effect",
	emits: ["close"],
	setup(props, { emit }) {
		const scoreData = getScoreData(state.subjectId);
		const soundEffectData = reactive({
			step: 0,
			tips: ["左边红灯表示吹奏的音过低", "吹奏时请保持中间绿灯亮起", "右边红灯表示吹奏的音过高"],
			time: 1,
		});
		watch(
			() => evaluatingData.soundEffectFrequency,
			() => {
        // console.log('吹奏',evaluatingData.soundEffectFrequency , scoreData.frequency)
				const trend =
					Math.abs(evaluatingData.soundEffectFrequency - scoreData.frequency) <= 10 ? 1 : evaluatingData.soundEffectFrequency > scoreData.frequency ? 2 : 0;
				soundEffectData.step = trend;
				if (trend !== 1) {
					soundEffectData.time = Date.now();
				}
        // 持续时间达到3秒钟,效音成功
				if (Date.now() - soundEffectData.time > 3000) {
					// console.log("效音完成");
          emit('close')
				}
			}
		);

		/** 跳过本次 */
		const handleSelect = (e: {text: string}) => {
      if (e.text === '关闭校音'){
        emit('close', true)
        return
      } 
      emit('close')
		};
		return () => (
			<div class={styles["sound-effect"]}>
				<div class={styles.top}>
					<div class={styles.back} onClick={() => emit('close')}>
						<img src={icons["arrow-left-background"]} />
					</div>
					<Popover trigger="click" class={styles.skibtns} actions={[{ text: "跳过本次" }, { text: "关闭校音" }]} onSelect={handleSelect}>
						{{
							reference: () => (
								<div class={styles.rightSkipBtn}>
									<span>跳过本次</span>
									<Icon name="play" color="var(--van-primary-color)" class={styles.tran}/>
								</div>
							),
						}}
					</Popover>
				</div>
				<div class={styles.content}>
					<div class={styles.heiban}>
						<img class={styles.iconChild} src={iconChild} />
						<div class={styles.scoreContent}>
							<img src={scoreData.src} />
						</div>
						<div class={styles.tips}>{soundEffectData.tips[soundEffectData.step]}</div>
						<div class={styles.steps}>
							<img src={soundEffectData.step === 0 ? DotErrorIcon : DotIcon} />
							<img src={soundEffectData.step === 1 ? DotActiveIcon : DotIcon} />
							<img src={soundEffectData.step === 2 ? DotErrorIcon : DotIcon} />
						</div>
					</div>
				</div>
			</div>
		);
	},
});
