import NotifyMp3 from "@/assets/audio/notify.mp3";
import {ElMessage} from "element-plus";
import {useAlterToneStore} from "@/stores/audioStore";

let audio = new Audio(NotifyMp3)
audio.muted = true
let intervalId:any = null
let playCount = 0
let isAudioInitialized = false;
let isPlaying = false

export const initAudio = () => {
    if (!isAudioInitialized) {
        isAudioInitialized = true;
        audio.muted = false;
        audio.play().then(() => {
            ElMessage({
                message: '已开启提示音',
                type: 'success',
            });
            useAlterToneStore().setAlterTone(true);
        }).catch((error) => {
            console.error('Error playing audio:', error);
        });
        audio.currentTime = 0
    }
};

export const playAudio = () => {
    if (isPlaying) {
        return;
    }
    const alterTone = useAlterToneStore().getAlterTone();
    const superAlterTone = useAlterToneStore().getSuperAlterTone();
    const count = superAlterTone ? 15 : 1;
    console.log('播放声音，alterTone', alterTone, playCount, intervalId, superAlterTone);
    if (!alterTone) {
        return;
    }
    isPlaying = true
    audio = new Audio(NotifyMp3)
    audio.play().then(() => {
        console.log('声音播放, count, ismute,.isstop',count, audio.muted, audio.paused)
        isPlaying = false
    }).catch((error) => {
        isPlaying = false
        console.error('Error playing audio:', error);
    }).finally( () => {
        isPlaying = false
    });
    if (superAlterTone) {
        console.log('开启了超强因 intervalId = ' , intervalId)
    }
    if (superAlterTone && intervalId == null) {
        intervalId = setInterval(() => {
            playCount += 1
            if (isPlaying) {
                return
            }
            isPlaying = true;
            audio.play().then(() => {
                console.log('声音播放, count , ismute,.isstop',count, audio.muted, audio.paused)
                if (playCount >= count) {
                    stopPlay()
                }
                isPlaying = false
            }).catch((error) => {
                isPlaying = false
                console.error('Error playing audio:', error);
            });
        }, 3000);
    }

};

export const stopPlay = () => {
    if (intervalId) {
        clearInterval(intervalId);
        intervalId = null
    }
    audio.pause();
    audio.currentTime = 0;
    playCount = 0;
}

const resetAudio = () => {
    audio.pause()
    audio.currentTime = 0
}