<template>
  <div 
    style="min-height: 100vh"
    class="has-background-blue-100"
    data-theme="light"
    lang="vi" 
  >
    <slot></slot>
    <SnackBar v-if="snackbar" v-bind="snackbar" @close="$store.removeSnackbar()" />
    <Modal v-if="showmodal" v-bind="showmodal" @close="showmodal = undefined" />
  </div>
</template>

<script setup>
import { onMounted } from "vue";
import { useRoute } from "vue-router";
import SnackBar from '@/components/snackbar/SnackBar.vue';
import Modal from '@/components/Modal.vue'
const route = useRoute();
const { $getdata, $requestLogin, $store } = useNuxtApp();
var authorized = ref(false);
const snackbar = ref(undefined);
const showmodal = ref(undefined);
function getViewport() {
  let viewport;
  var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  if (width <= 768) viewport = 1; //'mobile'
  else if (width >= 769 && width <= 1023) viewport = 2; //'tablet'
  else if (width >= 1024 && width <= 1215) viewport = 3; //'desktop'
  else if (width >= 1216 && width <= 1407) viewport = 4; //'widescreen'
  else if (width >= 1408) viewport = 5; //'fullhd'
  $store.commit("viewport", viewport);
}
async function checkRedirect() {
  if (route.query.username && route.query.token) {
    let row = await $getdata(
      "user",
      null,
      {
        filter: { username: route.query.username },
        values: "id,avatar,username,fullname,type,type__code,type__name,is_admin",
      },
      true
    );
    if (row === "error" || row === undefined) return; /* $requestLogin(); */
    else {
      row.token = route.query.token;
      $store.commit("login", row);
    }
  } else if (!$store.login) return /* $requestLogin(); */
  // await checkLogin();
}
async function checkLogin() {
  if ($store.login ? $store.login.token : false) {
    $store.commit("rights", await $getdata("grouprights", { group: $store.login.type }));
    $store.commit("dealer", await $getdata('dealer', undefined,
      {
        filter: { user: $store.login.id },
        values: "id,code,name,phone,email,create_time",
      },
      true
    ));
    let authtoken = await $getdata("token", { token: $store.login.token }, undefined, true);
    if (authtoken ? authtoken.expiry : true) return /* $requestLogin(); */
    authorized.value = true;
  }
  // else $requestLogin();
}
onMounted(() => {
  checkRedirect()
  getViewport()
})
watch(() => $store.snackbar, (newVal) => {
  snackbar.value = newVal;
}, { deep: true });
watch(() => $store.showmodal, (newVal, oldVal) => {
  showmodal.value = newVal
})
</script>