<script lang="ts" setup>
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useAppStore } from '@/store/modules/app'
import { Footer } from '@/layout/components/Footer'

defineOptions({ name: 'AppView' })

const appStore = useAppStore()

const footer = computed(() => appStore.getFooter)

const tagsViewStore = useTagsViewStore()

const wrapperMap = new Map()
const wrapperKeys = ref<Set<string>>(new Set())

const getCaches = computed((): string[] => {
  return [...tagsViewStore.getCachedViews, ...wrapperKeys.value]
})

//region 无感刷新
const routerAlive = ref(true)
// 无感刷新，防止出现页面闪烁白屏
const reload = () => {
  routerAlive.value = false
  nextTick(() => (routerAlive.value = true))
}
// 为组件后代提供刷新方法
provide('reload', reload)

//设置特殊路由对应的组件名称
const formatComponentInstance = (component, route) => {
  if (!route.meta.specialCacheName) return component
  const wrapperName = route.meta.specialCacheName
  if (wrapperMap.has(wrapperName)) return wrapperMap.get(wrapperName)
  const wrapper = {  name: wrapperName,  render: () => h(component)  }
  wrapperMap.set(wrapperName, wrapper)
  wrapperKeys.value.add(wrapperName)
  return wrapper
}
</script>

<template>
  <section
    :class="[
      'flex-1 p-[var(--app-content-padding)] w-[calc(100%-var(--app-content-padding)-var(--app-content-padding))] bg-[var(--app-content-bg-color)] dark:bg-[var(--el-bg-color)]'
    ]"
  >
    <router-view v-if="routerAlive">
      <template #default="{ Component, route }">
        <keep-alive :include="getCaches">
          <component :is="formatComponentInstance(Component, route)" :key="route.fullPath" />
        </keep-alive>
      </template>
    </router-view>
  </section>
  <Footer v-if="footer" />
</template>
