import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import state, { customData } from "/src/state";
import { browser } from "../utils/index";
import { transferJianNote } from "/src/helpers/customMusicScore"
import {
	isSpecialMark,
	isSpeedKeyword,
	Fraction,
	SourceMeasure,
	isGradientWords,
	GRADIENT_SPEED_RESET_TAG,
	StringUtil,
	OpenSheetMusicDisplay,
} from "/osmd-extended/src";
import { GradualChange, speedInfo } from "./calcSpeed";
const browserInfo = browser();
dayjs.extend(duration);

/**
 * 需要隐藏的中文速度文本
 */
const hideSpeedWords: string[] = ["中速"];

/**
 * 获取节拍器的时间
 * @param speed 速度
 * @param firstMeasure 曲谱第一个小节
 * @returns 节拍器的时间
 */
export const getFixTime = (speed: number) => {
	const duration: any = getDuration(state.osmd as unknown as OpenSheetMusicDisplay);
	let numerator = duration.numerator || 0;
	let denominator = duration.denominator || 4;
	const beatUnit = duration.beatUnit || "quarter";
	// if (state.repeatedBeats) {
	// 	// 音频制作问题仅2拍不重复
	// 	numerator = numerator === 2 ? 4 : numerator;
	// } else if (numerator === 2 && denominator === 4) {
	// 	numerator = 4
	// }
	// 重复节拍，拍数*2进行计算
	if (state.repeatedBeats) {
		numerator = numerator*2;
	}
	// console.log('diff', speed, duration, formatBeatUnit(beatUnit), denominator, numerator, (numerator / denominator))
	return (60 / speed) * formatBeatUnit(beatUnit) * (numerator / denominator);
};

export const retain = (time: number) => {
	return Math.ceil(time * 1000000) / 1000000;
};

export const formatLyricsEntries = (note: any) => {
	const voiceEntries = note.parentStaffEntry?.voiceEntries || [];
	const lyricsEntries: string[] = [];

	for (const voic of voiceEntries) {
		if (voic.lyricsEntries?.table) {
			const values: any[] = Object.values(voic.lyricsEntries.table);
			for (const lyric of values) {
				lyricsEntries.push(lyric?.value.text);
			}
		}
	}
	return lyricsEntries;
};

export const getMeasureDurationDiff = (measure: any) => {
	const { realValue: SRealValue } = measure.activeTimeSignature;
	const { realValue: RRealValue } = measure.duration;
	return SRealValue - RRealValue;
};

/** 按照dorico的渐快渐慢生成对应的速度 */
export const createSpeedInfo = (gradualChange: GradualChange | undefined, speed: number) => {
	if (gradualChange && speedInfo[gradualChange.startWord?.toLocaleLowerCase()]) {
		const notenum = Math.max(gradualChange.endXmlNoteIndex, 3);
		const speeds: number[] = [];
		const startSpeed = speed;
		const endSpeed = speed / speedInfo[gradualChange.startWord?.toLocaleLowerCase()];

		for (let index = 0; index < notenum; index++) {
			const speed = startSpeed + ((endSpeed - startSpeed) / notenum) * (index + 1);
			speeds.push(speed);
		}
		return speeds;
	}
	return;
};

const tranTime = (str: string = "") => {
	let result = str;
	const splits = str.split(":");
	if (splits.length === 1) {
		result = `00:${splits[0]}:00`;
	} else if (splits.length === 2) {
		result = `00:${splits[0]}:${splits[1]}`;
	}
	// console.log(`1970-01-01 00:${result}0`)
	return `1970-01-01 00:${result}0`;
};

export const getSlursNote = (note: any, pos?: "start" | "end") => {
	return pos === "end" ? note.noteElement.slurs[0]?.endNote : note.noteElement.slurs[0]?.startNote;
};

export const getNoteBySlursStart = (note: any, anyNoteHasSlurs?: boolean, pos?: "start" | "end") => {
	let activeNote = note;
	let slursNote = getSlursNote(activeNote, pos);

	for (const item of activeNote.measures) {
		if (item.noteElement.slurs.length) {
			slursNote = getSlursNote(item, pos);
			activeNote = item;
		}
	}
	return activeNote;
};

/** 根据 noteElement 获取note */
export const getParentNote = (note: any) => {
	let parentNote;
	if (note) {
		// time = activeNote.time
		for (const n of state.times) {
			if (note === n.noteElement) {
				// console.log(note)
				return n;
			}
		}
	}
	return parentNote;
};

export type FractionDefault = {
	numerator: number;
	denominator: number;
	wholeValue: number;
};

export type Duration = FractionDefault & {
	TempoInBPM: number;
	beatUnit: string;
};

export const getDuration = (osmd?: OpenSheetMusicDisplay): Duration => {
	if (osmd) {
		const { Duration, TempoInBPM, ActiveTimeSignature, TempoExpressions } = osmd.GraphicSheet.MeasureList[0][0]?.parentSourceMeasure;
		if (Duration) {
			let beatUnit = "quarter";
			for (const item of TempoExpressions) {
				beatUnit = item.InstantaneousTempo.beatUnit || "quarter";
			}
			const duration = formatDuration(ActiveTimeSignature, Duration) as unknown as FractionDefault;
			return {
				...duration,
				TempoInBPM,
				beatUnit,
			};
		}
	}
	const duration = new Fraction() as unknown as FractionDefault;
	return {
		...duration,
		TempoInBPM: 90,
		beatUnit: "quarter",
	};
};

export function formatDuration(activeTimeSignature: Fraction, duration: Fraction): Fraction {
	// 弱起第一小节duration不对
	return activeTimeSignature;
}

export function formatBeatUnit(beatUnit: string) {
	let multiple = 4;
	switch (beatUnit) {
		case "1024th":
			// bpm = bpm;
			multiple = 1024;
			break;
		case "512th":
			// divisionsFromNote = (noteDuration / 4) * 512;
			multiple = 512;
			break;
		case "256th":
			// divisionsFromNote = (noteDuration / 4) * 256;
			multiple = 256;
			break;
		case "128th":
			// divisionsFromNote = (noteDuration / 4) * 128;
			multiple = 128;
			break;
		case "64th":
			// divisionsFromNote = (noteDuration / 4) * 64;
			multiple = 64;
			break;
		case "32nd":
			// divisionsFromNote = (noteDuration / 4) * 32;
			multiple = 32;
			break;
		case "16th":
			// divisionsFromNote = (noteDuration / 4) * 16;
			multiple = 16;
			break;
		case "eighth":
			// divisionsFromNote = (noteDuration / 4) * 8;
			multiple = 8;
			break;
		case "quarter":
			multiple = 4;
			break;
		case "half":
			// divisionsFromNote = (noteDuration / 4) * 2;
			multiple = 2;
			break;
		case "whole":
			// divisionsFromNote = (noteDuration / 4);
			multiple = 1;
			break;
		case "breve":
			// divisionsFromNote = (noteDuration / 4) / 2;
			multiple = 0.5;
			break;
		case "long":
			// divisionsFromNote = (noteDuration / 4) / 4;
			multiple = 0.25;
			break;
		case "maxima":
			// divisionsFromNote = (noteDuration / 4) / 8;
			multiple = 0.125;
			break;
		default:
			break;
	}

	return multiple;
}

/** 根据音符单位，速度，几几拍计算正确的时间 */
export function getTimeByBeatUnit(beatUnit: string, bpm: number, denominator: number) {
	return (denominator / formatBeatUnit(beatUnit)) * bpm;
}

export type CustomInfo = {
	showSpeed: boolean;
	parsedXML: string;
};

/** 从xml中获取自定义信息，并删除多余的字符串 */
export const getCustomInfo = (xml: string): CustomInfo => {
	const data = {
		showSpeed: true,
		parsedXML: xml,
	};
	const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
	const words: any = xmlParse.getElementsByTagName("words");
	for (const word of words) {
		if (word && word.textContent?.trim() === "隐藏速度") {
			data.showSpeed = false;
			word.textContent = "";
		}
		if (word && word.textContent?.trim() === "@") {
			word.textContent = "segno";
		}
	}
	data.parsedXML = new XMLSerializer().serializeToString(xmlParse);
	return data;
};

/**
 * 替换文本标签中的内容
 */
const replaceTextConent = (beforeText: string, afterText: string, ele: Element): Element => {
	const words: any = ele?.getElementsByTagName("words");
	for (const word of words) {
		if (word && word.textContent?.trim() === beforeText) {
			word.textContent = afterText;
		}
	}
	return ele;
};

/**
 * 添加第一分谱信息至当前分谱
 * @param ele 需要插入的元素
 * @param fitstParent 合奏谱第一个分谱
 * @param parent 需要添加的分谱
 */
const setElementNoteBefore = (ele: Element, fitstParent: Element, parent?: Element | null) => {
	let noteIndex: number = 0;
	if (!fitstParent) {
		return;
	}
	for (let index = 0; index < fitstParent.childNodes.length; index++) {
		const element = fitstParent.childNodes[index];
		if (element.nodeName === "note") {
			noteIndex++;
		}
		if (element === ele) {
			break;
		}
	}
	if (noteIndex === 0 && parent) {
		parent.insertBefore(ele, parent.childNodes[0]);
		return;
	}
	if (parent && parent.childNodes.length > 0) {
		let noteIndex2: number = 0;
		const notes = Array.from(parent.childNodes).filter((child) => child.nodeName === "note");
		const lastNote = notes[notes.length - 1];
		if (noteIndex >= notes.length && lastNote) {
			parent.insertBefore(ele, parent.childNodes[Array.from(parent.childNodes).indexOf(lastNote)]);
			return;
		}
		for (let index = 0; index < notes.length; index++) {
			const element = notes[index];
			if (element.nodeName === "note") {
				noteIndex2 = noteIndex2 + 1;
				if (noteIndex2 === noteIndex) {
					parent.insertBefore(ele, element);
					break;
				}
			}
		}
	}
	// console.log(noteIndex, parent)
};

