import { Snackbar } from "@varlet/ui";
import { defineComponent, onMounted, ref } from "vue";
import styles from "./index.module.less";
import { api_shareAchievements } from "/src/helpers/communication";
import state from "/src/state";
import { storeData } from "/src/store";
import { evaluatingData } from "/src/view/evaluating";
import qs from 'query-string'

export default defineComponent({
	name: "evaluat-share",
	emits: ["close"],
	setup(props, { emit }) {
		const src = ref("");
		const shareLoadedPngData = ref("");
		const shareDisabeled = ref(true);
		const getShareUrl = () => {
			const data: any = {
				name: storeData.user?.username || "",
				subjectName: (storeData.user?.subjectNames || "").split(",")[0] || "",
				avatar: encodeURIComponent(storeData.user?.avatar || ""),
				score: evaluatingData.resultData?.score || 0,
				examSongName: state.examSongName || "",
			};
			if (!state.isPercussion) {
				data.intonation = evaluatingData.resultData?.intonation;
				data.cadence = evaluatingData.resultData?.cadence;
				data.integrity = evaluatingData.resultData?.integrity;
			}
			// src.value = `${location.origin}/accompany/share-evaluating/index.html?${qs.stringify(data)}`;
			src.value = `${location.origin}/share-colexiu-evaluating/index.html?${qs.stringify(data)}`;
		};
		const shareLoaded = (evt: Event) => {
			const el = evt.target as HTMLIFrameElement;
			if (el) {
				// @ts-ignore
				el.contentWindow.setPng = (data: string) => {
					shareLoadedPngData.value = data;
                    shareDisabeled.value = false
				};
			}
		};
		const shareNext = async () => {
			const res = await api_shareAchievements({
				title: "分享我的乐器练习进度，一起见证我的成长！",
				desc: "晒一下我的评测分数，快来“小酷AI”上和我PK一下吧！",
				image: shareLoadedPngData.value,
				video: "",
				type: "image",
				button: ['copy'],
            	url: getShareUrl(),
			});
			if (!res?.content?.status && res?.content?.message) {
                Snackbar(res?.content?.message);
			}
            emit("close");
		};
		onMounted(() => {
			getShareUrl();
		});
		return () => (
			<div>
				<div class={styles.btns}>
					<div class={styles.sbtn} onClick={() => emit("close")}>
						取消
					</div>
					<div class={[styles.sbtn, shareDisabeled.value && styles.disabled]} onClick={shareNext}>
						继续
					</div>
				</div>
				<iframe class={styles.iframe} src={src.value} onLoad={shareLoaded} />
			</div>
		);
	},
});
