import { defineComponent, nextTick, onMounted, reactive } from "vue";
import state, { EnumMusicRenderType } from "/src/state";
import MusicScore from "../music-score";
import styles from "./index.module.less";
import { getQuery } from "/src/utils/queryString";
import { closeToast, showLoadingToast } from "vant";
import { svg2canvas } from "/src/utils/svg2canvas";
import { moveGracePosition } from "/src/helpers/customMusicScore"

export default defineComponent({
	name: "transfer-to-img",
	setup() {
		const query: any = getQuery();
		const productRenderType = "productRenderType"
		const detailData = reactive({
			isLoading: true,
			isProductLoading: false,
			step: 0,
			product: [
				{
					state: false,
					name: "五线谱",
					type: EnumMusicRenderType.staff,
					base64: "" as any,
				},
				{
					state: false,
					name: "首调",
					type: EnumMusicRenderType.firstTone,
					base64: "" as any,
				},
				{
					state: false,
					name: "固定调",
					type: EnumMusicRenderType.fixedTone,
					base64: "" as any,
				},
			],
			isSpecialXml: false, // TODO：是否是摇篮曲（节奏练习）的曲子
		});

		onMounted(() => {
			(window as any).appName = "colexiu";
			state.isSingleLine = false;
			state.isCreateImg = true;
			state.isEvxml = true;
			state.xmlUrl = decodeURIComponent(query.xmlUrl);
			const specialXmls = ['https://oss.dayaedu.com/MECMP/1715332965751.xml','https://oss.dayaedu.com/MECMP/1715326622946.xml'];
			if (specialXmls.includes(state.xmlUrl)) {
				detailData.isSpecialXml = true;
			}
			//课堂乐器,默认简谱
			sessionStorage.setItem(productRenderType, detailData.product[detailData.step].type);
			state.musicRenderType = detailData.product[detailData.step].type
			showLoadingToast({ message: "生成中", duration: 0 });
			setTimeout(() => {
				detailData.isLoading = false;
			}, 500);
		});

		/** 渲染完成 */
		const handleRendered = async () => {
			if (document.getElementById('scrollContainer')) {
				moveGracePosition(detailData.isSpecialXml);
			}
			detailData.product[detailData.step].state = true;
			detailData.product[detailData.step].base64 = await downPng();

			try {
				console.log(JSON.parse(JSON.stringify(detailData.product)), detailData.step);
			} catch (error) {}

			detailData.step += 1;

			if (detailData.step !== detailData.product.length) {
				//课堂乐器,默认简谱
				sessionStorage.setItem(productRenderType, detailData.product[detailData.step].type);
				state.musicRenderType = detailData.product[detailData.step].type
				nextTick(() => {
					detailData.isLoading = true;
					setTimeout(() => {
						detailData.isLoading = false;
					}, 500);
				});
				return;
			}

			closeToast();
			console.log(detailData.product,123456);
			window.parent?.postMessage(
				{
					api: "webApi_renderSvg",
					product: JSON.stringify(detailData.product),
				},
				"*"
			);
		};
		const downPng = () => {
			return new Promise((resolve) => {
				setTimeout(async () => {
					try {
						const svg: any = document.getElementById("osmdSvgPage1")?.cloneNode(true);
						if (!svg) {
							resolve("");
							return;
						}
						const cw = svg.width.animVal.value;
						const ch = svg.height.animVal.value;
						const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
						rect.setAttribute("x", "0");
						rect.setAttribute("y", "0");
						rect.setAttribute("width", `${cw * 2}`);
						rect.setAttribute("height", `${ch * 2}`);
						rect.setAttribute("fill", "#fff");
						svg.prepend(rect);
						const _canvas = svg2canvas(svg.outerHTML);
						const base64 = _canvas.toDataURL("image/png", 1);
						resolve(base64);
					} catch (error) {
						resolve("");
					}
				}, 500);
			});
		};

		return () => (
			<div class={styles.detail}>
				<div id="scrollContainer" class={[styles.container, "hideCursor"]}>
					{/* 曲谱渲染 */}
					{!detailData.isLoading && <MusicScore renderTypeKey={productRenderType} showSelection={false} onRendered={handleRendered} />}
				</div>
			</div>
		);
	},
});
