<template>
  <div class="overflow-x-hidden">
    <AppHeader/>
    <slot/>
    <AppFooter/>
  </div>
</template>

<script setup lang="ts">
import {useMenu, useSetting, useSubMenu, useWebsite} from "~/composables/configState";
import {getLoacl, setLocal} from "~/utils/state";
import {useI18n} from "#imports";
import {getSiteInfo} from "~/api/layout";
import {getTenantIdByDomain} from "~/api/cms/cmsDomain";

// 加载状态
const website = useWebsite()
const menu = useMenu()
const subMenu = useSubMenu()
const setting = useSetting()
const i18n = useI18n()


// 挂载钩子
onMounted(() => {
  //必须在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 (process.env.NODE_ENV === 'production') {
    getTenantIdByDomain({
      domain
    }).then(data => {
      if (data?.count && data.count > 0) {
        console.log('域名已授权 => ', data.list[0].domain)
        localStorage.setItem('TenantId', `${data?.list[0].tenantId}`)
      }
    })
  }

  // TODO 2 读取服务器缓存数据
  getSiteInfo({})
    .then(data => {
      website.value = data
      if (data.topNavs) {
        menu.value = data.topNavs;
      }
      if (data.bottomNavs) {
        subMenu.value = data.bottomNavs;
      }
      if (data.config) {
        localStorage.setItem('Domain', data.config.Domain);
        localStorage.setItem('SysDomain', data.config.SysDomain);
      }
      // 网站设置信息
      if(data.setting){
        setting.value = data.setting;
      }
      // getCmsWebsiteSetting(Number(data.websiteId)).then(res => {
      //   setting.value = res;
      // })
      // seo
      useSeoMeta({
        description: data.comments || data.websiteName,
        keywords: data.keywords || data.websiteName,
        titleTemplate: localStorage.getItem('SiteName')
      })
      // 站点状态
      if (data.running != 1) {
        showError({
          statusCode: data.running,
          message: data.statusText
        })
      }
    })
    .catch((err) => {
      showError({
        statusCode: 0,
        message: '未开通'
      })
    })

  loading.close();
}

reload()
</script>

