<template>
  <div class="overflow-x-hidden">
    <!-- 加载应用 -->
    <template v-if="!loading">
      <!-- 管理中心界面 -->
      <template v-if="getPath().startsWith('/manage')">
        <slot/>
      </template>
      <!-- 默认布局 -->
      <template v-else>
        <app-header/>
        <slot/>
        <app-footer/>
      </template>
    </template>

    <!-- 异常状态 -->
    <UnderMaintenance v-if="loading"/>
  </div>
</template>
<script setup lang="ts">
import {useServerRequest} from "~/composables/useServerRequest";
import type {ApiResult} from "~/api";
import {useConfigInfo, useForm, useMenu, useSubMenu, useToken, useWebsite} from "~/composables/configState";
import {getPath} from "~/utils/common";
import UnderMaintenance from "~/components/UnderMaintenance.vue";
import {navigateTo} from "#imports";
import type {CmsDomain} from "~/api/cms/cmsDomain/model";
import type {CmsWebsite} from "~/api/cms/cmsWebsite/model";

// 加载状态
const runtimeConfig = useRuntimeConfig();
const loading = ref<boolean>(false)
const website = useWebsite()
const config = useConfigInfo()
const menu = useMenu()
const token = useToken()
const subMenu = useSubMenu()

// 挂载钩子
onMounted(() => {
  reload();
  //必须在onMounted的时候才能用local和window
  // getLoacl();
  window.onbeforeunload = () => {
    //离开页面时保存数据，由于可能突发情况，所以重要数据请手动调用setLocal函数
    // setLocal(); //如果需要调试本地存储数据，记得把这个注释一下
  };
});

// 加载数据
const reload = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading'
  })

  // TODO 1 查询当前域名是否合法 生产环境生效
  const domain = window.location.hostname;

  if (domain !== 'localhost') {
    const {data: domainInfo } = await useServerRequest<ApiResult<CmsDomain>>('/cms/cms-domain/getTenantIdByDomain',{baseURL: 'https://server.gxwebsoft.com/api',query: {
        domain
      }});
    const data = domainInfo.value?.data;
    console.log(data,'查询当前域名是否有绑定域名,绑定则解构出租户ID放入缓存')
    if (data) {
      localStorage.setItem('TenantId',`${data?.tenantId}`)
    }
  }

  // TODO 2 读取服务器缓存数据
  const {data: websiteInfo} = await useServerRequest<ApiResult<CmsWebsite>>('/cms/cms-website/getSiteInfo', {});
  if (!websiteInfo.value) {
    ElMessage.error('require is not defined.')
    return false;
  }
  if(websiteInfo.value.code === 401){
    const token = useToken();
    token.value = '';
    localStorage.clear();
    // window.location.reload();
    return false;
  }
  if (websiteInfo.value?.data) {
    website.value = websiteInfo.value?.data;
    localStorage.setItem('SiteName',`${website.value.websiteName}`);
    localStorage.setItem('TenantId',`${websiteInfo.value.data.tenantId}`);
    if (website.value.topNavs) {
      menu.value = website.value?.topNavs;
    }
    if (website.value.bottomNavs) {
      subMenu.value = website.value?.bottomNavs;
    }
    if(website.value.config){
      localStorage.setItem('Domain',website.value.config.Domain);
      localStorage.setItem('SysDomain',website.value.config.SysDomain);
    }
  }

  loading.close();
}

</script>