/**
 * 检查传入文字是否为重复关键词
 * @param text 总谱xml
 * @returns 是否是重复关键词
 */
export const isRepeatWord = (text: string): boolean => {
	if (text) {
		const innerText = text.toLocaleLowerCase();
		const dsRegEx: string = "d\\s?\\.s\\.";
		const dcRegEx: string = "d\\.\\s?c\\.";

		return (
			innerText === "@" ||
			StringUtil.StringContainsSeparatedWord(innerText, dsRegEx + " al fine", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, dsRegEx + " al coda", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, dcRegEx + " al fine", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, dcRegEx + " al coda", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, dcRegEx) ||
			StringUtil.StringContainsSeparatedWord(innerText, "da\\s?capo", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, dsRegEx, true) ||
			StringUtil.StringContainsSeparatedWord(innerText, "dal\\s?segno", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, "al\\s?coda", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, "to\\s?coda", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, "a (la )?coda", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, "fine", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, "coda", true) ||
			StringUtil.StringContainsSeparatedWord(innerText, "segno", true)
		);
	}
	return false;
};

export const onlyVisible = (xml: string, partIndex: number): string => {
	if (!xml) return "";
	// console.log('原始xml')
	const detailId = state.examSongId + "";
	const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
	const partList = xmlParse.getElementsByTagName("part-list")?.[0]?.getElementsByTagName("score-part") || [];
	const partListNames = Array.from(partList).map((item) => item.getElementsByTagName("part-name")?.[0]?.textContent?.trim() || "");
	const parts: any = xmlParse.getElementsByTagName("part");
	// const firstTimeInfo = parts[0]?.getElementsByTagName('metronome')[0]?.parentElement?.parentElement?.cloneNode(true)
	const firstMeasures = [...parts[0]?.getElementsByTagName("measure")];
	const metronomes = [...parts[0]?.getElementsByTagName("metronome")];
	const words = [...parts[0]?.getElementsByTagName("words")];
	const codas = [...parts[0]?.getElementsByTagName("coda")];
	const rehearsals = [...parts[0]?.getElementsByTagName("rehearsal")];

	/** 第一分谱如果是约定的配置分谱则跳过 */
	if (partListNames[0]?.toLocaleUpperCase?.() === "COMMON") {
		partIndex++;
		partListNames.shift();
	}
	const visiblePartInfo = partList[partIndex];
	// console.log(visiblePartInfo, partIndex)
	// 根据后台已选择的分轨筛选出能切换的声轨
	state.partListNames = partListNames;
	// console.log('分轨名称',state.partListNames)
	if (visiblePartInfo) {
		const id = visiblePartInfo.getAttribute("id");
		Array.from(parts).forEach((part: any) => {
			if (part && part.getAttribute("id") !== id) {
				part.parentNode?.removeChild(part);
				// 不等于第一行才添加避免重复添加
			} else if (part && part.getAttribute("id") !== "P1") {
				// 速度标记仅保留最后一个
				const metronomeData: {
					[key in string]: Element;
				} = {};
				for (let i = 0; i < metronomes.length; i++) {
					const metronome = metronomes[i];
					const metronomeContainer = metronome.parentElement?.parentElement?.parentElement;
					if (metronomeContainer) {
						const index = firstMeasures.indexOf(metronomeContainer);
						metronomeData[index] = metronome;
					}
				}
				Object.values(metronomeData).forEach((metronome) => {
					const metronomeContainer: any = metronome.parentElement?.parentElement;
					const parentMeasure: any = metronomeContainer?.parentElement;
					const measureMetronomes = [...(parentMeasure?.childNodes || [])];
					const metronomesIndex = metronomeContainer ? measureMetronomes.indexOf(metronomeContainer) : -1;
					// console.log(parentMeasure)
					if (parentMeasure && metronomesIndex > -1) {
						const index = firstMeasures.indexOf(parentMeasure);
						const activeMeasure = part.getElementsByTagName("measure")[index];
						setElementNoteBefore(metronomeContainer, parentMeasure, activeMeasure);
					}
				});
				/** word比较特殊需要精确到note位置 */
				words.forEach((word) => {
					let text = word.textContent || "";
					text = ["cresc."].includes(text) ? "" : text;
					if ((isSpecialMark(text) || isSpeedKeyword(text) || isGradientWords(text) || isRepeatWord(text) || GRADIENT_SPEED_RESET_TAG) && text) {
						const wordContainer = word.parentElement?.parentElement;
						const parentMeasure = wordContainer?.parentElement;
						const measureWords = [...(parentMeasure?.childNodes || [])];
						const wordIndex = wordContainer ? measureWords.indexOf(wordContainer) : -1;
						if (wordContainer && parentMeasure && wordIndex > -1) {
							const index = firstMeasures.indexOf(parentMeasure);
							const activeMeasure = part.getElementsByTagName("measure")[index];
							// 找当前小节是否包含word标签
							const _words = Array.from(activeMeasure?.getElementsByTagName("words") || []);
							// 遍历word标签,检查是否和第一小节重复,如果有重复则不平移word
							const total = _words.reduce((total: any, _word: any) => {
								if (_word.textContent?.includes(text)) {
									total++;
								}
								return total;
							}, 0);
							if (total === 0) {
								if (["12280"].includes(detailId)) {
									activeMeasure?.insertBefore(wordContainer.cloneNode(true), activeMeasure?.childNodes[wordIndex]);
								} else {
									setElementNoteBefore(wordContainer, parentMeasure, activeMeasure);
								}
							}
						}
					}
				});
				/** word比较特殊需要精确到note位置 */
				codas.forEach((coda) => {
					const wordContainer = coda.parentElement?.parentElement;
					const parentMeasure = wordContainer?.parentElement;
					const measureWords = [...(parentMeasure?.childNodes || [])];
					const wordIndex = wordContainer ? measureWords.indexOf(wordContainer) : -1;
					if (wordContainer && parentMeasure && wordIndex > -1) {
						const index = firstMeasures.indexOf(parentMeasure);
						const activeMeasure = part.getElementsByTagName("measure")[index];
						if (["12280"].includes(detailId)) {
							activeMeasure?.insertBefore(wordContainer.cloneNode(true), activeMeasure?.childNodes[wordIndex]);
						} else {
							setElementNoteBefore(wordContainer, parentMeasure, activeMeasure);
						}
					}
				});
				rehearsals.forEach((rehearsal) => {
					const container = rehearsal.parentElement?.parentElement;
					const parentMeasure = container?.parentElement;
					// console.log(rehearsal)
					if (parentMeasure) {
						const index = firstMeasures.indexOf(parentMeasure);
						part.getElementsByTagName("measure")[index]?.appendChild(container.cloneNode(true));
						// console.log(index, parentMeasure, firstMeasures.indexOf(parentMeasure))
					}
				});
			} else {
				words.forEach((word, idx) => {
					const text = word.textContent || "";
					// if (idx == 0 && text) {
					// 	word.textContent = '测试一下'
					// 	word.setAttribute('default-y',60)
					// 	word.setAttribute('margin-left',300)
					// 	word.setAttribute('y',300)
					// 	word.outerHTML = '<words default-x="155" default-y="100" justify="right" valign="middle" font-family="SimHei" font-style="normal" font-size="11.9365" font-weight="normal">哈哈哈哈哈</words>'
					// }
					if (isSpeedKeyword(text) && text) {
						const wordContainer = word.parentElement?.parentElement?.parentElement;
						if (wordContainer && wordContainer.firstElementChild && wordContainer.firstElementChild !== word) {
							const wordParent = word.parentElement?.parentElement;
							const fisrt = wordContainer.firstElementChild;
							wordContainer.insertBefore(wordParent, fisrt);
						}
					}
				});
			}

			// 最后一个小节的结束线元素不在最后 调整
			if (part && part.getAttribute("id") === id) {
				const barlines = part.getElementsByTagName("barline");
				const lastParent = barlines[barlines.length - 1]?.parentElement;
				if (lastParent?.lastElementChild?.tagName !== "barline") {
					const children = lastParent?.children || [];
					for (let el of children) {
						if (el.tagName === "barline") {
							// 将结束线元素放到最后
							lastParent?.appendChild(el);
							break;
						}
					}
				}
			}
		});
		Array.from(partList).forEach((part) => {
			if (part && part.getAttribute("id") !== id) {
				part.parentNode?.removeChild(part);
			}
		});
	}
	// console.log(xmlParse)
	return new XMLSerializer().serializeToString(appoggianceFormate(xmlParse));
};

export const onlyVisible2 = (xml: string): string => {
	if (!xml) return "";
	// console.log('原始xml')
	const detailId = state.examSongId + "";
	const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
	const partList = xmlParse.getElementsByTagName("part-list")?.[0]?.getElementsByTagName("score-part") || [];
	const partListNames = Array.from(partList).map((item) => item.getElementsByTagName("part-name")?.[0]?.textContent?.trim() || "");


	state.partListNames = partListNames;

	Array.from(partList).forEach((part) => {
		let partListName = part.getElementsByTagName("part-name")?.[0]?.textContent?.trim();
		if (!state.canSelectTracks.includes(partListName)) {
			part.parentNode?.removeChild(part);
		}
	});
	// console.log(xmlParse)
	return new XMLSerializer().serializeToString(appoggianceFormate(xmlParse));
};

