<template>
  <div class="fit">
    <q-ajax-bar position="top" color="accent" size="5px" skip-hijack />
    <q-menu context-menu />
    <router-view />
  </div>
</template>
<script lang="ts">
import { SessionStorage, Cookies, useQuasar, setCssVar } from "quasar";
import { defineComponent } from "vue";
import { useI18n } from "vue-i18n";
import EventBus, { EventNamesDefine } from "src/common/EventBus";
import { IWuJieInterface, useStore } from "src/store";
import GlobalData from "./common/GlobalData";
import { EProductNames } from "./entities/ProductNames";
import { api } from "./boot/axios";
import { WuJieInitializer } from "./common/WuJieInitializer";

export default defineComponent({
  name: "App",

  setup() {
    const $t = useI18n();
    const $store = useStore();
    const $q = useQuasar();

    if ((window as any).$wujie) {
      const $wujie = (window as any).$wujie as IWuJieInterface;
      $store.commit("setWuJie", $wujie);
      WuJieInitializer.initialize($wujie, $store, $q, $t);
    }

    document.title = $t.t("title");

    if (!navigator.cookieEnabled) {
      $q.dialog({
        title: $t.t("error"),
        html: true,
        message: `
          <p>${$t.t(
            "The client depends on the Cookie function. If cookies are not enabled in the current browser, the client cannot be used!"
          )}</p>
          <p> ${$t.t("Please refresh this page after cookies are enabled")} </p>
        `,
        persistent: true,
        ok: false,
        cancel: false,
      });
    }

    // 设置产品
    if (
      !(
        (<any>window).media_control_client_product ==
          EProductNames.LED_PLAYER ||
        (<any>window).media_control_client_product ==
          EProductNames.SPECIAL_VIDEO ||
        (<any>window).media_control_client_product ==
          EProductNames.OLD_LED_PLAYER
      )
    ) {
      console.error("can't get product, use default led_player");
      (<any>window).media_control_client_product = EProductNames.LED_PLAYER;
    }
    console.log((<any>window).media_control_client_product);
    $store.commit("setProductName", (<any>window).media_control_client_product);

    // 设置标题
    if (
      (<any>window).media_control_client_product == EProductNames.LED_PLAYER ||
      (<any>window).media_control_client_product == EProductNames.OLD_LED_PLAYER
    ) {
      const custom_title = (<any>window).media_control_client_custom_title;
      if (custom_title && typeof custom_title == "string") {
        document.title = custom_title;
      } else {
        document.title = $t.t("LedPlayer") + "WebApp";
      }
    } else if (
      (<any>window).media_control_client_product == EProductNames.SPECIAL_VIDEO
    ) {
      document.title = $t.t("SuperVPlayer") + "WebApp";
    }

    // 设置 AXIOS 默认请求头
    {
      api.defaults.headers.common["X-Product-Name"] = (<any>(
        window
      )).media_control_client_product;
    }

    // 导入对应的quasar 语言包
    try {
      {
        import("quasar/lang/" + $t.locale.value).then((lang) => {
          $q.lang.set(lang.default);
        });
      }
    } catch (e) {
      console.log(e);
    }

    try {
      const user_search = (<any>window).user_search || {};
      if (typeof user_search == "object") {
        $store.commit(
          "setAvancedDebug",
          typeof user_search["debug"] != "undefined"
        );

        $store.commit(
          "setFactoryMode",
          typeof user_search["factory"] != "undefined"
        );
      }
    } catch (e) {
      console.log(e);
    }

    EventBus.getInstance().on(EventNamesDefine.CheckDebug2, () => {
      const to_normal_url = () => {
        const p1 = window.location.href.indexOf("?debug");
        const p2 = window.location.href.indexOf("#");
        const p3 = window.location.href.substring(0, p1);
        const p4 = window.location.href.substring(p2);
        window.location.href = p3 + p4;
      };
      if ($store.state.advanced_debug) {
        const pwd = Math.floor(Math.random() * (999999 - 100000 + 1) + 100000);
        $q.dialog({
          title: "PWD?",
          message: pwd + "?",
          prompt: {
            model: "",
            type: "text", // optional
          },
          persistent: true,
          cancel: true,
        })
          .onOk((data: string) => {
            try {
              const v = parseInt(data.replace(/-/g, "").trim());
              if (pwd * pwd * pwd * new Date().getUTCHours() == v) {
                return;
              }
            } catch (e) {
              console.log(e);
            }
            to_normal_url();
          })
          .onCancel(() => {
            to_normal_url();
          });
      }
    });

    window.onresize = (evt: any) =>
      EventBus.getInstance().emit(EventNamesDefine.WindowResize, evt);

    window.onmousedown = (evt: MouseEvent) => {
      EventBus.getInstance().emit(EventNamesDefine.WindowMouseDown, evt);
    };
    window.onmousemove = (evt: any) => {
      EventBus.getInstance().emit(EventNamesDefine.WindowMouseMove, evt);
    };
    window.onmouseup = (evt: any) => {
      EventBus.getInstance().emit(EventNamesDefine.WindowMouseUp, evt);
    };
    window.onmouseout = (evt: any) => {
      EventBus.getInstance().emit(EventNamesDefine.WindowMouseOut, evt);
    };

    window.document.body.onclick = (evt: any) => {
      if ((<any>window).touchPriority) {
        return;
      }
      EventBus.getInstance().emit(EventNamesDefine.DocumentBodyClick, evt);
    };

    if ("ontouchstart" in document.documentElement === true) {
      window.document.body.ontouchstart = (evt: any) => {
        if ((<any>window).touchPriority) {
          EventBus.getInstance().emit(EventNamesDefine.DocumentBodyClick, evt);
        }
      };
    }

    document.body.classList.add("overflow-hidden");

    (window as any).controlLogout = () => {
      Cookies.remove("auto_login");
      GlobalData.getInstance().getCurrentClient()?.destory();
      GlobalData.getInstance().clearClients();
      SessionStorage.clear();
      try {
        $q.fullscreen.exit();
      } catch {}
      window.location.reload();
    };

    (window as any).setPcTheme = () => {
      setCssVar("primary", "#4aa1ce");
      setCssVar("secondary", "#26a69a");
      setCssVar("accent", "#9c27b0");
      setCssVar("dark", "#1d1d1d");
      setCssVar("positive", "#21ba45");
      setCssVar("negative", "#c10015");
      setCssVar("info", "#31ccec");
      setCssVar("warning", "#f2c037");
      setCssVar("dark-page", "#121212");
    };

    (window as any).setPadTheme = () => {
      setCssVar("primary", "#0b3536");
      setCssVar("secondary", "#ffffff");
      setCssVar("accent", "#2fa39b");
      setCssVar("dark", "#000000");
      setCssVar("positive", "#21ba45");
      setCssVar("negative", "#c10015");
      setCssVar("info", "#31ccec");
      setCssVar("warning", "#f2c037");
      setCssVar("dark-page", "#121212");
    };

    const landspace = () => {
      let landspace = false;
      landspace = window.innerWidth > innerHeight;

      if ($q.platform.is.ipad) {
        landspace = window.screen.width > window.screen.height;

        if (Math.abs(window.orientation) == 90) {
          landspace = !landspace;
        }

        {
          const user_search = (<any>window).user_search || {};
          if (typeof user_search == "object") {
            landspace = typeof user_search["___debug_ipad___"] != "undefined";
          }
        }
      }
      if (window.innerHeight < 600) {
        // TODO fix android
      }
      return landspace;
    };
    (<any>window).landspace = landspace;

    window.onorientationchange = () => {
      $store.commit("updateLandspace", landspace());
    };

    $store.commit("updateLandspace", landspace());

    if (
      $q.platform.is.ios ||
      $q.platform.is.ipad ||
      $q.platform.is.safari ||
      $q.platform.is.iphone
    ) {
      // 阻止双击放大
      var lastTouchEnd = 0;
      document.addEventListener("touchstart", function (event: any) {
        if (event.touches.length > 1) {
          event.preventDefault();
        }
      });
      document.addEventListener(
        "touchend",
        function (event) {
          var now = new Date().getTime();
          if (now - lastTouchEnd <= 300) {
            event.preventDefault();
          }
          lastTouchEnd = now;
        },
        false
      );

      // 阻止双指放大
      document.addEventListener("gesturestart", function (event) {
        event.preventDefault();
      });
    }

    return {};
  },
});
</script>
