<meta name="viewport" content="user-scalable=no" />

<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />

<!-- uc强制竖屏 portrait|landscape -->
<meta name="screen-orientation" content="landscape" />
<!-- UC强制全屏 -->
<meta name="full-screen" content="yes" />
<!-- UC应用模式 -->
<meta name="browsermode" content="application" />

<!-- QQ强制竖屏 portrait|landscape-->
<meta name="x5-orientation" content="landscape" />
<!-- QQ/华为强制全屏 -->
<meta name="x5-fullscreen" content="true" />
<!-- QQ应用模式 -->
<meta name="x5-page-mode" content="app" />

<template>
  <q-layout view="hHh lpR fFf">
    <div v-show="$store.state.initialized">
      <!-- header -->
      <q-header
        elevated
        class="header"
        @touchstart="(evt) => evt.stopPropagation()"
      >
        <top-tool-bar />
      </q-header>

      <!-- page -->
      <q-page-container class="col bg-primary">
        <div class="row">
          <!-- cener content -->
          <div class="col q-ma-sm">
            <router-view />
          </div>
        </div>
      </q-page-container>
      <q-footer>
        <bottom-bar />
      </q-footer>
    </div>
    <div v-show="!$store.state.initialized">
      <q-page-container class="col">
        <q-page class="row items-center justify-evenly">
          <q-list>
            <q-item>
              <q-item-section>
                <q-spinner color="primary" size="8em" :thickness="2" />
              </q-item-section>
            </q-item>
            <q-item />
            <q-item>
              <q-item-section>
                <div class="text-h5">loading...</div>
              </q-item-section>
            </q-item>
            <q-item v-show="show_back">
              <q-item-section>
                <a href="javascript:void(0);" OnClick="window.controlLogout()">
                  {{ $t("back to login page") }}
                </a>
              </q-item-section>
            </q-item>
          </q-list>
        </q-page>
      </q-page-container>
    </div>
  </q-layout>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";

import TopToolBar from "./TopToolbar.vue";
import BottomBar from "./BottomBar.vue";

import EventBus, { EventNamesDefine } from "src/common/EventBus";
import { useI18n } from "vue-i18n";
import { useQuasar } from "quasar";
import { useStore } from "src/store";
import { api } from "src/boot/axios";
import GlobalData from "src/common/GlobalData";
import { HttpProtocol } from "src/entities/HttpProtocol";
import { EProductNames } from "src/entities/ProductNames";

export default defineComponent({
  name: "PadMainLayout",

  components: { TopToolBar, BottomBar },

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

    const show_back = ref(true);
    (<any>window).isPad = true; // pad flag
    (<any>window).touchPriority = true; // 优先使用触摸事件

    try {
      (window as any).setPadTheme();
    } catch {}

    EventBus.getInstance().on(EventNamesDefine.CurrentConnectDisconnect, () => {
      show_back.value = false;
    });

    EventBus.getInstance().on(EventNamesDefine.CurrentConnectConnected, () => {
      console.log();
      show_back.value = true;
    });

    if ($q.platform.is.android && !$q.platform.is.capacitor) {
      $q.dialog({
        title: $t.t("The Anroid platform"),
        message: $t.t(
          "The Anroid platform recommends using APK for a better experience"
        ),
        persistent: true,
        ok: {
          label: $t.t("download"),
          noCaps: true,
          flat: true,
        },
        cancel: {
          label: $t.t("cancel"),
          noCaps: true,
          flat: true,
        },
      }).onOk(() => {
        window.location.href =
          window.location.origin +
          window.location.pathname +
          "/store/cx_android_client.apk";
      });
    }

    if ($q.platform.is.android && $q.platform.is.capacitor) {
      let client = GlobalData.getInstance().getCurrentClient();
      if (client) {
        let url = new URL(client.url);
        url.port =
          GlobalData.getInstance().applicationConfig?.httpserver_port ??
          HttpProtocol.DefaultHttpPort.toString();
        url.pathname = "";
        url.protocol = "http:";

        // 获取重定向后的 url
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url.toString(), true);
        xhr.onload = function () {
          url = new URL(xhr.responseURL);
          const back_pathname = url.pathname;

          // 设置产品
          url.pathname += "/media_control_client_product.js";
          api.get(url.toString()).then((data) => {
            const start = (data.data as string).lastIndexOf("=");
            const end = (data.data as string).lastIndexOf(";");
            let product = (data.data as string)
              .substring(start + 1, end == -1 ? undefined : end)
              ?.trim();
            try {
              product = JSON.parse(product);
            } catch (e) {}

            if (
              product == EProductNames.LED_PLAYER ||
              product == EProductNames.SPECIAL_VIDEO ||
              product == EProductNames.OLD_LED_PLAYER
            ) {
              (<any>window).media_control_client_product = product;
              $store.commit(
                "setProductName",
                (<any>window).media_control_client_product
              );

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

          url.pathname = back_pathname;
          url.pathname += "/store/version.txt";
          api
            .get(url.toString())
            .then((data) => {
              if (data && data.data) {
                try {
                  const server_version = parseInt(
                    (data.data as string).trim().replace(/\./g, "")
                  );
                  var package_json = require("../../package.json");
                  const local_version = parseInt(
                    package_json.version.trim().replace(/\./g, "")
                  );
                  if (server_version > local_version) {
                    $q.dialog({
                      title: $t.t("upgrade"),
                      message: $t.t(
                        "The detected version does not match, please download the new version!"
                      ),
                      persistent: true,
                      ok: {
                        label: $t.t("download"),
                        noCaps: true,
                        flat: true,
                      },
                    }).onOk(() => {
                      url.pathname =
                        back_pathname + "/store/cx_android_client.apk";
                      window.location.href = url.toString();
                    });
                  }
                } catch (e) {
                  alert($t.t("get version error!"));
                }
              }
            })
            .catch(() => {
              alert($t.t("get version error!"));
            });
        };
        xhr.send(null);
      }
    }

    return {
      show_back,
      loga(a: any) {
        console.log(a);
      },
    };
  },
});
</script>