// 倚音后连音线
export const appoggianceFormate = (xmlParse: Document): Document => {
	if (!xmlParse) return xmlParse;
	const graces: any = xmlParse.querySelectorAll("grace");
	if (!graces.length) return xmlParse;
	const getNextElement = (el: HTMLElement): HTMLElement => {
		if (el.querySelector("grace")) {
			return getNextElement(el?.nextElementSibling as HTMLElement);
		}
		return el;
	};
	for (let grace of graces) {
		const notations = grace.parentElement?.querySelector("notations");
		if (notations && notations.querySelectorAll("slur").length > 1) {
			let nextEle: Element = getNextElement(grace.parentElement?.nextElementSibling as HTMLElement);
			if (nextEle && nextEle.querySelectorAll("slur").length > 0) {
				const slurNumber = Array.from(nextEle.querySelector("notations")?.children || []).map((el: Element) => {
					return el.getAttribute("number");
				});
				const slurs = notations.querySelectorAll("slur");
				for (let nota of slurs) {
					if (!slurNumber.includes(nota.getAttribute("number"))) {
						nextEle.querySelector("notations")?.appendChild(nota);
					}
				}
			}
		}
	}
	return xmlParse;
};

/** 根据ID获取最顶级ID */
export const isWithinScope = (tree: any[], id: number): number => {
	if (!tree) return 0;
	let result = 0;
	for (const item of tree) {
		if (item.id === id) {
			result = item.id;
			break;
		}
		if (item.sysMusicScoreCategoriesList) {
			result = isWithinScope(item.sysMusicScoreCategoriesList, id);
			if (result > 0) {
				result = item.id;
			}
			if (result) break;
		}
	}
	return result;
};

class NoteList {
	notes: any[] = [];
	constructor(notes: any[]) {
		this.notes = notes;
	}

	public last() {
		return this.notes[this.notes.length - 1];
	}

	public list() {
		return this.notes;
	}
}

export const getNotesByid = (id: string): NoteList => {
	const notes = new NoteList(state.times.filter((item) => item.id === id));
	return notes;
};

/** 格式化当前曲谱缩放比例 */
export const formatZoom = (num = 1) => {
	return num * state.zoom;
};

/** 妙极客多分轨的曲子，可能没有part-name标签，需要手动加上该标签 */
export const xmlAddPartName = (xml: string) => {
	if (!xml) return "";
	const xmlParse = new DOMParser().parseFromString(xml, "text/xml");
	const scoreParts = Array.from(xmlParse.getElementsByTagName("score-part"));
	for (const scorePart of scoreParts) {
		if (scorePart.getElementsByTagName("part-name").length === 0) {
			state.evxmlAddPartName = true;
			const name = scorePart.getAttribute("id") || "";
			const newPartName = `<part-name>${name}</part-name>`
			// scorePart.prepend(newPartName);
			scorePart.innerHTML = newPartName + scorePart.innerHTML;
		} 
		if (scorePart.getElementsByTagName("part-name").length && !scorePart.getElementsByTagName("part-name")?.[0]?.textContent?.trim() ) {
			scorePart.getElementsByTagName("part-name")[0].textContent = scorePart.getAttribute("id") || "";
		}
	}
	return new XMLSerializer().serializeToString(xmlParse);
}

/** 格式化曲谱
 * 1.全休止符的小节,没有音符默认加个全休止符
 */
export const formatXML = (xml: string, xmlUrl?: string): string => {
	if (!xml) return "";
	const xmlParse = new DOMParser().parseFromString(xml, "text/xml");

	// 声调
	const fifths = xmlParse.getElementsByTagName("fifths");
	if (fifths && fifths.length) {
		// 是否是C调
		state.isCTone = fifths[0].textContent === '0'
	}

	const endings = Array.from(xmlParse.getElementsByTagName("ending"));
	for (const ending of endings) {
		// if (ending.getAttribute('type') === 'stop') {
		// 	// @ts-ignore
		// 	ending.parentNode?.removeChild(ending.parentNode?.getElementsByTagName('bar-style')[0])
		// }
		// @ts-ignore
		// ending.parentNode.parentNode?.removeChild(ending.parentNode)
	}

	const measures = Array.from(xmlParse.getElementsByTagName("measure"));
	const minutes: any = xmlParse.getElementsByTagName("per-minute");
	let speeds: any = []
	for (const minute of minutes) {
		let measureSpeed = minute.textContent ? Number(minute.textContent) : 0;
		// 速度带附点，需要转换成不带附点的速度值
		const hasSpeedDot = Array.from(minute?.parentElement?.children || []).some((item: any) => item?.tagName === 'beat-unit-dot')
		measureSpeed = hasSpeedDot ? measureSpeed + measureSpeed/2 : measureSpeed;
		if (minute.textContent && measureSpeed) {
			speeds.push(Number(measureSpeed))
		}
		// if (hasSpeedDot && measureSpeed) {
		// 	minute.textContent = measureSpeed
		// 	const dotDom = minute?.parentElement.querySelector('beat-unit-dot')
		// 	minute?.parentElement?.removeChild(dotDom)
		// }
	}
	speeds = [...new Set(speeds)]
	const hasVaryingSpeed = speeds.length > 1 ? true : false
  // 如果后台没有设置速度，默认取xml速度，如果xml也没有速度，默认赋值100
	if (state.originSpeed === 0) {
		state.originSpeed = speeds[0] ? speeds[0] : 100;
		state.speed = state.originSpeed;
	}
	// 如果谱面和小节都没有打速度，osmd设置的小节速度默认取后台设置的速度
	if (speeds.length === 0) {
		;(window as any).baseMeasureSpeed = state.originSpeed
	} else {
		state.originAudioPlayRate = speeds[0] / state.originSpeed
	}
	console.log('是否是变速的曲子：',hasVaryingSpeed,speeds)

	const repeats: any = Array.from(xmlParse.querySelectorAll('repeat'));
	compatibleXmlPitchVoice(xmlParse);
	// 获取作词、作曲家
	getComposer(xmlParse);
	// 处理重复小节信息
	parseXmlToRepeat(repeats)
	// 解析处理evxml
	if (state.isEvxml) {
		analyzeEvxml(xmlParse, xmlUrl);
		customizationXml(xmlParse);
	}
	// const words: any = xmlParse.getElementsByTagName("words");
	// for (const word of words) {
	// 	if (word && word.textContent?.trim() === "筒音作5") {
	// 		word.setAttribute('y',260)
	// 		word.outerHTML = '<words id="test-word" default-x="805" default-y="100" x="200" justify="right" valign="middle" font-family="SimHei" font-style="normal" font-size="11.9365" font-weight="normal">筒音作5</words>'
	// 	}
	// }
	// console.log(11111,Array.from(xmlParse.getElementsByTagName("staffline")),Array.from(xmlParse.getElementsByTagName("words")))
	let speed = -1
	let beats = -1;
	let beatType = -1;
	// 前面小节的拍子
	let preBeats: number = 4;
	let preBeatType: number = 4;
	// 小节中如果没有节点默认为休止符
	for (const measure of measures) {
		if (beats === -1 && measure.getElementsByTagName("beats").length) {
			beats = parseInt(measure.getElementsByTagName("beats")[0].textContent || "4");
		}
		if (beatType === -1 && measure.getElementsByTagName("beat-type").length) {
			beatType = parseInt(measure.getElementsByTagName("beat-type")[0].textContent || "4");
		}
		if (speed === -1 && measure.getElementsByTagName('per-minute').length) {
		  speed = Number(measure.getElementsByTagName('per-minute')[0]?.textContent)
		}
		// 当前小节的拍数
		const currentBeats = measure.getElementsByTagName("beats").length ? measure.getElementsByTagName("beats")[0]?.textContent : preBeats;
		const currentBeatType = measure.getElementsByTagName("beat-type").length ? measure.getElementsByTagName("beat-type")[0]?.textContent : preBeatType;
		preBeats = Number(currentBeats);
		preBeatType = Number(currentBeatType);
		const divisions = parseInt(measure.getElementsByTagName("divisions")[0]?.textContent || "256");
		// 如果note节点里面有space节点，并且没有duration节点，代表这是一个空白节点，需要删除
		if (measure.getElementsByTagName("note").length && state.isEvxml) {
			const noteList = Array.from(measure.getElementsByTagName("note")) || [];
			noteList.forEach((note: any) => {
				// if (note.getElementsByTagName("space").length && !note.getElementsByTagName("duration").length) {
				// 	measure.removeChild(note);
				// }
				// 非倚音音符
				if (!note.getElementsByTagName("grace").length) {
					if (!note.getElementsByTagName("duration").length || (note.getElementsByTagName("duration").length && note.getElementsByTagName("duration")[0]?.textContent == 0)) {
						measure.removeChild(note);
					}
				}
			});
		}
		// 如果有特殊中文速度文本，需要删除
		const reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
		if (measure.getElementsByTagName("words").length && state.isEvxml) {
			const wordList = Array.from(measure.getElementsByTagName("words")) || [];
			wordList.forEach((word: any) => {
				// TODO:删除妙极客曲子无意义的words
				// wordArr?.push(word?.textContent)
				if (word?.textContent && reg.test(word?.textContent) && word?.parentNode?.parentNode) {
					measure.removeChild(word.parentNode.parentNode);
					// deleteWordArr?.push(word?.textContent)
				}
				// if(hideSpeedWords.includes(word?.textContent) && word?.parentNode?.parentNode) {
				// 	measure.removeChild(word.parentNode.parentNode);
				// }
			})
		}
		if (measure.getElementsByTagName("note").length === 0) {
			const forwardTimeElement = measure.getElementsByTagName("forward")[0]?.getElementsByTagName("duration")[0];
			if (forwardTimeElement) {
				forwardTimeElement.textContent = "0";
			}
			measure.innerHTML =
				measure.innerHTML +
				`
        <note>
          <rest measure="yes"/>
          <duration>${divisions * beats}</duration>
          <voice>1</voice>
          <type>whole</type>
        </note>`;
		} else if (state.musicRenderType !== 'staff') {
			transferJianNote(measure, divisions, preBeats, preBeatType)
		}
	}
	return new XMLSerializer().serializeToString(xmlParse);
};


