import { computed, defineComponent, onBeforeMount, onMounted } from "vue";
import { RouterView } from "vue-router";
import TheError from "../components/The-error";
import { setUserInfo, storeData } from "../store";
import { browser, getRandomKey, getToken, setBehaviorId, setToken } from "../utils";
import { getQuery } from "../utils/queryString";
import { studentQueryUserInfo } from "./api";
import { api_cloudLoading, api_getToken } from "../helpers/communication";
import { showToast } from "vant";

export default defineComponent({
	name: "App",
	setup() {
		const query: any = getQuery();
		/** 获取用户信息 */
		const getUserInfo = async () => {
			return await studentQueryUserInfo();
		};
		const setUser = async () => {
			try {
				const res = await getUserInfo();
				if (res?.code === 5000) {
					const browserInfo = browser();
					showToast(res.message);
					if (browserInfo.isApp) {
						postMessage({ api: "login" });
					} else {
						window.location.href = `${
							/(192|localhost)/.test(location.origin) ? "https://test.lexiaoya.cn" : location.origin
						}/classroom`;
					}
					return;
				}
				const student = res?.data || {};
				setUserInfo(student);
				storeData.platformType = student.clientType === 'STUDENT' ? 'STUDENT' : ''
			} catch (error) {
				storeData.status = "error";
				api_cloudLoading();
				console.log("🚀 ~ error:", error);
			}
		};
		onBeforeMount(async () => {
			if (query.Authorization) {
				setToken(query.Authorization);
			}
			if (!getToken()) {
				const res = await api_getToken();
				if (res?.content) {
					const content = res.content;
					const token = content.tokenType + " " + content.accessToken;
					setToken(token);
				}
			}
			if (query.productXmlImg) {
				storeData.status = "login";
				return;
			}
			setUser();
			setBehaviorId(getRandomKey());
		});
		onMounted(() => {
			const _loading = document.getElementById("loading");
			_loading && document.body.removeChild(_loading);
		});

		const inited = computed(() => {
			return storeData.status === "login";
		});
		return () => (
			<>{storeData.status === "error" ? <TheError /> : inited.value ? <RouterView /> : null}</>
		);
	},
});
