import { computed, defineComponent, onBeforeMount, onMounted } 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();
      const info = res?.data || {};
      setUserInfo(info);
      // console.log("🚀 ~ res:", res);
    };
    onBeforeMount(() => {
      if (query.Authorization) {
        setToken(query.Authorization);
      }
      setUser();
      sessionStorage.setItem("SCRIPT_ERROR", "0");
    });

    onMounted(() => {
      // 禁用右键菜单
      document.addEventListener("contextmenu", function (event) {
        event.preventDefault();
      });
      // 禁用浏览器快捷键
      document.addEventListener("keydown", function (event) {
        // 屏蔽 F12 和 Ctrl+Shift+I
        if (event.key === "F12" || (event.ctrlKey && event.shiftKey && event.key === "I") || (event.metaKey && event.altKey && event.key === "I")) {
          event.preventDefault();
        }
      });
    });

    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>
    );
  },
});