/** 获取所有音符的时值,以及格式化音符 */
export const formateTimes = (osmd: OpenSheetMusicDisplay) => {
	const customNoteRealValue = customData.customNoteRealValue;
	const customNoteCurrentTime = customData.customNoteCurrentTime;
	const detailId = state.examSongId + "";
	const partIndex = state.partIndex + "";
	let fixtime = browserInfo.huawei ? 0.08 : 0; //getFixTime()
	const allNotes: any[] = [];
	const allNoteId: string[] = [];
	const allMeasures: any[] = [];
	const { originSpeed: baseSpeed } = state;
	let preMeasureNumber = 0;
	const formatRealKey = (realKey: number, detail: any) => {
		// 不是管乐迷, 不处理
		// if (state.appName !== "GYM") return realKey;
		// 长笛的LEVEL 2-5-1条练习是泛音练习，以每小节第一个音的指法为准，高音不变变指法。
		const olnyOneIds = ["906"];
		if (olnyOneIds.includes(state.cbsExamSongId)) {
			return detail.measures[0]?.realKey || realKey;
		}
		// 圆号的LEVEL 2-5条练习是泛音练习，最后四小节指法以连音线第一个小节为准
		const olnyOneIds2 = ["782", "784"];
		if (olnyOneIds2.includes(state.cbsExamSongId)) {
			const measureNumbers = [14, 16, 30, 32];
			if (measureNumbers.includes(detail.firstVerticalMeasure?.measureNumber)) {
				return allNotes[allNotes.length - 1]?.realKey || realKey;
			}
		}
		// 2-6 第三小节指法按照第一个音符显示
		const filterIds = ["900", "901", "640", "641", "739", "740", "800", "801", "773", "774", "869", "872", "714", "715"];
		if (filterIds.includes(state.cbsExamSongId)) {
			if (detail.firstVerticalMeasure?.measureNumber === 3 || detail.firstVerticalMeasure?.measureNumber === 9) {
				return detail.measures[0]?.realKey || realKey;
			}
		}
		return realKey;
	};
	if (!osmd.cursor) return [];
	const iterator: any = osmd.cursor.Iterator;
	// console.log("🚀 ~ iterator:", iterator)
	console.time("音符跑完时间");

	let i = 0;
	let si = 0;
	let measures: any[] = [];
	let stepSpeeds: number[] = [];
	/** 弱起时间 */
	let difftime = 0;
	let usetime = 0;
	let relaMeasureLength = 0;
	let beatUnit = "quarter";
	let gradualSpeed;
	let gradualChange: GradualChange | undefined;
	let gradualChangeIndex = 0;
	let totalMultipleRestMeasures = 0;
	let multipleRestMeasures = 0;
	let staveNoteIndex = 0;
	let staveIndex = 0;
	let xmlMp3BeatFixTime = 0 // xml上节拍器的时间

	let preNoteEndTime = 0; // 上一个音符的结束时间

	let preNoteMeasureNumber = 0; // 上一个小节的number值

	const _notes = [] as any[];
	if (state.gradualTimes) {
		console.log("后台设置的渐慢小节时间", state.gradual, state.gradualTimes);
	}

	let currentTimeStamp = iterator.currentTimeStamp.RealValue;
	const currentTimes = [] as any[];
	let isSetNextNoteReal = false;
	let differFrom = 0;
	// let testIdx = 0;
	let repeatIdx = 0; // 循环的次数
	const firstTrackName = state.canSelectTracks[0] || "";
	while (!iterator.EndReached) {
		// console.log({ ...iterator });
		/** 多声轨合并显示，当前音符的时值取所有声轨中的最小值 */
		if (state.isCombineRender) {
			iterator.currentVoiceEntries = iterator.currentVoiceEntries.filter((item: any) => {
				const trackName = state.isEvxml && state.evxmlAddPartName ? item.parentVoice.parent.IdString || '' : item.parentVoice.parent.Name || '';
				return trackName === firstTrackName
			});
		}
		let minIndex = 0, elRealValue = 0
		for (let index = 0; index < iterator.currentVoiceEntries.length; index++) {
			const element = iterator.currentVoiceEntries[index];
			if (element.isGrace) {
				if (minIndex == index && minIndex == 0) {
				minIndex = iterator.currentVoiceEntries.length > 1 ? 1 : 0
				}
				continue
			}
			if (element.notes[0].length.realValue < elRealValue) {
				minIndex = index
			}
			elRealValue = element.notes[0].length.realValue
		}
		if (minIndex !== 0 && state.isCombineRender && iterator.currentVoiceEntries[minIndex]) {
			iterator.currentVoiceEntries[minIndex].Notes[0].NoteToGraphicalNoteObjectId = iterator.currentVoiceEntries?.[0].Notes[0].NoteToGraphicalNoteObjectId;
		}
		const voiceEntries = iterator.currentVoiceEntries?.[minIndex] ? [iterator.currentVoiceEntries?.[minIndex]] : [];
		let currentVoiceEntries: any[] = [];
		// 多分轨，当前小节最大音符数量
		let maxNoteNum = 0;
		// iterator.currentMeasure?.verticalMeasureList?.forEach((item: any) => maxNoteNum = Math.max(maxNoteNum, item?.staffEntries?.length || 0))
		maxNoteNum = iterator.currentMeasure?.verticalSourceStaffEntryContainers.length || 0
		// console.log(iterator.currentMeasure.MeasureNumberXML,maxNoteNum,iterator.currentMeasure?.verticalSourceStaffEntryContainers.length)
		// 单声部多声轨
		if (state.multitrack > 0) {
			currentVoiceEntries = [...iterator.CurrentVoiceEntries];
		} else {
			currentVoiceEntries = [...iterator.CurrentVoiceEntries].filter((n) => {
				return n && n?.ParentVoice?.VoiceId != 1;
			});
		}
		let currentTime = 0;
		let isDouble = false;
		let isMutileSubject = false;

		if (currentVoiceEntries.length && !isSetNextNoteReal) {
			isDouble = true;
			let voiceNotes = [...iterator.CurrentVoiceEntries].reduce((notes, n) => {
				notes.push(...n.Notes);
				return notes;
			}, [] as any);
			voiceNotes = voiceNotes.filter((note: any) => !note.IsGraceNote)
			voiceNotes = voiceNotes.sort((a: any, b: any) => a?.length?.realValue - b?.length?.realValue);
			currentTime = voiceNotes?.[0]?.length?.realValue || 0;

			if (state.multitrack > 0 && currentVoiceEntries.length === 2) {
				const min = voiceNotes[0]?.length?.realValue || 0;
				const max = voiceNotes[voiceNotes.length - 1]?.length?.realValue || 0;
				differFrom = max - min;
				isSetNextNoteReal = differFrom === 0 ? false : true;
			}
		}
		// 多声部上下音符没对齐,光标多走一拍
		if (_notes[_notes.length - 1]?.isDouble && !currentVoiceEntries.length) {
			isMutileSubject = true;
		}
		if (state.multitrack > 0 && !isDouble && isSetNextNoteReal) {
			isDouble = true;
			currentTime = differFrom;
			isSetNextNoteReal = false;
			differFrom = 0;
		}
		currentTimes.push(iterator.currentTimeStamp.realValue - currentTimeStamp);
		currentTimeStamp = iterator.currentTimeStamp.realValue;
		for (const v of voiceEntries) {
			let note = v.notes[0];
			if (note.IsGraceNote) {
				// 如果是装饰音, 取不是装饰音的时值
				const voice = note.parentStaffEntry.voiceEntries.find((_v: any) => !_v.isGrace);
				if (!voice) {
					continue;
				}
				note = voice.notes[0];
			}
			note.fixedKey = note.ParentVoiceEntry.ParentVoice.Parent.SubInstruments[0].fixedKey || 0;
			// 有倚音
			if (note?.voiceEntry?.isGrace) {
				isDouble = true;
				let ns = [...iterator.currentVoiceEntries].reduce((notes, n) => {
					notes.push(...n.notes);
					return notes;
				}, []);
				ns = ns.sort((a: any, b: any) => b?.length?.realValue - a?.length?.realValue);
				currentTime = currentTime != 0 ? Math.min(ns?.[0]?.length?.realValue, currentTime) : ns?.[0]?.length?.realValue;
			}
			if (state.multitrack > 0 && currentTime > note.length.realValue) {
				currentTime = note.length.realValue;
			}
			note.maxNoteNum = maxNoteNum;
			note.trackIndex = minIndex;
			_notes.push({
				note,
				iterator: { ...iterator },
				currentTime,
				isDouble,
				isMutileSubject,
				measuresTempoInBPM: note?.sourceMeasure?.tempoInBPM
			});
		}

		iterator.moveToNextVisibleVoiceEntry(false);
		// 从头开始循环，repeatIdx标记+1
		if (iterator.backJumpOccurred) {
			repeatIdx += 1;
		}
		iterator.repeatIdx = repeatIdx;
		// console.log('小节',testIdx,iterator.repeatIdx,iterator.EndReached,iterator.currentMeasureIndex,iterator.backJumpOccurred,iterator.forwardJumpOccurred)
		// testIdx += 1;
	}
	// 是否是变速的曲子
	const hasVaryingSpeed = _notes.some((item: any) => item.measuresTempoInBPM !== _notes[0].measuresTempoInBPM)
	console.log('变速曲子',hasVaryingSpeed, _notes)
	let noteIds: any = [];
	// let voicesBBox: any = null;
	for (let { note, iterator, currentTime, isDouble, isMutileSubject } of _notes) {
		if (note) {
			if (preMeasureNumber != note?.sourceMeasure?.MeasureNumberXML) {
				si = 0
			}
			if (si === 0 && preMeasureNumber != note?.sourceMeasure?.MeasureNumberXML) {
				preMeasureNumber = note?.sourceMeasure?.MeasureNumberXML
				allMeasures.push(note.sourceMeasure);
			}
			if (si === 0 && state.isSpecialBookCategory) {
				for (const expression of (note.sourceMeasure as SourceMeasure)?.TempoExpressions) {
					if (expression?.InstantaneousTempo?.beatUnit) {
						// 取最后一个有效的tempo
						beatUnit = expression.InstantaneousTempo.beatUnit;
					}
				}
			}
			// 判断是否是同一小节
			if (staveIndex == note.sourceMeasure?.MeasureNumberXML && i !== 0) {
				staveNoteIndex++
			} else {
				// staveIndex不同,重新赋值
				staveIndex = note.sourceMeasure?.MeasureNumberXML
				staveNoteIndex = 0
			}			
			let measureSpeed = note.sourceMeasure.tempoInBPM;
			const { metronomeNoteIndex } = iterator.currentMeasure;
			if (metronomeNoteIndex !== 0 && metronomeNoteIndex > si) {
				measureSpeed = allNotes[allNotes.length - 1]?.speed || 100;
			}
			// 当前的分轨
			let activeVerticalMeasureList: any = [];
			/**
			 * bug: #9959
			 * 多分轨合并展示，第一分轨又可能获取不到对应的音符，需要在当前小节中音符最多的分轨中去查找音符
			 */
			// if (state.isCombineRender) {
			// 	const allTrackList = note.sourceMeasure.verticalMeasureList;
			// 	let maxIdx = 0, maxNote = 0;
			// 	allTrackList.forEach((item: any, index: number) => {
			// 		if (item?.vfVoices['1']?.tickables?.length > maxNote) {
			// 			maxIdx = index
			// 			maxNote = item?.vfVoices['1']?.tickables?.length
			// 		}
			// 	})
			// 	activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[maxIdx]] || [];
			// } else {
			// 	activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[0]] || [];
			// }
			
			// 合并展示某些分轨，需要把展示的分轨筛选出来
			if (state.isCombineRender && note.sourceMeasure.verticalMeasureList.length) {
				note.sourceMeasure.verticalMeasureList = note.sourceMeasure?.verticalMeasureList.filter((item: any) => state.canSelectTracks.includes(item?.parentStaff?.parentInstrument.Name))
			}

			activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[0]] || [];
			// 某些情况下，合并显示的妙极客曲子，note.sourceMeasure?.verticalMeasureList可能为空数组
			if (state.isCombineRender && state.isEvxml && note.sourceMeasure?.verticalMeasureList.length === 0) {
				activeVerticalMeasureList = osmd.GraphicSheet.MeasureList.find((item: any) => item[0]?.MeasureNumber === note.sourceMeasure.MeasureNumberXML) || [];
			}
			let currenrtVfVoices = activeVerticalMeasureList[0]?.vfVoices['1'] ? activeVerticalMeasureList[0]?.vfVoices['1'] : activeVerticalMeasureList[0]?.vfVoices['2'] ? activeVerticalMeasureList[0]?.vfVoices['2'] : null;
			/**
			 * TODO:多分轨合并的小节，音符可能没有id，此时就去其它分轨找
			 */
			const vmLength = note.sourceMeasure?.verticalMeasureList?.length
			let currentVmIndex = 0;
			let hasSvgElement = currenrtVfVoices?.tickables[staveNoteIndex];
			while (!hasSvgElement && vmLength > 1 && currentVmIndex <= vmLength - 1 && currenrtVfVoices !== null) {
				currentVmIndex += 1;
				activeVerticalMeasureList = [note.sourceMeasure?.verticalMeasureList?.[currentVmIndex]] || [];
				currenrtVfVoices = activeVerticalMeasureList[0]?.vfVoices['1'] ? activeVerticalMeasureList[0]?.vfVoices['1'] : activeVerticalMeasureList[0]?.vfVoices['2'] ? activeVerticalMeasureList[0]?.vfVoices['2'] : null;
				hasSvgElement = currenrtVfVoices?.tickables[staveNoteIndex];
			}

			const { realValue } = iterator.currentTimeStamp;
			const { RealValue: vRealValue, Denominator: vDenominator } = formatDuration(
				iterator.currentMeasure.activeTimeSignature,
				iterator.currentMeasure.duration
			);
			let { wholeValue, numerator, denominator, realValue: NoteRealValue } = note.length;
			if (customNoteRealValue[i]) {
				// console.log(NoteRealValue, customNoteRealValue[i])
				NoteRealValue = customNoteRealValue[i];
			}
			if (isDouble && currentTime > 0) {
				if (currentTime != NoteRealValue) {
					// console.log(`小节 ${note.sourceMeasure.MeasureNumberXML} 替换: noteLength: ${NoteRealValue}, 最小: ${currentTime}`);
					NoteRealValue = currentTime;
				}
			}
			// note.sourceMeasure.MeasureNumberXML === 8 && console.error(`小节 ${note.sourceMeasure.MeasureNumberXML}`, NoteRealValue)
			// 管乐迷,按自定义按读取到的音符时值
			if (customNoteCurrentTime) {
				if (isMutileSubject && currentTimes[i + 1] > 0 && NoteRealValue > currentTimes[i + 1]) {
					// console.log(NoteRealValue, currentTimes[i + 1])
					NoteRealValue = currentTimes[i + 1];
				}
			}

			let relativeTime = usetime;

			// 妙极客的曲子，修复有的音符有times，有的音符没有times导致的，累计时长错误问题
			if (state.isEvxml && relativeTime < preNoteEndTime - fixtime) {
				relativeTime = preNoteEndTime - fixtime
			}

			let beatSpeed = 0;
			// 速度不能为0 此处的速度应该是按照设置的速度而不是校准后的速度，否则mp3速度不对
			if (measureSpeed !== baseSpeed && !hasVaryingSpeed) {
				beatSpeed = baseSpeed || measureSpeed || 100
			} else {
				beatSpeed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
			}
			// let beatSpeed = measureSpeed || baseSpeed
			// 如果有节拍器,需要将节拍器的时间算出来
			if (i === 0) {
				if(state.isOpenMetronome){
					fixtime += getFixTime(beatSpeed);
					state.fixtime = fixtime;
				}
				// 存储mp3节拍器时间
				xmlMp3BeatFixTime = getFixTime(beatSpeed)
				// console.log("fixtime:", fixtime, '速度:', beatSpeed, "state.isSpecialBookCategory:", state.isSpecialBookCategory, 'state.isOpenMetronome:', state.isOpenMetronome);
			}
			// console.log(getTimeByBeatUnit(beatUnit, measureSpeed, iterator.currentMeasure.activeTimeSignature.Denominator))
			let gradualLength = 0;
			let speed = (state.isSpecialBookCategory ? measureSpeed : baseSpeed) || 1;
			gradualChange = iterator.currentMeasure.speedInfo || gradualChange;
			gradualSpeed = osmd.Sheet.SoundTempos?.get(note.sourceMeasure.measureListIndex) || gradualSpeed;
			if (!gradualSpeed || gradualSpeed.length < 2) {
				gradualSpeed = createSpeedInfo(gradualChange, speed);
			}
			// console.log({...iterator.currentMeasure},gradualChange, gradualSpeed)
			const measureListIndex = iterator.currentMeasure.measureListIndex;
			// 计算相差时间按照比例分配到所有音符上
			if (state.gradualTimes && Object.keys(state.gradualTimes).length > 0) {
				const withInRangeNote = state.gradual.find((item, index) => {
					const nextItem: any = state.gradual[index + 1];
					return (
						item[0].measureIndex <= measureListIndex &&
						item[1]?.measureIndex! >= measureListIndex &&
						(!nextItem || nextItem?.[0].measureIndex !== measureListIndex)
					);
				});
				const [first, last] = withInRangeNote || [];
				if (first && last) {
					// 小节数量
					const continuous = last.measureIndex - first.measureIndex;
					// 开始小节内
					const inTheFirstMeasure = first.closedMeasureIndex == measureListIndex && si >= first.noteInMeasureIndex;
					// 结束小节内
					const inTheLastMeasure = last.closedMeasureIndex === measureListIndex && si < last.noteInMeasureIndex;
					// 范围内小节
					const inFiestOrLastMeasure = first.closedMeasureIndex !== measureListIndex && last.closedMeasureIndex !== measureListIndex;
					if (inTheFirstMeasure || inTheLastMeasure || inFiestOrLastMeasure) {
						const startTime = state.gradualTimes[first.measureIndex];
						const endTime = state.gradualTimes[last.measureIndex];
						if (startTime && endTime) {
							const times = continuous - first.leftDuration / first.allDuration + last.leftDuration / last.allDuration;
							const diff = dayjs(tranTime(endTime)).diff(dayjs(tranTime(startTime)), "millisecond");
							gradualLength = ((NoteRealValue / vRealValue / times) * diff) / 1000;
						}
					}
				}
			} else if (state.appName === "GYM" && gradualChange && gradualSpeed && (gradualChange.startXmlNoteIndex === si || gradualChangeIndex > 0)) {
				const startSpeed = gradualSpeed[0] - (gradualSpeed[1] - gradualSpeed[0]);
				const { resetXmlNoteIndex, endXmlNoteIndex } = gradualChange;
				const noteDiff = endXmlNoteIndex;
				let stepSpeed = (gradualSpeed[gradualSpeed.length - 1] - startSpeed) / noteDiff;
				stepSpeed = note.DotsXml ? stepSpeed / 1.5 : stepSpeed;
				if (gradualChangeIndex < noteDiff) {
					const tempSpeed = Math.ceil(speed + stepSpeed * gradualChangeIndex);
					let tmpSpeed = getTimeByBeatUnit(beatUnit, tempSpeed, iterator.currentMeasure.activeTimeSignature.Denominator);
					const maxLength = (wholeValue + numerator / denominator) * vDenominator * (60 / tmpSpeed);
					// speed += stepSpeeds.reduce((a, b) => a + b, 0)
					speed += Math.ceil(stepSpeed * (gradualChangeIndex + 1));
					tmpSpeed = getTimeByBeatUnit(beatUnit, speed, iterator.currentMeasure.activeTimeSignature.Denominator);
					const minLength = (wholeValue + numerator / denominator) * vDenominator * (60 / tmpSpeed);
					gradualLength = (maxLength + minLength) / 2;
				} else if (resetXmlNoteIndex > gradualChangeIndex) {
					speed = allNotes[i - 1]?.speed;
				}
				beatSpeed =
					(state.isSpecialBookCategory ? getTimeByBeatUnit(beatUnit, speed, iterator.currentMeasure.activeTimeSignature.Denominator) : baseSpeed) || 1;
				const isEnd = !(gradualChangeIndex < noteDiff) && !(resetXmlNoteIndex > gradualChangeIndex);
				gradualChangeIndex++;
				if (isEnd) {
					gradualChangeIndex = 0;
					gradualChange = undefined;
					gradualSpeed = undefined;
					stepSpeeds = [];
				}
			}
			const _noteLength = NoteRealValue;
			// 当前音符的持续时长，当前音符的RealValue值*拍数*（60/后台设置的基准速度）
			let noteLength = gradualLength ? gradualLength : Math.min(vRealValue, NoteRealValue) * formatBeatUnit(beatUnit) * (60 / beatSpeed);
			// 小节时长
			const measureLength = vRealValue * 4 * (60 / beatSpeed);
			// console.table({value: iterator.currentTimeStamp.realValue, vRealValue,NoteRealValue, noteLength,measureLength, MeasureNumberXML: note.sourceMeasure.MeasureNumberXML})
			// console.log(i, Math.min(vRealValue, NoteRealValue),noteLength,gradualLength, formatBeatUnit(beatUnit),beatSpeed, NoteRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed) )
			/**
			 * TODO:摇篮曲-人音-排箫(1788501975122489346)，第12小节音符持续时间特殊处理
			*/
			if (['1788501975122489346','1788502467554750466'].includes(state.cbsExamSongId)) {
				if (i == 13) {
					noteLength = noteLength / 2;
				}
				if (i == 44) {
					noteLength = noteLength * 6;
				}
				if (i == 56) {
					noteLength = noteLength * 4;
				}
			}
			usetime += noteLength;
			relaMeasureLength += noteLength;
			let relaEndtime = noteLength + relativeTime;
			// console.log('relaEndtime',noteLength, relativeTime)
			const fixedKey = note.fixedKey || 0;
			// const svgElement = activeVerticalMeasureList[0]?.vfVoices["1"]?.tickables[si];
			//const svgElement = currenrtVfVoices?.tickables[staveNoteIndex];
			// 过滤掉ghostnote
			const filterTickables = currenrtVfVoices?.tickables?.filter((tickable: any) => tickable.attrs?.type !== "GhostNote")
			const svgElement = filterTickables?.[staveNoteIndex];

			// console.log('si',si,i)
			// console.log(note.sourceMeasure.MeasureNumberXML,note,svgElement, NoteRealValue, measureLength)
			if (allNotes.length && allNotes[allNotes.length - 1].relativeTime === relativeTime) {
				continue;
			}
			// console.log(iterator.currentMeasure)
			// 如果是弱起就补齐缺省的时长，midi音频不需要考虑弱起
			if (i === 0 && !state.isAppPlay) {
				let _firstMeasureRealValue = 0;
				const staffEntries = note.sourceMeasure.verticalMeasureList?.[0]?.staffEntries || [];
				//计算第一个小节里面的音符时值是否等于整个小节的时值
				staffEntries.forEach((_a: any) => {
					if (_a?.sourceStaffEntry?.voiceEntries?.[0]?.notes?.[0]?.length?.realValue) {
						_firstMeasureRealValue += _a.sourceStaffEntry.voiceEntries[0].notes[0].length.realValue;
					}
				});
				if (_firstMeasureRealValue < vRealValue) {
					// console.log(_firstMeasureRealValue, vRealValue)
					// 如果是弱起,将整个小节的时值减去该小节所有音符相加的时值,就是缺省的时值
					difftime = measureLength - _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
				}
				/**
				 * 管乐迷，部分弱起的曲目，mp3制作不标准，没有按照补齐弱起后的时间进行制作，需要单独处理
				 * 2670
				*/
				if (["2670"].includes(state.cbsExamSongId)) {
					// fixtime -= _firstMeasureRealValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
				} else {
					if (difftime > 0 && !state.isEvxml) {
						fixtime += difftime;
						state.fixtime = fixtime;
					}
				}
				// 管乐迷 diff获取不准确时, 弱起补齐
				if (["2589", "2561", "2560", "2559", "2558", "2556", "2555", "2554"].includes(detailId)) {
					// difftime = iterator.currentTimeStamp.realValue * formatBeatUnit(beatUnit) * (60 / beatSpeed);
					// fixtime += difftime;
				}

				// 如果是evxml，fixtime取读取xml的值
				if (state.isEvxml) {
					fixtime = state.evXmlBeginTime ? state.evXmlBeginTime : fixtime
					state.fixtime = fixtime
				}
				console.log('节拍器时间',fixtime,state.evXmlBeginTime)
			}
			let stave = activeVerticalMeasureList[0]?.stave;

			if (note.sourceMeasure.multipleRestMeasures) {
				totalMultipleRestMeasures = note.sourceMeasure.multipleRestMeasures;
				multipleRestMeasures = 0;
			}
			if (multipleRestMeasures < totalMultipleRestMeasures) {
				if (note?.sourceMeasure?.MeasureNumberXML !== preNoteMeasureNumber) {
					multipleRestMeasures++;
				} else {
					multipleRestMeasures = allNotes.length ? allNotes.last().multipleRestMeasures : 0;
				}
			} else {
				if (note?.sourceMeasure?.MeasureNumberXML !== preNoteMeasureNumber) {
					multipleRestMeasures = 0;
					totalMultipleRestMeasures = 0;
				} else {
					multipleRestMeasures = allNotes.length ? allNotes.last().multipleRestMeasures : 0;
				}
			}

			// console.log(note.tie)
			// console.log('👀看看endtime', duration, relaEndtime, fixtime, i)
			// console.log('频率',note?.pitch?.frequency,i)
			/**
			 * evxml的曲子，如果曲谱xml中带有times信息，则音符时值优先取times中的值
			 * 曲子：1795013295024062466（春暖花开），如果音符有times信息，休止符没有times信息，此种规则是认为休止符不参与时值计算的，需要过滤掉该休止符
			 * TODO:需要考虑唱名怎么处理，唱名是xml有多少个音符，就需要唱多少个，不能剔除
			 */
			if (state.isEvxml && note.isRestFlag && note?.noteTimeInfo?.length === 0 && state.xmlHasTimes ) {
				const idx = _notes.findIndex(item=>item.note === note);
				let nextNoteTimes = _notes[idx+1]?.note?.noteTimeInfo?.[0]?.begin*1000 
				let preNoteTImes = _notes[idx-1]?.note?.noteTimeInfo?.[0]?.end*1000
				// 当下一个音符也没有时间的时候，再往下一个找
				if(!nextNoteTimes && nextNoteTimes!==0){
					let nextIndex = idx + 2
					while(!nextNoteTimes && nextIndex<_notes.length){
						nextNoteTimes = _notes[nextIndex]?.note?.noteTimeInfo?.[0]?.begin*1000
						nextIndex ++
					}
					// 当最后音符就是没有打时间的休止小节，可能nextNoteTimes时间找不到，目前没有处理
				}
				if(!preNoteTImes && preNoteTImes!==0){
					let preIndex = idx - 2
					while(!preNoteTImes && preIndex>-1){
						preNoteTImes = _notes[preIndex]?.note?.noteTimeInfo?.[0]?.end*1000
						preIndex --
					}
					// 当没有找到preNoteTImes的时候 赋值为0 (当第一个音符就是没有打时间的休止小节会出现这种情况)
					preNoteTImes || (preNoteTImes = 0)
				}
				const allowRange = Math.abs(nextNoteTimes - preNoteTImes)< 10;
				if (allowRange) {
					note.maxNoteNum = note.maxNoteNum - 1;
					// 唱名时间补齐,当删除这个音符的时候，上个音符的持续时间要加上这个音符的时间
					allNotes[allNotes.length - 1].noteLengthTime += noteLength
					continue;
				}
			}
			let evNoteStartTime = 0, evNoteEndTime = 0;
			if (state.isEvxml && note?.noteTimeInfo?.length ) {
				let idx = noteIds.filter((item: any) => item === svgElement?.attrs.id)?.length || 0;
				// 如果是合并的小节的休止符
				if (note.isRestFlag && !svgElement && note?.NoteToGraphicalNoteObjectId) {
					const customRestId = `rest-${note?.sourceMeasure?.MeasureNumberXML}-${note?.NoteToGraphicalNoteObjectId}`;
					idx = noteIds.filter((item: any) => item === customRestId)?.length || 0;
				}
				evNoteStartTime = note?.noteTimeInfo[idx]?.begin
				evNoteEndTime = note?.noteTimeInfo[idx]?.end
				if (evNoteStartTime) {
					relativeTime = evNoteStartTime - fixtime
					// usetime = evNoteStartTime - fixtime
				}
				// usetime = evNoteStartTime - fixtime
			}
			svgElement?.attrs.id && noteIds.push(svgElement?.attrs.id)
			// 如果是合并的休止小节，是没有渲染音符的，所以没有svgElement对象，也就没有id，此时需要添加自定义的一个id进度，便于多遍循环时，找到对应的noteTimeInfo里面的时间信息
			if (note.isRestFlag && !svgElement && note?.NoteToGraphicalNoteObjectId) {
				noteIds.push(`rest-${note?.sourceMeasure?.MeasureNumberXML}-${note?.NoteToGraphicalNoteObjectId}`)
			}

			// 如果该音符包含倚音，添加标记
			let hasGraceNote = false;
			if (svgElement?.modifiers?.length) {
				hasGraceNote = svgElement?.modifiers.some((item: any) => item?.attrs?.type === "GraceNoteGroup")
			}
			const filterRepeatIdx = allNotes.filter((item: any) => item.noteId === note.NoteToGraphicalNoteObjectId).length
			const nodeDetail = {
				trackIndex: note.trackIndex, // 当前的音符属于第几条分轨
				isStaccato: note.voiceEntry.isStaccato(),
				isRestFlag: note.isRestFlag,
				noteId: note.NoteToGraphicalNoteObjectId,
				measureListIndex: note.sourceMeasure.measureListIndex,
				MeasureNumberXML: note.sourceMeasure.MeasureNumberXML, // 当前的小节数，（从1开始）
				_noteLength: _noteLength,
				svgElement: svgElement,
				frequency: note?.pitch?.frequency || -1,
				nextFrequency: note?.pitch?.nextFrequency || -1,
				prevFrequency: note?.pitch?.prevFrequency || -1,
				difftime,
				octaveOffset: activeVerticalMeasureList[0]?.octaveOffset,
				speed,
				beatSpeed,
				i,
				si,
				stepSpeeds,
				measureOpenIndex: allMeasures.length - 1,
				measures,
				tempoInBPM: note.sourceMeasure.tempoInBPM,
				measureLength,
				relaMeasureLength,
				id: svgElement?.attrs.id,
				hasGraceNote,
				note: note.halfTone + 12, // see issue #224
				fixtime, // 弱起补充的时间
				relativeTime: retain(relativeTime),
				time: state.isEvxml && evNoteStartTime ? retain(evNoteStartTime) : retain(relativeTime + fixtime), // 开始播放的时间
				endtime: state.isEvxml && evNoteEndTime ? retain(evNoteEndTime) : retain(relaEndtime + fixtime), // 播放完成的时间
				relaEndtime: retain(relaEndtime),
				realValue,
				halfTone: note.halfTone,
				noteElement: note,
				fixedKey,
				realKey: 0,
				duration: 0,
				formatLyricsEntries: formatLyricsEntries(note),
				stave,
				firstVerticalMeasure: activeVerticalMeasureList[0],
				noteLength: 1,
				osdmContext: osmd,
				speedbeatUnit: beatUnit,
				multipleRestMeasures: multipleRestMeasures, // 当前合并小节的索引，从1开始到当前的totalMultipleRestMeasures结束，
				totalMultipleRestMeasures, // 当前小节总的合并小节数
				measureSpeed,  // 小节速度
				maxNoteNum: note.maxNoteNum, // 当前小节音符最多的分轨的音符数量
				// repeatIdx: iterator.repeatIdx || 0, // 标记是第几遍循环，从0开始
				repeatIdx: filterRepeatIdx,
				noteLengthTime: noteLength, //当前音符时长
				xmlNoteTime: 0, // xml上音符开始时间 唱名用
				xmlNoteEndTime: 0, //xml上音符结束时间 唱名用
				xmlMp3BeatFixTime,  //xml上节拍器的时间
				notBeatFixtime: state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime, // 不含节拍器的fixtime值 唱名用
				notBeatTime: state.isEvxml && evNoteStartTime ? retain(evNoteStartTime) : retain(relativeTime + (state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime)), // 不含节拍器的 音符开始时间
				notBeatEndTime: state.isEvxml && evNoteEndTime ? retain(evNoteEndTime) : retain(relaEndtime + (state.isOpenMetronome ? fixtime - xmlMp3BeatFixTime : fixtime)) // 不含节拍器的 音符结束时间
			};
			// console.log(i,'当前的小节',nodeDetail.MeasureNumberXML,totalMultipleRestMeasures,multipleRestMeasures)
			// 如果是妙极客的曲子，并且第二遍循环播放需要等待时间，并且是第二遍循环的第一个小节的第一个音符
			// if (state.isEvxml && state.secondEvXmlBeginTime && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === 1 && nodeDetail.noteId === 0) {
			// 	nodeDetail.time = nodeDetail.time + state.secondEvXmlBeginTime;
			// 	nodeDetail.endtime = nodeDetail.endtime + state.secondEvXmlBeginTime;
			// 	usetime = usetime + state.secondEvXmlBeginTime;
			// 	relativeTime = relativeTime + state.secondEvXmlBeginTime;
			// }
			// if (state.isEvxml && nodeDetail.repeatIdx && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === 1 && nodeDetail.noteId === 0) {
			const firstRepeatNodeId = allNotes.find((item: any) => item.MeasureNumberXML === state.timegapRepeatMeasureIndex)?.noteId || 0;
			if (state.isEvxml && nodeDetail.repeatIdx && nodeDetail.i > 0 && nodeDetail.MeasureNumberXML === state.timegapRepeatMeasureIndex && nodeDetail.noteId === firstRepeatNodeId) {
				const currentWaitTime = state.evXmlBeginArr[nodeDetail.repeatIdx] || 0;
				nodeDetail.time = nodeDetail.time + currentWaitTime;
				nodeDetail.endtime = nodeDetail.endtime + currentWaitTime;
				usetime = usetime + currentWaitTime;
				relativeTime = relativeTime + currentWaitTime;
			}		
			nodeDetail.realKey = formatRealKey(note.halfTone - fixedKey * 12, nodeDetail);
			nodeDetail.duration = nodeDetail.endtime - nodeDetail.time;
			let tickables = currenrtVfVoices?.tickables || [];
			if ([121].includes(state.subjectId)) {
				tickables = note.sourceMeasure.verticalSourceStaffEntryContainers;
			}
			// console.log(note.sourceMeasure.MeasureNumberXML, note.sourceMeasure.verticalSourceStaffEntryContainers.length)
			// console.log('👀看看endtime', nodeDetail.duration, relaEndtime, fixtime, i)
			// console.log('音符时间',nodeDetail.i,nodeDetail.time,nodeDetail.endtime)
			tickables = tickables.filter((tickable: any) => tickable.attrs?.type !== "GhostNote")
			let maxNum = (state.isCombineRender && note.maxNoteNum) ? note.maxNoteNum : tickables.length;
			// 妙极客的曲子，一个休止小节内可能有多个休止符，此时maxNum是0，需要针对这种情况作处理
			if (note.isRestFlag && maxNum === 0) {
				maxNum = note.maxNoteNum;
			}
			nodeDetail.noteLength = maxNum || 1;
			allNotes.push(nodeDetail);
			allNoteId.push(nodeDetail.id);

			if ( measures.some((item: any) => item.MeasureNumberXML !== nodeDetail.MeasureNumberXML) ) {
				measures = [];
				measures.push(nodeDetail);
				nodeDetail.measures = measures;
			} else {
				measures.push(nodeDetail);
			}
			/**
			 * bug: #9877
			 * 多分轨合并展示的曲子，不同分轨，同一小节音符的数量可能不能，不能只通过tickables的长度判断该小节的音符数量
			 */
			if (si < maxNum - 1) {
				si++;
			} else {
				si = 0;
				relaMeasureLength = 0;
				measures = [];
			}
			preNoteEndTime = nodeDetail.endtime;
		}
		preNoteMeasureNumber = note?.sourceMeasure?.MeasureNumberXML;
		i++;
	}
	// 按照时间轴排序
	const sortArray = allNotes.sort((a, b) => a.relativeTime - b.relativeTime).map((item, index) => Object.assign(item,{i:index}));
	// const sortArray = allNotes.sort((a, b) => a.time - b.time).map((item, index) => ({ ...item, i: index }));
	// const sortArray = allNotes.map((item, index) => ({ ...item, i: index }));
	// 给 xmlNoteTime 和 xmlNoteEndTime 赋值
	let xmlNoteTime = 0
	sortArray.map(item => {
		const noteLengthTime = item.noteLengthTime
		item.xmlNoteTime = retain(xmlNoteTime)
		item.xmlNoteEndTime = retain(xmlNoteTime + noteLengthTime)
		xmlNoteTime += noteLengthTime
	})
	console.timeEnd("音符跑完时间");
	try {
		osmd.cursor.reset();
	} catch (error) {}
	return sortArray;
};

