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"

export const audioData = reactive({
	songEle: null as unknown as HTMLAudioElement,
	backgroundEle: null as unknown as HTMLAudioElement,
	midiRender: false,
	progress: 0, // midi播放进度（单位：秒）
	duration: 0 // 音频总时长（单位：秒）
});
const midiRef = ref();
/** 播放或暂停 */
export const audioListStart = (type: "play" | "paused") => {
	// 开始播放之前, 先设置倍数
	if (type === "play" && state.originSpeed !== 0) {
		setAudioPlaybackRate(state.speed / state.originSpeed);
	}
	// 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();
	} else if (type === "paused") {
		audioData.songEle?.pause();
		audioData.backgroundEle?.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);
};

/** 获取当前播放的时间 */
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;
	
	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;
	}
	return audioData.songEle?.duration || audioData.backgroundEle?.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.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;
		}
	}
};

/** 检测音源数量 */
export const detectTheNumberOfSoundSources = () => {
	let total = 0;
	if (audioData.songEle) total += 1;
	if (audioData.backgroundEle) total += 1;
	return total;
};

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);
				} else {
					audioData.songEle && (audioData.songEle.muted = true);
					audioData.backgroundEle && (audioData.backgroundEle.muted = false);
				}
			}
		);

		const createAudio = (src: string): Promise<HTMLAudioElement | null> => {
			return new Promise((resolve) => {
				const a = new Audio(src + '?v=' + Date.now());
				a.load();
				a.onloadedmetadata = () => {
					resolve(a);
				};
				a.onerror = () => {
					resolve(null);
				};
			});
		};
		// 监听评测曲谱音频播放进度，返回
		const progress = (res: any) => {
			const currentTime = res?.currentTime || res?.content?.currentTime;
			const total = res?.totalDuration || res?.content?.totalDuration;
			const time = currentTime / 1000;
			audioData.progress = time;
			audioData.songEle && (audioData.songEle.currentTime = time);
			audioData.backgroundEle && (audioData.backgroundEle.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();
			}
		}

		onMounted(() => {
			if (state.playMode !== "MIDI") {
				Promise.all([createAudio(state.music), createAudio(state.accompany)]).then(
					([music, accompany]) => {
						state.audioDone = true;
						// console.log(music, accompany);
						if (music) {
							audioData.songEle = music;
						}
						if (accompany) {
							audioData.backgroundEle = accompany;
						}
						if (audioData.songEle) {
							audioData.songEle.addEventListener("play", onPlay);
							audioData.songEle.addEventListener("ended", onEnded);
							accompany && (accompany.muted = true);
						} else if (audioData.backgroundEle) {
							audioData.backgroundEle.addEventListener("play", onPlay);
							audioData.backgroundEle.addEventListener("ended", onEnded);
						}
					}
				);

				api_playProgress(progress);
			} else {
				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>
		);
	},
});
