import {nextTick, ref} from "vue";
import { debounce } from "@/utils/common";

export function useAudio() {
	const innerAudioContext = ref(null);
	const options = ref(null);
	function createAudio(audioUrl) {
		const innerAudioContext = uni.createInnerAudioContext();
		innerAudioContext.autoplay = false;
		innerAudioContext.src = audioUrl;
		innerAudioContext.onPlay(() => {
			// 播放
			uni.$emit('yy-audio-playing', options);
		});
		innerAudioContext.onError((res) => {
		  uni.$emit('yy-audio-error')
		});
		innerAudioContext.onEnded(() => {
			// 播放结束
			uni.$emit('yy-audio-end',options)
		})
		return innerAudioContext;
	}
	function changeSource(url) {
		innerAudioContext.src= url;
		innerAudioContext.currentTime = 0;
	}
	
	const debuncePlay = debounce((myOption) => {
		innerAudioContext.value = createAudio(myOption.url);
		innerAudioContext.value.play()
	},50)
	
	function handlePlay(data) {
		if (innerAudioContext.value) {
			innerAudioContext.value.stop();
			innerAudioContext.value.destroy();
			innerAudioContext.value = null;
			uni.$emit('destory-stop')	
		}
		options.value = data;
		debuncePlay(data);
	}
	
	function handleStop() {
		// console.log('stop')
		if (innerAudioContext.value) {
			innerAudioContext.value.destroy();
			innerAudioContext.value = null;
			uni.$emit('destory-stop')	
		}
	}


	// 播放过程中点击同一个视频触发终止
	uni.$on('repeat-play-to-stop',() => {
		handleStop();
	})

	// 试题切换停止播放
	uni.$on('swiper-change',() => {
		handleStop();
	})
	// 解析关闭 停止播放
	uni.$on('question-jiexi-close',() => {
		handleStop();
	})
	// 交卷 停止播放
	uni.$on('unitTest-submit', () => {
		handleStop();
	})
	
	return {
		options,
		handlePlay,
		handleStop,
		innerAudioContext
	}
}