/** 获取小节之间的连音线，仅同音高*/
export const getNoteByMeasuresSlursStart = (note: any) => {
	let activeNote = note;
	let tieNote;
	if (note.noteElement.tie && note.noteElement.tie.StartNote) {
		tieNote = note.noteElement.tie.StartNote;
	}
	if (activeNote && tieNote && tieNote !== activeNote.noteElement) {
		const arr: any = []
		for (const note of state.times) {
			if (tieNote === note.noteElement) {
				arr.push(note)
			}
		}
		if (arr.length) {
			return arr.find((n: any) => n.i === (note.i - 1)) || arr[0]
		}
	}
	return activeNote;
};

// 解析xml，获取作词、作曲家名称
const getComposer = (xmlParse: any) => {
	const creators: any = Array.from(xmlParse.querySelectorAll('creator'));
	for (const creator of creators) {
		if (creator && creator.getAttribute('type') === 'composer' && !state.musicComposer) {
			state.musicComposer = creator.textContent?.trim() || '';
		}
		if (creator && creator.getAttribute('type') === 'lyricist' && !state.musicLyricist) {
			state.musicLyricist = creator.textContent?.trim() || '';
		}
	}
}

// 通过xml信息获取重播的小节信息
const parseXmlToRepeat = (repeats: any) => {
	if (!repeats.length) return
	let repeatInfo: any = []
	// 重复开始小节，结束小节
	let start = 0, end = 0
	for (let i = 0; i < repeats.length; i++) {
		const element = repeats[i];
		const direction = element.getAttribute('direction')
		let parentElement = element.parentNode
		while (parentElement && parentElement.tagName !== 'measure') {
			parentElement = parentElement.parentNode
		}
		let notesNumber = parentElement.getAttribute('number') // 第多少小节，从1开始
		notesNumber = notesNumber ? Number(notesNumber) : 0
		if (direction === 'forward') {
			start = notesNumber
		} else if (direction === 'backward') {
			end = notesNumber
			repeatInfo.push({
				start,
				end
			})
		}
	}
	state.repeatInfo = repeatInfo
	// console.log('重播',repeatInfo)
}

