import {ref} from "vue"
import {
    audioPlayer,
    useAudioCache,
} from "./useAudio.js";

export function useYinBiaoAutoPlay () {
    const AudioP = new audioPlayer();
    const {
        cacheAudio,
    } = useAudioCache();

    const current = ref(0);
    const list = ref([]);
    let code = null;
    const isAutoPlaying = ref(false);

    async function handlePlay() {
        isAutoPlaying.value = true;
		uni.$emit('xunhuanYinbiaoBofang', isAutoPlaying.value)
        code = new Date().getTime();
        const activeYin = {
            url: list.value[current.value].yinpin,
            code
        }
        const cachedPath = await cacheAudio(activeYin.url);
        if (cachedPath && cachedPath.includes('.mp3')) {
            AudioP.play(cachedPath, code);
        } else {
            uni.showToast({
                title: '音频加载失败',
                icon: 'none'
            });
            isAutoPlaying.value = false;
			uni.$emit('xunhuanYinbiaoBofang', isAutoPlaying.value)
        }
    }

    function upd(mCode) {
        if (code !== mCode) {
            isAutoPlaying.value = false;
            uni.$emit('xunhuanYinbiaoBofang', isAutoPlaying.value)
            return;
        }

        if (current.value<list.value.length-1) {
            current.value = current.value+1;
            // 继续播放第二音频
            handlePlay();
        } else {
            // 播放结束
            isAutoPlaying.value = false;
            uni.$emit('xunhuanYinbiaoBofang', isAutoPlaying.value)
        }
    }

    function initListen() {
        uni.$on('danci-audio-ended', upd)
    }

    function removeListen() {
        uni.$off('danci-audio-ended',upd)
    }


    function playYinbiaoAuto(clist) {
		isAutoPlaying.value = true;
		uni.$emit('xunhuanYinbiaoBofang', isAutoPlaying.value)
        current.value = 0
        list.value = clist;
        // 执行首次播放
        handlePlay();
    }

    // 初始化首次监听
    initListen();
    return {
        playYinbiaoAuto,
        isAutoPlaying,
        removeListen
    }
}