<template>
  <router-view class="app-page" v-slot="{ Component, route }">
    <RouterTransition :transition-name="transitionName" @leave="onLeave" @after-enter="onAfterEnter">
      <!-- 缓存组件，前进刷新，后退缓存 -->
      <keep-alive :exclude="excludeViews">
        <component :is="handleComponent(Component, route)" :key="getRouteKey(route)" />
      </keep-alive>
    </RouterTransition>
  </router-view>
</template>

<script lang="ts" setup>
import { RouteLocationNormalized, RouteRecordNormalized, RouteRecordName } from 'vue-router'
import animateRouter from '@mobile/router/animateRouter'
import RouterTransition from '@mobile/components/base/router-transition/index.vue'
import http from '@/services/http'

const { transitionName, excludeViews } = animateRouter.getStateRef()

// 手动给组件添加 name 属性，处理缓存 exclude 无效的问题
const handleComponent = (component: Record<'type', { name: RouteRecordName | undefined }>, route: RouteRecordNormalized) => {
  if (component) {
    component.type.name = route.name
  }
  return component
}

// key 的作用是当 $route.query 参数发生变化时会刷新页面
// 不直接使用 $route.fullPath 的原因是每次都会刷新页面，导致嵌套路由缓存失效
const getRouteKey = (route: RouteLocationNormalized) => {
  const qs = Object.keys(route.query)
  return qs.length ? route.fullPath : undefined
}

const onLeave = () => {
  http.pending = true
}

const onAfterEnter = () => {
  http.pending = false
}
</script>

<style lang="less">
@import './index.less';
</style>