<template>
	<router-view v-slot="{ Component, route }">
		<keep-alive :include="cachedViews">
			<component :is="Component" :key="route.name" />
		</keep-alive>
	</router-view>
</template>

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

	const props = defineProps({})

	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)
	})

	// 暴露方法供外部使用
	defineExpose({
		clearCache,
		cachedViews
	})
</script>
<style lang="less" scoped>
	.routeCache {
		width: 100%;
		height: 100%;
	}
</style>
