//sdk
// <script src="//yun.duiba.com.cn/db_games/libs0924/howler.min.js"></script>

var resPath = "https://yun.duiba.com.cn/db_games/qx/hyundaiXXL/sound/";

export enum SoundType {
    bg = "bg",
    line = 'line',
    boom = 'boom',
    fall = 'fall',
    eliminate = 'eliminate',
    bonusTime = 'bonusTime',
}

export function cusPlaySound(type: SoundType, loop: boolean = false) {
    playSound(resPath + type + ".mp3", loop);
}

/**
 * 提前加载音频
 * @param type
 */
export function preloadSound(type: SoundType) {
    let src = resPath + type + ".mp3";
    soundHash[src] = new Howl({
        src: src,
        preload: true,
    });
}

/**
 * 根据路径记录
 */
const soundHash: { [key: string]: Howl } = {};

export function playSound(src: string, loop: boolean = false) {

    //console.log('测试音效',src);

    let sound: Howl;
    //循环的，且有缓存，取缓存的
    if (soundHash[src] && loop) sound = soundHash[src]
    //没有就新建
    if (!sound) sound = new Howl({ src: [src], autoplay: false, loop });
    //记录下，方便停止
    soundHash[src] = sound;
    //不循环删除缓存
    if (!loop) sound.on('stop', function () {
        delete soundHash[src]
    });
    //播放
    sound.play();
    //console.log('测试是否播放音效',src);
    //返回一个，可以自行控制
    return sound;
}

export function stopSound(src: string) {
    if (soundHash[src]) soundHash[src].stop();
}

export function stopAllSound() {
    for (let key in soundHash) soundHash[key].stop();
}

export function playAllSound() {
    for (let key in soundHash) soundHash[key].play();
}


//设置隐藏属性和改变可见属性的事件的名称
let hidden: string, visibilityChange: string;
if (typeof document.hidden !== 'undefined') {
    hidden = 'hidden';
    visibilityChange = 'visibilitychange';
} else if (typeof document['msHidden'] !== 'undefined') {
    hidden = 'msHidden';
    visibilityChange = 'msvisibilitychange';
} else if (typeof document['webkitHidden'] !== 'undefined') {
    hidden = 'webkitHidden';
    visibilityChange = 'webkitvisibilitychange';
}

const handleVisibilityChange = (e) => {
    if (document.visibilityState == "visible") {
        playAllSound();
        console.log("网页显示")
    } else if (document.visibilityState == "hidden") {
        stopAllSound()
        console.log("网页隐藏")
    }
};

document.addEventListener(
    visibilityChange,
    handleVisibilityChange,
    false
);

window.onbeforeunload = function () {
    //发接口
}

// window.addEventListener('beforeunload', ()=>{
//     //发接口出去，

// })


// document.body['onbeforeunload'] = () => {

// }

