import { Skeleton } from "vant";
import { computed, defineComponent, nextTick, onBeforeMount, onBeforeUnmount, onMounted, reactive, Transition, watch, watchEffect } from "vue";
import { useRoute } from "vue-router";
import { formateTimes } from "../../helpers/formateMusic";
import Metronome, { metronomeData } from "../../helpers/metronome";
import state, { handleSetSpeed, isRhythmicExercises } from "/src/state";
import { storeData } from "../../store";
import AudioList from "../../view/audio-list";
import MusicScore, { resetMusicScore } from "../../view/music-score";
import { sysMusicScoreAccompanimentQueryPage, sysMusicScoreCategoriesQueryTree } from "../api";
import EvaluatModel from "../evaluat-model";
import HeaderTop from "../header-top";
import styles from "./index.module.less";
import { api_openCamera, api_setStatusBarVisibility, isSpecialShapedScreen } from "/src/helpers/communication";
import { getQuery } from "/src/utils/queryString";
import Evaluating, { evaluatingData } from "/src/view/evaluating";
import MeasureSpeed from "/src/view/plugins/measure-speed";
import { mappingVoicePart, subjectFingering } from "/src/view/fingering/fingering-config";
import Fingering from "/src/view/fingering";
import store from "store";
import HelperModel from "../helper-model";
import RecordingTime from "../custom-plugins/recording-time";
import ExerciseStatistics from "../custom-plugins/ExerciseStatistics";
import HomeWork from "../custom-plugins/HomeWork";
import EvaluatingWork from "../custom-plugins/EvaluatingWork";
import VipModel from "../custom-plugins/vip-verify";
import GuidePage from "../custom-plugins/guide-page";
import { handleSetCustomRender, setCustomGradual, setCustomNoteRealValue } from "../custom-plugins/custom-gradual";
import { getStorageSpeed, setGlobalData } from "/src/utils";

