import { computed, defineComponent, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import styles from "./index.module.less";
import {
	getMidiCurrentTime,
	getMidiDuration,
	handleTogglePlayMidi,
	hanldeInitMidiData,
	hanldeSetMidiPlaybackRate,
	setMidiCurrentTime,
} from "./midiPlayer";
import state, { IPlayState, onEnded, onPlay } from "/src/state";
import { api_playProgress, api_cloudTimeUpdae, api_cloudplayed, api_remove_cloudplayed, api_remove_cloudTimeUpdae } from "/src/helpers/communication";
import { evaluatingData } from "/src/view/evaluating";
import { cloudToggleState } from "/src/helpers/midiPlay"
import { storeData } from "/src/store";
import { handleStartTick } from "../tick";

export const audioData = reactive({
	songEle: null as HTMLAudioElement | null, // 原生
	backgroundEle: null as HTMLAudioElement | null, //伴唱
	mingSongEle: null as HTMLAudioElement | null, //唱名
	songCollection: {  // 音乐源合集 带节拍器和不带节拍器的
		songEle: null as HTMLAudioElement | null,
		backgroundEle: null as HTMLAudioElement | null,
		fanSongEle: null as HTMLAudioElement | null,
		banSongEle: null as HTMLAudioElement | null,
		mingSongEle: null as HTMLAudioElement | null,
		beatSongEle: null as HTMLAudioElement | null,
		betaBackgroundEle: null as HTMLAudioElement | null,
		betaFanSongEle: null as HTMLAudioElement | null,
		betaBanSongEle: null as HTMLAudioElement | null,
		betaMingSongEle: null as HTMLAudioElement | null
	},
	midiRender: false,
	progress: 0, // midi播放进度（单位：秒）
	duration: 0 // 音频总时长（单位：秒）
});
const midiRef = ref();
/** 播放或暂停 */
export const audioListStart = (type: "play" | "paused") => {
	// 开始播放之前, 先设置倍数
	if (type === "play" && state.originSpeed !== 0) {
		const actualRate = state.originAudioPlayRate * state.basePlayRate;
		// console.log('音频播放倍率',actualRate)
		setAudioPlaybackRate(actualRate);
	}
	// console.log('api','midi状态1',type,state.isAppPlay)
	// 如果是midi播放
	if (state.isAppPlay) {
		// handleTogglePlayMidi(type);
		cloudToggleState(type);
		return;
	}
	if (type === "play") {
		audioData.songEle?.play();
		audioData.backgroundEle?.play();
		audioData.mingSongEle?.play();
	} else if (type === "paused") {
		audioData.songEle?.pause();
		audioData.backgroundEle?.pause();
		audioData.mingSongEle?.pause();
	}
};
/** 设置倍数播放 */
export const setAudioPlaybackRate = (rate: number) => {
	// 如果是midi播放
	if (state.isAppPlay) {
		if (state.modeType === "evaluating") return
		hanldeSetMidiPlaybackRate(rate);
		return;
	}
	audioData.songEle && (audioData.songEle.playbackRate = rate);
	audioData.backgroundEle && (audioData.backgroundEle.playbackRate = rate);
	audioData.mingSongEle && (audioData.mingSongEle.playbackRate = rate);
};

/** 获取当前播放的时间 */
export const getAudioCurrentTime = () => {
	// 如果是midi播放
	if (state.isAppPlay) {
		// const c = getMidiCurrentTime();
		return audioData.progress;
	}
	// console.log('返回的时间',state.playSource, audioData.songEle?.currentTime,audioData.progress)
	if (state.playSource === "music") return audioData.songEle?.currentTime || audioData.progress;
	if (state.playSource === "background") return audioData.backgroundEle?.currentTime || audioData.progress;
	if (state.playSource === "mingSong") return audioData.mingSongEle?.currentTime || audioData.progress;
	
	return audioData.songEle?.currentTime || audioData.progress;
};
/** 获取曲谱的总时间 */
export const getAudioDuration = () => {
	// 如果是midi播放
	if (state.isAppPlay) {
		// const d = getMidiDuration();
		const songEndTime = state.times[state.times.length - 1 || 0]?.endtime || 0
		return audioData.duration || songEndTime;
	}
	// 唱名文件时长比较短，和普通文件不一样 所以这里单独处理
	if(state.playSource === "mingSong") return audioData.mingSongEle?.duration || audioData.duration;
	return audioData.songEle?.duration || audioData.backgroundEle?.duration || audioData.mingSongEle?.duration || audioData.duration;
};

/** 设置播放的开始时间 */
export const setAudioCurrentTime = (time: number, index = 0) => {
	// console.log('开始时间12345',time)
	// 如果是midi播放
	if (state.isAppPlay) {
		setMidiCurrentTime(index);
		return;
	}
	audioData.songEle && (audioData.songEle.currentTime = time);
	audioData.backgroundEle && (audioData.backgroundEle.currentTime = time);
	audioData.mingSongEle && (audioData.mingSongEle.currentTime = time);
	audioData.progress = time;
};

/** 设置当前没有播放的音频静音 */
export const toggleMutePlayAudio = (source: IPlayState, muted: boolean) => {
	if (source === "music") {
		if (audioData.songEle) {
			audioData.songEle.muted = muted;
		}
	} else if (source === "background") {
		if (audioData.backgroundEle) {
			audioData.backgroundEle.muted = muted;
		}
	} else if(source === "mingSong"){
		if (audioData.mingSongEle) {
			audioData.mingSongEle.muted = muted;
		}
	}
};

/** 切换节拍器音源 */
export const changeSongSourceByBate = (isDisBate:boolean) => {
	// isDisBate 为true 切换到不带节拍的，为false 切换到带节拍的
	const songEleCurrentTime = audioData.songEle?.currentTime || 0
	const backgroundEleCurrentTime = audioData.backgroundEle?.currentTime || 0
	const mingSongEleCurrentTime = audioData.mingSongEle?.currentTime || 0
	if (isDisBate) {
		if(state.playType === "play"){
			audioData.songEle = audioData.songCollection.songEle
			audioData.backgroundEle = audioData.songCollection.backgroundEle
		} else {
			audioData.songEle = audioData.songCollection.fanSongEle
			audioData.backgroundEle = audioData.songCollection.banSongEle
			audioData.mingSongEle = audioData.songCollection.mingSongEle
		}
	} else {
		// 没有节拍器资源的时候 用 不带节拍器的资源，防止播放不了
		if(state.playType === "play"){
			audioData.songEle = audioData.songCollection.beatSongEle || audioData.songCollection.songEle
			audioData.backgroundEle = audioData.songCollection.betaBackgroundEle || audioData.songCollection.backgroundEle
		} else {
			audioData.songEle = audioData.songCollection.betaFanSongEle || audioData.songCollection.fanSongEle
			audioData.backgroundEle = audioData.songCollection.betaBanSongEle || audioData.songCollection.banSongEle
			audioData.mingSongEle = audioData.songCollection.betaMingSongEle || audioData.songCollection.mingSongEle
		}
	}
	audioData.songEle && (audioData.songEle.currentTime = songEleCurrentTime)
	audioData.backgroundEle && (audioData.backgroundEle.currentTime = backgroundEleCurrentTime)
	audioData.mingSongEle && (audioData.mingSongEle.currentTime = mingSongEleCurrentTime)
	// 设置静音与取消静音
	if (state.playSource === "music") {
		audioData.songEle && (audioData.songEle.muted = false);
		audioData.backgroundEle && (audioData.backgroundEle.muted = true);
		audioData.mingSongEle && (audioData.mingSongEle.muted = true);
	} else if (state.playSource === "background") {
		audioData.songEle && (audioData.songEle.muted = true);
		audioData.backgroundEle && (audioData.backgroundEle.muted = false);
		audioData.mingSongEle && (audioData.mingSongEle.muted = true);
	}else {
		audioData.songEle && (audioData.songEle.muted = true);
		audioData.backgroundEle && (audioData.backgroundEle.muted = true);
		audioData.mingSongEle && (audioData.mingSongEle.muted = false);
	}
}
export default defineComponent({
	name: "audio-list",
	setup() {
		/** iframe 加载完成后, 加载midiURL */
		const handleLoad = () => {
			midiRef.value.contentWindow.handleRendered = () => {
				audioData.midiRender = true
			};
			hanldeInitMidiData(midiRef.value);
		};

		watch(
			() => state.playSource,
			() => {
				if (state.modeType === "evaluating" && !state.setting.enableAccompaniment) {
					console.log("评测模式设置了关闭伴奏,不切换原音伴奏");
					return;
				}
				if (state.playSource === "music") {
					audioData.songEle && (audioData.songEle.muted = false);
					audioData.backgroundEle && (audioData.backgroundEle.muted = true);
					audioData.mingSongEle && (audioData.mingSongEle.muted = true);
				} else if (state.playSource === "background") {
					audioData.songEle && (audioData.songEle.muted = true);
					audioData.backgroundEle && (audioData.backgroundEle.muted = false);
					audioData.mingSongEle && (audioData.mingSongEle.muted = true);
				}else {
					audioData.songEle && (audioData.songEle.muted = true);
					audioData.backgroundEle && (audioData.backgroundEle.muted = true);
					audioData.mingSongEle && (audioData.mingSongEle.muted = false);
				}
			}
		);

		const createAudio = (src?: string): Promise<HTMLAudioElement | null> => {
			if(!src){
				return Promise.resolve(null)
			}
			return new Promise((resolve) => {
				const a = new Audio(src + '?v=' + Date.now());
				a.load();
				a.onloadedmetadata = () => {
					resolve(a);
				};
				a.onerror = () => {
					resolve(null);
				};
			});
		};

		/**
		 * #11046
		 * 声音与圆点消失的节点不一致，可能原因是部分安卓手机没有立即播放，所以需要等待有音频进度返回时再播放节拍器
		 * mp3节拍器的圆点动画
		 */
		const tickAnimate = (time: number) => {
			if (storeData.isApp && state.modeType === 'evaluating' && evaluatingData.needPlayTick && time > 0) {
				evaluatingData.needPlayTick = false;
				handleStartTick()
			}
		}

		// 监听评测曲谱音频播放进度，返回
		const progress = (res: any) => {
			const currentTime = res?.currentTime || res?.content?.currentTime;
			// console.log('app进度时间',currentTime)
			const total = res?.totalDuration || res?.content?.totalDuration;
			const time = currentTime / 1000;
			audioData.progress = time;
			tickAnimate(time);
			audioData.songEle && (audioData.songEle.currentTime = time);
			audioData.backgroundEle && (audioData.backgroundEle.currentTime = time);
			audioData.mingSongEle && (audioData.mingSongEle.currentTime = time);
			audioData.duration = total / 1000;
			if (
				res?.content?.totalDuration > 1000 &&
				currentTime >= total
			) {
				if (evaluatingData.isAudioPlayEnd) return
				evaluatingData.isAudioPlayEnd = true
				onEnded();
			}
		};

		// midi播放进度回调
		const midiProgress = (res: any) => {
			// console.log('api',res)
			if (audioData.duration == 0) {
				const songEndTime = state.times[state.times.length - 1 || 0]?.endtime || 0
				audioData.duration = songEndTime
			}
			const currentTime = res?.currentTime || res?.content?.currentTime;
			const total = res?.totalDuration || res?.content?.totalDuration;
			const time = currentTime / 1000;
			audioData.progress = time;
			// if (
			// 	audioData.duration > 1000 &&
			// 	currentTime >= audioData.duration * 1000
			// ) {
			// 	console.log('midi结束')
			// 	onEnded();
			// }
			// 选段模式，播放结束
			if (state.sectionStatus && state.section.length == 2 && currentTime >= state.section) {
				//
			}
		}
		// midi播放结束回调
		const midiPlayEnd = (res: any) => {
			if (res) {
				console.log('midi结束')
				audioData.progress = 0
				onEnded();
			}
		}
		// 加载音源
		function loadAudio(){
			return Promise.all([createAudio(state.music), createAudio(state.accompany), createAudio(state.fanSong), createAudio(state.banSong), createAudio(state.mingSong)])
		}
		// 加载节拍器音源
		function loadBeatAudio(){
			return Promise.all([createAudio(state.beatSong.music), createAudio(state.beatSong.accompany), createAudio(state.beatSong.fanSong), createAudio(state.beatSong.banSong), createAudio(state.beatSong.mingSong)])
		}
		onMounted(async () => {
			// 预览的时候不走音频加载逻辑
			if(state.isPreView){
				state.isLoading = false;
				return
			}			
			if (state.playMode !== "MIDI") {
				console.time("音频加载时间")
				// 处理音源
				const [music, accompany, fanSong, banSong, mingSong] = await loadAudio()
				audioData.backgroundEle = accompany;
				audioData.songEle = music;
				Object.assign(audioData.songCollection, {
					songEle:music,
					backgroundEle:accompany,
					fanSongEle:fanSong,
					banSongEle:banSong,
					mingSongEle:mingSong
				})
				if (music) {
					music.addEventListener("play", onPlay);
					music.addEventListener("ended", onEnded);
					accompany && (accompany.muted = true);
				} else if (accompany) {
					accompany.addEventListener("play", onPlay);
					accompany.addEventListener("ended", onEnded);
				}
				if(fanSong){
					fanSong.addEventListener("play", onPlay);
					fanSong.addEventListener("ended", onEnded);
					banSong && (banSong.muted = true);
					mingSong && (mingSong.muted = true);
				}else if(banSong){
					banSong.addEventListener("play", onPlay);
					banSong.addEventListener("ended", onEnded);
					mingSong && (mingSong.muted = true);
				} else if(mingSong){
					mingSong.addEventListener("play", onPlay);
					mingSong.addEventListener("ended", onEnded);
				}
				// 处理带节拍器的音源
				const [beatMusic, beatAccompany, beatFanSong, beatBanSong, beatMingSong] = await loadBeatAudio()
				Object.assign(audioData.songCollection, {
					beatSongEle:beatMusic,
					betaBackgroundEle:beatAccompany,
					betaFanSongEle:beatFanSong,
					betaBanSongEle:beatBanSong,
					betaMingSongEle:beatMingSong
				})
				if (beatMusic) {
					beatMusic.addEventListener("play", onPlay);
					beatMusic.addEventListener("ended", onEnded);
					beatAccompany && (beatAccompany.muted = true);
				} else if (beatAccompany) {
					beatAccompany.addEventListener("play", onPlay);
					beatAccompany.addEventListener("ended", onEnded);
				}
				if(beatFanSong){
					beatFanSong.addEventListener("play", onPlay);
					beatFanSong.addEventListener("ended", onEnded);
					beatBanSong && (beatBanSong.muted = true);
					beatMingSong && (beatMingSong.muted = true);
				}else if(beatBanSong){
					beatBanSong.addEventListener("play", onPlay);
					beatBanSong.addEventListener("ended", onEnded);
					beatMingSong && (beatMingSong.muted = true);
				} else if(beatMingSong){
					beatMingSong.addEventListener("play", onPlay);
					beatMingSong.addEventListener("ended", onEnded);
				}
				state.audioDone = true;
				state.isLoading = false
				console.timeEnd("音频加载时间")
				console.log("音频数据：",audioData)
				api_playProgress(progress);
			} else {
				state.audioDone = true;
				state.isLoading = false
				const songEndTime = state.times[state.times.length - 1 || 0]?.endtime || 0
				audioData.duration = songEndTime
				// 监听midi播放进度
				api_cloudTimeUpdae(midiProgress);
				// 监听midi播放结束
				api_cloudplayed(midiPlayEnd);
			}
		});
		onUnmounted(() => {
			api_remove_cloudplayed(midiPlayEnd);
			api_remove_cloudTimeUpdae(midiProgress);
		});

		// console.log(state.playMode, state.midiUrl);
		return () => (
			<>
				<div class={styles.audioList}>
					{state.playMode === "MIDI" && state.speed != 0 && (
						<iframe
							style={{ display: "none" }}
							ref={midiRef}
							src={`/midi/index.html`}
							onLoad={handleLoad}
						/>
					)}
				</div>
			</>
		);
	},
});
