<template>
  <app-header />
  <slot />
  <app-footer />
</template>
<script setup lang="ts">
  import {getLoacl, setLocal} from "~/utils/common";
  import {listWebsite} from "~/api/cms/website";
  import {useServerRequest} from "~/composables/useServerRequest";
  import type {ApiResult} from "~/api";
  import type {Domain} from "~/api/cms/domain/model";
  import {useConfigInfo, useMenu, useSubMenu, 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";

  // TODO 1 查询当前域名是否有绑定域名,绑定则解构出租户ID放入缓存
  localStorage.removeItem('TID_DOMAIN');
  if (!localStorage.getItem('TID_DOMAIN')) {
    const domain = window.location.hostname;
    const {data: domainInfo } = await useServerRequest<ApiResult<Domain>>('/cms/domain/getByDomain/' + domain);
    const data = domainInfo.value?.data;
    console.log(data,'当前域名是否有绑定')
    if (data) {
      localStorage.setItem('TID_DOMAIN',`${data?.tenantId}`)
    }
  }

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

  // TODO 3 读取网站信息
  const website = useWebsite()
  const {data: websiteInfo } = await useServerRequest<ApiResult<Website>>('/cms/website/getSiteInfo');
  if(websiteInfo.value?.data){
    website.value = websiteInfo.value?.data;
  }

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

  // TODO 5 获取网站顶部菜单
  const menu = useMenu()
  const { data: menuInfo } = await useServerRequest<ApiResult<Navigation[]>>('/cms/navigation/tree', {
    query: {
      position: 1
    }
  });
  if(menuInfo.value?.data){
    menu.value = menuInfo.value?.data
  }

  // TODO 6 获取网站底部菜单
  const subMenu = useSubMenu()
  const { data: subMenuInfo } = await useServerRequest<ApiResult<Navigation[]>>('/cms/navigation/tree', {
    query: {
      position: 2
    }
  });
  if(subMenuInfo.value?.data){
    subMenu.value = subMenuInfo.value?.data
  }

</script>
