import { computed, defineComponent, onMounted, reactive, ref } from "vue";
import { formatXML, onlyVisible } from "../../helpers/formateMusic";
// // @ts-ignore
import { OpenSheetMusicDisplay } from "/osmd-extended/src";
import state, { EnumMusicRenderType } from "/src/state";
import Selection from "../selection";
import styles from "./index.module.less";
import queryString from "query-string";
import { getGradualLengthByXml } from "/src/helpers/calcSpeed";
import { resetFormate, resetGivenFormate, setGlobalMusicSheet } from "/src/helpers/customMusicScore"
import { setGlobalData } from "/src/utils";

export const musicRenderTypeKey = "musicRenderType";
let osmd: any = null;
const musicData = reactive({
	showSelection: false, // 可以加载点击浮层
	isRenderLoading: true,
	score: "",
	containerWidth: 0,
});

/** 重新渲染曲谱 */
export const resetRenderMusicScore = (type?: string) => {
	const search = queryString.parse(location.search);
	const newSearch = queryString.stringify({
		...search,
		_t: Date.now(),
		musicRenderType: type
	});
	location.search = "?" + newSearch;
};

let wordList: never[] = [], deleteWordList: never[] = [];

export default defineComponent({
	name: "music-score",
	emits: ["rendered"],
	props: {
		/** 是否渲染选择框 */
		showSelection: {
			type: Boolean,
			default: true,
		},
		renderTypeKey: {
			type: String,
			default: "",
		},
		musicColor: {
			type: String,
			default: "",
		},
		/** 是否渲染声轨名称 */
		showPartNames: {
			type: Boolean,
			default: false,
		},
	},
	setup(props, { emit }) {
        // 解析报错的xml
        const errorList: any = [];
        const checkRender = async (list?: any) => {
            let errorNum = 0;
            for (let i = 0; i < list.length; i++) {
                const item = list[i];
                try {
                    await getXML(item.evxml_file_url);
                    // await init(i);
                } catch (error) {
                    errorNum += 1;
                    errorList.push(item.evxml_file_url);
                    console.log('🚀 ~ evxml解析报错:',`第${i}个xml`,error,'总错误数:',errorNum)
                }
            }
            // console.log('🚀 ~ evxml循环完成','没有times和timegap的:',state.noTimes,'解析报错的xml:',errorList)
			console.log('关键词',wordList, deleteWordList)
        }
		/** 设置 曲谱模式,五线谱还是简谱 */
		const setRenderType = () => {
			const musicRenderType: any = sessionStorage.getItem(props.renderTypeKey || musicRenderTypeKey);
			if (musicRenderType in EnumMusicRenderType) {
				state.musicRenderType = musicRenderType;
			}
		};
		const getXML = async (evxml: any) => {
			const res = await fetch(evxml).then((response) => response?.text());
            if (res) {
                const xml = formatXML(res, evxml, wordList, deleteWordList);
                musicData.score = state.isCombineRender ? xml : onlyVisible(xml, state.partIndex);
                if (state.gradualTimes) {
                    state.gradual = getGradualLengthByXml(xml);
                }
            }
		};

		const init = async (idx: any) => {
			const container = document.getElementById("testCheck");
			if (!container || !musicData.score) return;
			setGlobalMusicSheet();
			osmd = new OpenSheetMusicDisplay(container, {
				drawTitle: false,
				drawSubtitle: false,
				// drawMeasureNumbers: false,
				autoResize: false,
				followCursor: false,
				drawPartNames: props.showPartNames, // 是否渲染声轨名称
				drawComposer: false, // 渲染作者
				defaultColorMusic: props.musicColor, // 颜色
				renderSingleHorizontalStaffline: state.isSingleLine ? true : false,
				autoGenerateMultipleRestMeasuresFromRestMeasures: state.isSingleLine ? false : true, // 连续休止小节是否合并显示
				// darkMode: true, // 暗黑模式
				// pageFormat: 'A4_P',
				// autoBeam: true,
				// drawMetronomeMarks: false,
				// drawLyricist: false,
				// ...this.opotions,
				
			});
			// osmd.EngravingRules.CompactMode = true // 紧凑模式
			osmd.EngravingRules.PageRightMargin = state.isSingleLine ? (window.innerWidth+200)/10 : 2;
			osmd.EngravingRules.FixedMeasureWidth = state.isSingleLine ? true : false; // 是否固定小节的宽度（小节同一宽度渲染）
			osmd.EngravingRules.PageTopMargin = 10;
			osmd.EngravingRules.PageTopMarginNarrow = 3;
			osmd.EngravingRules.PageLeftMargin = 2;
			osmd.EngravingRules.PageBottomMargin = 2;
			osmd.EngravingRules.DYMusicScoreType = "staff";
			osmd.EngravingRules.DYMusicScoreId = state.examSongId || ''
			await osmd.load(musicData.score);
			osmd.zoom = state.zoom;
			osmd.render();
			console.log("🚀 ~ evxml渲染完:", `第${idx}个xml`)
            container.innerHTML = "";
			
		};
		/** 获取渲染容器的宽度 */
		const getContainerWidth = () => {
			musicData.containerWidth = 625;
			// console.log(musicData.containerWidth)
		};
		onMounted(async () => {
			getContainerWidth();
            state.isEvxml = true
            // checkRender(xmlList2);
		});
		return () => (
			<div
				id="testCheck"
			>
			</div>
		);
	},
});