// 校验当前选段是否满足重播条件
export const verifyCanRepeat = (startNum: number, endNum: number) => {
	let repeatIdx = -1
	if (state.repeatInfo.length) {
		for (let i = state.repeatInfo.length - 1; i >= 0; i--) {
			const { start, end } = state.repeatInfo[i];
			if (startNum <= start && endNum >= end) {
				repeatIdx = i
				return {
					repeatIdx,
					canRepeat: true
				}
				break;
			}
		}
		return {
			repeatIdx,
			canRepeat: false
		}
	} else {
		return {
			repeatIdx,
			canRepeat: false
		}
	}
}

// 处理妙极客xml谱面
const customizationXml = (xmlParse: any) => {
	const credits: any = Array.from(xmlParse.querySelectorAll('credit'));
	const creators: any = Array.from(xmlParse.querySelectorAll('creator'));
	const graces: any = Array.from(xmlParse.querySelectorAll('grace'));
	const measures: any[] = Array.from(xmlParse.getElementsByTagName("measure"));
	const notes: any[] = Array.from(xmlParse.getElementsByTagName("note"));

	// 获取音符最多的歌词数，time最多的次数，取两者的最大值，用于自定义循环播放次数
	let maxLyricNum = 0, maxTimeNum = 0;
	if (notes && notes.length) {
		for (const note of notes) {
			if (maxLyricNum < note.getElementsByTagName("lyric").length) {
				maxLyricNum = note.getElementsByTagName("lyric").length
			}
			if (maxTimeNum < note.getElementsByTagName("time").length) {
				maxTimeNum = note.getElementsByTagName("time").length
			}
		}
	}
	state.maxLyricNum = Math.max(maxLyricNum, maxTimeNum);
	// state.osmd.EngravingRules.DYCustomRepeatCount = maxLyricNum;
	;(window as any).DYCustomRepeatCount = state.maxLyricNum;
	console.log('歌词次数',maxLyricNum)

	if (credits && credits.length) {
		for (const credit of credits) {
			if (credit.getElementsByTagName("credit-type")?.[0]?.textContent === 'lyricist') {
				const creditWord = credit.getElementsByTagName("credit-words")
				creditWord?.[0].setAttribute('justify', 'right')
			}
		}
	}
	if (creators && creators.length) {
		for (const creator of creators) {
			if (creator.getAttribute('type') === 'lyricist') {
				// creator.textContent = '测试一下1';
			}
			
		}
	}
	// 妙极客xml的倚音(grace)标签需要加上slash=yes属性
	if (graces && graces.length) {
		for (const grace of graces) {
			grace?.setAttribute('slash','yes');
			// console.log(grace,'倚音')
		}
	}
	// 妙极客xml部分小节没有音符，只有Segno，该小节不需要渲染，表示的是反复标记
	for (const measure of measures) {
		const hasNote = measure.getElementsByTagName("note").length;
		const hasSegno = measure.getElementsByTagName("segno").length;
		const sounds = Array.from(measure.getElementsByTagName("sound"));
		const hasSoundSegno = sounds.some((item: any) => item.getAttribute('segno') === 'segno' );
		if (!hasNote && hasSegno && hasSoundSegno) {
			const parent = measure.parentNode;
			parent.removeChild(measure);
		}
	}

	/**
	 * bug: #10289，曲目：1782672015612725196、1788040971888537602
	 * 妙极客xml，多遍歌词循环的曲目，如果没有repeat标签，需要加上repeat标签
	 * */
	if (maxLyricNum > 1) {
		const hasRepeat = xmlParse.querySelectorAll('repeat').length > 0;
		if (!hasRepeat) {
			const parts = xmlParse.querySelectorAll('score-partwise>part')
			if (parts.length) {
				for (const part of parts) {
					const currentMeasures = part.querySelectorAll('measure').length ? Array.from(part.querySelectorAll('measure')) : [];
					const lastMeasure: any = currentMeasures.last();
					if (lastMeasure?.getElementsByTagName('barline').length) {
						const barlineDom = lastMeasure?.getElementsByTagName('barline')[0]
						barlineDom.innerHTML = barlineDom.innerHTML + `<repeat direction="backward" />`;
					} else {
						lastMeasure.innerHTML = lastMeasure.innerHTML + `
						<barline location="right">
							<bar-style>light-heavy</bar-style>
							<repeat direction="backward" />
						</barline>`
					}
					// console.log(lastMeasure)
				}
			}
		}
	}
}

