import { computed, defineComponent, onBeforeMount } from "vue";
import { RouterView, useRoute } from "vue-router";
import TheError from "../components/The-error";
import { setUserInfo, storeData } from "../store";
import { getQuery } from "../utils/queryString";
import { studentQueryUserInfo, teacherQueryUserInfo } from "./api";
import {
	GlobalThemeOverrides,
	NConfigProvider,
	NDialogProvider,
	NMessageProvider,
	NNotificationProvider,
	darkTheme,
} from "naive-ui";
import { browser, lighten, setToken } from "../utils";
import { showToast } from "vant";

export default defineComponent({
	name: "App",
	setup() {
		const appTheme = "#198CFE";
		const lightenStr = lighten(appTheme, 6);
		const themeOverrides: GlobalThemeOverrides = {
			common: {
				primaryColor: appTheme,
				primaryColorHover: lightenStr,
				primaryColorPressed: lightenStr,
			},
			LoadingBar: {
				colorLoading: appTheme,
			},
		};
		const query: any = getQuery();
		/** 获取用户信息 */
		const getUserInfo = async () => {
			if (storeData.platformType === "TEACHER") {
				return await teacherQueryUserInfo();
			}
			return await studentQueryUserInfo();
		};
		const setUser = async () => {
			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 info = res?.data || {};
			setUserInfo(info);
			// console.log("🚀 ~ res:", res);
		};
		onBeforeMount(() => {
			if (query.Authorization) {
				setToken(query.Authorization);
			}
			setUser();
		});

		const inited = computed(() => {
			return storeData.status === "login" || query.dev;
		});
		return () => (
			<NConfigProvider inlineThemeDisabled themeOverrides={themeOverrides} abstract>
				<NDialogProvider>
					<NNotificationProvider>
						<NMessageProvider max={1} theme={darkTheme.Message}>
							{storeData.status === "error" ? <TheError /> : inited.value ? <RouterView /> : null}
						</NMessageProvider>
					</NNotificationProvider>
				</NDialogProvider>
			</NConfigProvider>
		);
	},
});