//特殊教材分类id
const classIds = [1, 30, 97]; // [大雅金唐, 竖笛教程, 声部训练]
const classKey = "sysMusicScoreCategoriesList";
export default defineComponent({
	name: "music-list",
	setup() {
		const route = useRoute();
		const query: any = {
			...getQuery(),
			...route.query,
		};

		const paramsId = route.params.id as string;
		const detailData = reactive({
			isLoading: true,
			paddingLeft: "",
			classList: [] as any,
		});
		const getAPPData = async () => {
			const screenData = await isSpecialShapedScreen();
			if (screenData?.content) {
				// console.log("🚀 ~ screenData:", screenData.content);
				const { isSpecialShapedScreen, notchHeight } = screenData.content;
				if (isSpecialShapedScreen) {
					detailData.paddingLeft = 25 + "px";
				}
			}
		};
		onBeforeMount(() => {
			getAPPData();
		});
		// console.log(route.params, query)
		/** 获取曲谱数据 */
		const getMusicInfo = (res: any) => {
			const index = query["part-index"] ? parseInt(query["part-index"] as string) : 0;
			const musicInfo = res.data[index] ? res.data[index] : res.data[0];
			// console.log("🚀 ~ musicInfo:", musicInfo);
			setState(musicInfo, index);
			setCustom();
			detailData.isLoading = false;
			state.partListNames = res.data.map((n: any) => n.track);
		};
		const getCategorId = (arr: any[]): any[] => {
			const list = [];
			if (!Array.isArray(arr)) return [];
			for (let i = 0; i < arr.length; i++) {
				list.push(arr[i].id);
				if (Array.isArray(arr[i][classKey])) {
					list.push(...getCategorId(arr[i][classKey]));
				}
			}
			return list;
		};
		const getIds = (arr: any[], _classids?: any[]): any[] => {
			const classids = _classids ? _classids : classIds;
			if (!Array.isArray(arr)) return [];
			const ids = [];
			for (let i = 0; i < arr.length; i++) {
				if (classids.includes(arr[i].id)) {
					ids.push(arr[i].id, ...getCategorId(arr[i][classKey]));
				} else {
					ids.push(...getIds(arr[i][classKey], classids));
				}
			}
			return ids;
		};
		/** 获取分类数据 */
		const getCategory = (res: any) => {
			detailData.classList = res.data;
		};

		const setState = (data: any, index: number) => {
			state.detailId = data.id;
			state.xmlUrl = data.xmlUrl;
			state.partIndex = index;
			state.subjectId = data.subjectId;
			state.categoriesId = data.categoriesId;
			state.categoriesName = data.categoriesName;
			state.enableEvaluation = data.enableEvaluation;
			state.examSongId = data.examSongId + "";
			state.examSongName = data.examSongName;
			// 解析扩展字段
			if (data.extConfigJson) {
				try {
					state.extConfigJson = JSON.parse(data.extConfigJson as string);
				} catch (error) {
					console.error("解析扩展字段错误:", error);
				}
				state.gradualTimes = state.extConfigJson.gradualTimes
				state.repeatedBeats = state.extConfigJson.repeatedBeats || 0
			}
			state.isOpenMetronome = !data.isOpenMetronome;
			state.needTick = data.isOpenMetronome;
			state.isShowFingering = data.isShowFingering;
			state.music = data.isOpenMetronome ? data.mp3Url : data.metronomeMp3Url;
			state.accompany = data.isOpenMetronome ? data.url : data.metronomeUrl;
			state.midiUrl = data.midiUrl;
			state.parentCategoriesId = data.parentCategoriesId;
			state.playMode = data.playMode;
			state.originSpeed = state.speed = data.speed;
			state.track = data.track;
			state.isOpenPrepare = true;

			// 映射声部ID
			state.subjectId = mappingVoicePart(state.subjectId, "GYM");
			// 是否打击乐
			state.isPercussion = state.subjectId == 23 || state.subjectId == 113 || state.subjectId == 121 || isRhythmicExercises();

			// 设置指法
			state.fingeringInfo = subjectFingering(state.subjectId);

			//小曲目 不需要计算音乐的节拍器
			if (getIds(detailData.classList, [41]).includes(data.parentCategoriesId)) {
				state.isOpenMetronome = false;
			}
			// 设置是否特殊曲谱
			state.isSpecialBookCategory = !getIds(detailData.classList).includes(state.parentCategoriesId)
			// console.log('state.isSpecialBookCategory', state.isSpecialBookCategory, state.parentCategoriesId);
		};

		const setCustom = () => {
			if (state.extConfigJson.multitrack) {
				setGlobalData("multitrack", state.extConfigJson.multitrack);
			}
		};

		onBeforeMount(() => {
			api_setStatusBarVisibility();
			const settting = store.get("musicscoresetting");
			if (settting) {
				state.setting = settting;
				if (state.setting.camera) {
					api_openCamera();
				}
				// console.log("🚀 ~ settting:", settting)
			}
		});

		onMounted(() => {
			(window as any).appName = "gym";
			Promise.all([sysMusicScoreCategoriesQueryTree(storeData.platformType === "WEB"), sysMusicScoreAccompanimentQueryPage(paramsId)]).then((values) => {
				getCategory(values[0]);
				getMusicInfo(values[1]);
			});
		});

		/** 渲染完成 */
		const handleRendered = (osmd: any) => {
			state.musicRendered = true;
			state.osmd = osmd;
			setCustomGradual();
			setCustomNoteRealValue();
			state.times = formateTimes(osmd);
			console.log("🚀 ~ state.times:", state.times);
			try {
				metronomeData.metro = new Metronome();
				metronomeData.metro.init(state.times);
			} catch (error) {}

			// 设置设置过的速度
			const storeSpeed = getStorageSpeed(state.examSongId)
			if (storeSpeed){
				handleSetSpeed(storeSpeed)
			}
			handleSetCustomRender()
		};
		/** 指法配置 */
		const fingerConfig = computed<any>(() => {
			if (state.setting.displayFingering && state.fingeringInfo?.name) {
				if (state.fingeringInfo.direction === "transverse") {
					return {
						container: {
							paddingBottom: state.fingeringInfo.height,
						},
						fingerBox: {
							height: state.fingeringInfo.height,
						},
					};
				} else {
					return {
						container: {
							paddingRight: state.fingeringInfo.width,
						},
						fingerBox: {
							position: "absolute",
							width: state.fingeringInfo.width,
							height: "100%",
							right: 0,
							top: 0,
						},
					};
				}
			}
			return {
				container: {},
				fingerBox: {},
			};
		});

		// 监听指法显示
		watch(
			() => state.setting.displayFingering,
			() => {
				if (state.fingeringInfo.direction === "vertical") {
					if (state.setting.displayFingering) {
						document.getElementById("musicAndSelection")?.style.removeProperty("--music-zoom");
					} else {
						nextTick(() => {
							resetMusicScore();
						});
					}
				}
			}
		);
		onMounted(() => {
			window.addEventListener("resize", resetMusicScore);
		});
		onBeforeUnmount(() => {
			window.removeEventListener("resize", resetMusicScore);
		});
		return () => (
			<div class={[styles.detail, state.setting.camera && styles.opencamera]} style={{ paddingLeft: detailData.paddingLeft }}>
				{!state.musicRendered && (
					<div class={styles.skeleton}>
						<Skeleton class={styles.skeleton} row={8} />
					</div>
				)}
				<div class={styles.headHeight}>
					<Transition name="van-slide-down">{state.musicRendered && <HeaderTop />}</Transition>
				</div>

				<div
					style={{ ...fingerConfig.value.container }}
					class={[styles.container, state.setting.eyeProtection && "eyeProtection", !state.setting.displayCursor && "hideCursor"]}
				>
					{/* 曲谱渲染 */}
					{!detailData.isLoading && <MusicScore key="musicscore" onRendered={handleRendered} />}
					{/* 播放 */}
					{!detailData.isLoading && <AudioList />}
					{/* 评测 */}
					{state.modeType === "evaluating" && (
						<>
							<Evaluating />
							{evaluatingData.rendered && <EvaluatModel />}
						</>
					)}
					{/* 指法 */}
					{state.setting.displayFingering && state.fingeringInfo?.name && (
						<div style={{ ...fingerConfig.value.fingerBox }}>
							<Fingering />
						</div>
					)}
				</div>

				{/* 插件模块 */}
				<div class="plugins-box">
					{state.musicRendered && (
						<>
							<MeasureSpeed />
							{/* 投屏 and 帮助 */}
							<HelperModel />
							{/* 统计训练时长 */}
							<RecordingTime />
							{/* 统计时长显示, 只有学生端显示 */}
							{storeData.platformType === "STUDENT" && <ExerciseStatistics />}
							{/* 课后训练作业 */}
							{query.workRecord && storeData.platformType === "STUDENT" && <HomeWork />}
							{/* 进度评测作业 */}
							{query.evaluatingRecord && storeData.platformType === "STUDENT" && <EvaluatingWork />}
							{/* 开通会员提示 */}
							{storeData.platformType === "STUDENT" && (query.workRecord || query.evaluatingRecord) && <VipModel />}
							{/* 引导 */}
							<GuidePage />
						</>
					)}
				</div>
			</div>
		);
	},
});