// 计算evxml的起始播放时间
const analyzeEvxml = (xmlParse: any, xmlUrl?: string) => {
	// xml拍号数
	const xmlNum = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[0]?.getAttribute('num');
	const denNum = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[0]?.getAttribute('den');
	const xmlNum2 = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[1]?.getAttribute('num');
	const denNum2 = xmlParse.getElementsByTagName("timegap")[0]?.getElementsByTagName("values")[0]?.getElementsByTagName("item")[1]?.getAttribute('den');
	const timeGaps: any = xmlParse.getElementsByTagName("timegap")?.length ? Array.from(xmlParse.getElementsByTagName("timegap")?.[0]?.getElementsByTagName("values")?.[0]?.getElementsByTagName("item")) : [];
	state.xmlHasTimes = !!xmlParse.getElementsByTagName("times")?.length
	// 第一个音符的起始时间
	const firstMeasure = xmlParse.getElementsByTagName("measure")[0];
	if (firstMeasure) {
		const firstNoteBeginTime = firstMeasure.getElementsByTagName("times")[0]?.getElementsByTagName("time")[0]?.getAttribute('begin');
		state.evXmlBeginTime = firstNoteBeginTime ? firstNoteBeginTime / 1000 : xmlNum ? 60 / state.originSpeed * xmlNum * 4/denNum : 0;
		state.secondEvXmlBeginTime = firstNoteBeginTime ? 0 : xmlNum2 ? 60 / state.originSpeed * xmlNum2 * 4/denNum2 : 0;
		const hasTimeGap = state.xmlHasTimeGap = xmlParse.getElementsByTagName("timegap").length > 0;
		const hasTimes = xmlParse.getElementsByTagName("times").length > 0;
		if (timeGaps && timeGaps.length && !firstNoteBeginTime) {
			// 有timegap的曲子，需要找到是从哪一小节开始循环的，默认是从第一节开始循环
			const startRepeat = Array.from(xmlParse.getElementsByTagName("repeat") || []).filter((item: any) => item?.getAttribute('direction') === 'forward')
			const firstRepeat: any = startRepeat?.length ? startRepeat[0] : null;
			if (firstRepeat) {
				let parentElement = firstRepeat?.parentNode
				while (parentElement && parentElement.tagName !== 'measure') {
					parentElement = parentElement.parentNode
				}
				state.timegapRepeatMeasureIndex = parentElement?.getAttribute('number') ? Number(parentElement?.getAttribute('number')) : 1;
			}
			for (const timeGap of timeGaps) {
				const num: any = timeGap?.getAttribute('num'), den: any = timeGap?.getAttribute('den');
				const startTime = num ? 60 / state.originSpeed * num * 4/den : 0;
				state.evXmlBeginArr.push(startTime)
			}
		}

		console.log('🚀 ~ evxml解析','有timegap:',hasTimeGap,'有times:',hasTimes,'timegap集合',state.evXmlBeginArr,'第一个timegap',state.evXmlBeginTime)
	}

	// if (!hasTimeGap && !hasTimes) {
	// 	state.noTimes.push(xmlUrl)
	// }
	
}

