import { computed, defineComponent, onBeforeMount, onMounted, onUnmounted } 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";
import state from "/src/state"

export default defineComponent({
  name: "App",
  setup() {
    const query: any = getQuery();
    /** 获取用户信息 */
    const getUserInfo = async () => {
      return await studentQueryUserInfo();
    };
    const setUser = async () => {
      try {
        const res = query.isCbs || window.location.href.includes("simple-detail") ? { code: 200, data: {} } : await getUserInfo();
        if (res?.code === 403) {
          const browserInfo = browser();
          showToast(res.msg);
          if (browserInfo.isApp) {
            postMessage({ api: "login" });
          } else {
            if (/(192|localhost)/.test(location.origin)) {
              return;
            }
            // 判断是否在应用中
            window.parent.postMessage(
              {
                api: "onLogin",
              },
              "*"
            );
            setTimeout(() => {
              window.location.href = `${location.origin}/classroom`;
            }, 500);
          }
          return;
        }
        const student = res?.data || {};
        setUserInfo(student);
        state.vipType = res.data.vipType || ''
        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 (window.location.href.includes("simple-detail")) {
        //
      } else {
        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());
    });

    // 老师端云练习，上下键切资源
    const onKeyBoard = (e: KeyboardEvent) => {
      if (e.code === "ArrowUp") {
        window.parent.postMessage(
          {
            api: "documentBodyKeyup",
            code: "ArrowUp",
          },
          "*"
        );
      } else if (e.code === "ArrowDown") {
        window.parent.postMessage(
          {
            api: "documentBodyKeyup",
            code: "ArrowDown",
          },
          "*"
        );
      }
    };
    onMounted(() => {
      const _loading = document.getElementById("loading");
      _loading && document.body.removeChild(_loading);
      // console.log(query);
      if (query.platform == "pc" || query.isPreView) {
        document.body.addEventListener("keyup", (e: KeyboardEvent) => onKeyBoard(e));
        // 禁用右键菜单
        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();
          }
        });
      }

      // // 禁用右键菜单
      // 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();
      //   }
      // });
    });

    onUnmounted(() => {
      if (query.platform == "pc") document.body.removeEventListener("keyup", onKeyBoard);
    });

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