<template>
  <div class="overflow-x-hidden">
    <!-- 加载应用 -->
    <template v-if="!loading" @scroll="handleScroll">
      <!-- 管理中心界面 -->
      <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 type {Domain} from "~/api/cms/domain/model";
import {useConfigInfo, useForm, useMenu, useSubMenu, useToken, useWebsite} from "~/composables/configState";
import type {Website} from "~/api/cms/website/model";
import type {Navigation} from "~/api/cms/navigation/model";
import type {Config} from "~/types/global";
import {getLoacl, getPath, setLocal} from "~/utils/common";
import UnderMaintenance from "~/components/UnderMaintenance.vue";
import {navigateTo} from "#imports";

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

// 挂载钩子
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 (domain !== 'localhost') {
    // 生产环境生效
    // const runtimeConfig = useRuntimeConfig();
    // const {data: domainInfo } = await useServerRequest<ApiResult<Domain>>('/cms/cms-domain/getTenantIdByDomain',{baseURL: runtimeConfig.public.apiServer,query: {
    //     domain
    //   }});
    // const data = domainInfo.value?.data;
    // console.log(data,'查询当前域名是否有绑定域名,绑定则解构出租户ID放入缓存')
    // if (data) {
    // localStorage.setItem('TID_DOMAIN',`${data?.tenantId}`)
    // }else {
    // token.value = '';
    // navigateTo('/passport/login')
    // }
  }

  // TODO 2 读取服务器缓存数据
  const {data: websiteInfo} = await useServerRequest<ApiResult<Website>>('/cms/cms-website/getSiteInfo', {
    baseURL: runtimeConfig.public.apiServer
  });
  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) {
    console.log(websiteInfo.value.data,'-=======')
    website.value = websiteInfo.value?.data;
    config.value = website.value.config;
    if (website.value.topNavs) {
      // if(localStorage.getItem('UserId')){
      //   website.value?.topNavs.push({
      //     title:  `入驻`,
      //     path: `/developer`
      //   })
      // }
      menu.value = website.value?.topNavs;
    }
    if (website.value.bottomNavs) {
      subMenu.value = website.value?.bottomNavs;
    }
    // 生产环境生效
    if (domain !== 'localhost') {
      console.log(domain, 'domain')
      console.log(website.value.websiteCode)
      console.log(`${website.value?.websiteCode}.wsdns.cn`, '二级域名')
    }
  }

  // TODO 4 读取网站状态
  // const {data: websiteRealTime } = await useServerRequest<ApiResult<Website>>('/cms/cms-website/' + website.value.websiteId,{baseURL: runtimeConfig.public.apiServer});
  // website.value = Object.assign({},website.value,websiteRealTime.value?.data)
  // if (website.value?.status != 1) {
  //   useHead({title: ''})
  //   // loading.value = true;
  //   return false;
  // }

  // TODO 5 读取网站配置信息
  // const { data: fields } = await useServerRequest<ApiResult<Config>>('/cms/cms-website-field/config', {baseURL: runtimeConfig.public.apiServer});
  // if (fields.value?.data) {
  //   config.value = fields.value?.data;
  // }

  // TODO 6 获取网站顶部菜单
  // const { data: menuInfo } = await useServerRequest<ApiResult<Navigation[]>>('/cms/cms-navigation/tree', {baseURL: runtimeConfig.public.apiServer,
  //   query: {
  //     top: 0
  //   }
  // });
  // if(menuInfo.value?.data){
  //   console.log(menuInfo.value.data,'顶部菜单')
  //   menu.value = menuInfo.value?.data
  // }

  // TODO 7 获取网站底部菜单
  // const { data: subMenuInfo } = await useServerRequest<ApiResult<Navigation[]>>('/cms/cms-navigation/tree', {baseURL: runtimeConfig.public.apiServer,
  //   query: {
  //     bottom: 0
  //   }
  // });
  // if(subMenuInfo.value?.data){
  //   subMenu.value = subMenuInfo.value?.data
  // }

  // TODO 8 获取当前页面的导航信息
  // const { data: navInfo } = await useServerRequest<ApiResult<Navigation>>('/cms/navigation/getNavigationByPath', {
  //   query: {
  //     path: getPath()
  //   }
  // });
  // if(navInfo.value?.data){
  //   form.value = navInfo.value?.data
  // }

  // TODO 9 配置SEO
  // useHead({
  //   title: `网宿软件首页`,
  //   meta: [{ name: website.value.keywords, content: website.value.comments }]
  // });


  // TODO 是否需要登录
  // if(form.value.permission === 1){
  //   // navigateTo(`/passport/login`)
  // }
}

reload()
</script>
