import { defineComponent, reactive, onMounted} from "vue"
import styles from "./index.module.less"
import soundWav from './timer.mp3';

let soundVIdeo: HTMLAudioElement | undefined;

const countdownData = reactive({
	isShow: false,
	step: 3,
	isAnimating: false
})
let _countdownTIme: NodeJS.Timer

export function startCountdown() {
	Object.assign(countdownData, {
		isShow: true,
		step: 3,
		isAnimating: false
	})
	//soundVIdeo?.play()
	let resolveFun: (value: boolean) => void
	_countdownTIme = setInterval(() => {
		if (countdownData.step <= 0) {
			clearInterval(_countdownTIme)
			countdownData.isShow = false
			resolveFun(true)
			//soundVIdeo?.pause()
		} else {
			countdownData.isAnimating = true
			const _time = setTimeout(() => {
				clearTimeout(_time)
				countdownData.isAnimating = false
				countdownData.step--
			}, 300) // css 动画是300毫秒 所以这里加了定时器
		}
	}, 1000)
	return new Promise( resolve => {
		resolveFun = resolve
	})
}
export default defineComponent({
	name: "countdown",
	setup() {
		if(!soundVIdeo) {
			soundVIdeo = new Audio(soundWav)
			soundVIdeo.load();
		}
		onMounted(()=>{
			soundVIdeo?.pause();
		})
		return () => (
			<>
				{countdownData.isShow && <div class={[styles.countdown,countdownData.isAnimating&&styles.isAnimating, styles[`step${countdownData.step}`]]}></div>}
			</>
		)
	}
})