/**
 * 兼容处理xml声部移调
 * 打谱软件可能会自动处理移调，这类型的xml就不用通过程序移调了
 * 没有通过软件处理的移调xml，才需要通过程序处理
 * 判读规则：只处理独奏的，不处理合奏的，
 * <instrument-name></instrument-name>标签的值为：Tenor Recorder（竖笛）、Panpipes（排箫）、Ocarina（陶笛）、Woodwind（葫芦丝）、空的和solo，需要程序处理移调
 */
export const compatibleXmlPitchVoice = (xmlParse: any) => {
	const partNames = Array.from(xmlParse.getElementsByTagName('part-name'));
	const partListNames = partNames.filter((item: any) => item?.textContent?.trim().toLocaleUpperCase() !== "COMMON");
	if (partListNames.length == 1) {
		const instrumentNames = Array.from(xmlParse.getElementsByTagName('instrument-name')) || [];
		// @ts-ignore
		const instrumentName = instrumentNames[0]?.textContent?.trim()?.toLocaleLowerCase() || ''
		// console.log('instrument名称',instrumentName)
		// 是否需要程序处理移调
		let xmlNeedAdjustVoice = false;
		switch (state.musicalCodeId) {
			case 37:
			case 38:
				xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('tenor recorder') ? true : false
				break;
			case 33:
				xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('panpipes') ? true : false
				break;
			case 34:
				xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('ocarina') ? true : false
				break;
			case 35:
				xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('woodwind') ? true : false
				break;		
			case 39:
				xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') || instrumentName.includes('whistling') ? true : false
				break;						
			default:
				xmlNeedAdjustVoice = !instrumentName || instrumentName.includes('solo') ? true : false
				break;
		}
		(window as any).xmlNeedAdjustVoice = xmlNeedAdjustVoice
	}
}