<template>
  <div class="routeCache" :view-type="viewType">
    <router-view v-slot="{ Component, route }" @view-type="changeViewType">
      <keep-alive :include="cachedViews">
        <component :is="Component" :key="route.name" />
      </keep-alive>
    </router-view>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
import MyEvent from '@/utils/myEvent'

const route = useRoute()

// 缓存的组件名称列表
const cachedViews = ref<string[]>([])

// 监听路由变化，管理缓存
watch(
  () => route,
  (newRoute) => {
    const routeName = newRoute.name as string
    const shouldCache = newRoute.meta?.cache === true

    // console.log('🔄 路由变化:', { routeName, shouldCache, currentCache: cachedViews.value })

    if (shouldCache && routeName && !cachedViews.value.includes(routeName)) {
      cachedViews.value.push(routeName)
      // console.log('✅ 添加到缓存:', routeName)
    } else if (!shouldCache && routeName && cachedViews.value.includes(routeName)) {
      // 从缓存列表中移除
      const index = cachedViews.value.indexOf(routeName)
      if (index > -1) {
        cachedViews.value.splice(index, 1)
        // console.log('❌ 从缓存移除:', routeName)
      }
    }
  },
  { immediate: true, deep: true }
)

// 提供清除缓存的方法
const clearCache = (routeName?: string) => {
  if (routeName) {
    const index = cachedViews.value.indexOf(routeName)
    if (index > -1) {
      cachedViews.value.splice(index, 1)
    }
  } else {
    cachedViews.value = []
  }
}

onMounted(() => {
  MyEvent.add('clearAllCache', clearCache)
})

//根据viewType设置布局风格样式
const viewType = ref(0)
const changeViewType = (v: number) => {
  viewType.value = v
}
const router = useRouter()
watch(
  () => router.currentRoute.value,
  () => (viewType.value = 0)
)

// 暴露方法供外部使用
defineExpose({
  clearCache,
  cachedViews
})
</script>
<style lang="less" scoped>
.routeCache {
  width: 100%;
  height: 100%;
  position: relative;
  font-family: 'satoshiRegular';
  &[view-type='1'] {
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
}
</style>
