<template>
  <page-toggle-transition
    style="height: 100%"
    :disabled="animate.disabled"
    :animate="animate.name"
    :direction="animate.direction"
  >
    <a-keep-alive :exclude-keys="excludeKeys" v-model="clearCaches">
      <router-view v-if="!refreshing" :key="$route.fullPath" />
    </a-keep-alive>
  </page-toggle-transition>
</template>

<script>
import PageToggleTransition from '../components/transition/PageToggleTransition'
import { mapState } from 'vuex'
import AKeepAlive from '@vue2-client/components/cache/AKeepAlive'

export default {
  name: 'BlankView',
  components: { PageToggleTransition, AKeepAlive },
  data() {
    return {
      clearCaches: [],
      excludeKeys: [],
      refreshing: false,
      isMicroAppEnv: false
    }
  },
  computed: {
    ...mapState('setting', ['cachePage', 'animate'])
  },
  created() {},
  mounted() {
    this.loadCacheConfig(this.$router?.options?.routes)
    if (window.__MICRO_APP_ENVIRONMENT__) {
      this.isMicroAppEnv = true
      window.microApp.addDataListener(data => {
        if (data.type === 'refresh') {
          this.refresh()
        } else if (data.type === 'clearCache' && data.key) {
          this.clearCache(data.key)
        }
      })
    }
  },
  methods: {
    // 加载需要排除缓存的路由配置
    loadCacheConfig(routes, pCache = true) {
      routes.forEach(item => {
        const cacheAble = item.meta?.keepAlive ?? pCache ?? true
        if (!cacheAble) {
          // 确保路径以 / 开头
          const path = item.path.startsWith('/') ? item.path : '/' + item.path
          this.excludeKeys.push(new RegExp(`^${path.replace(/:[^/]*/g, '[^/]*')}(\\?.*)?\\d*::.+$`))
        }
        if (item.children) {
          this.loadCacheConfig(item.children, cacheAble)
        }
      })
    },
    // 刷新页面方法
    refresh() {
      this.refreshing = true
      setTimeout(() => {
        this.refreshing = false
      }, 200)
    },
    // 清除特定页面的缓存
    clearCache(resultKeys) {
      console.warn('BlankView clearCache 开始执行:', resultKeys)

      // 1. 清除AKeepAlive缓存
      this.clearCaches = resultKeys
      // 2. 强制刷新router-view
      this.forceRefreshRouterView()

      console.warn('BlankView clearCache 执行完成')
    },

    // 强制刷新router-view
    forceRefreshRouterView() {
      this.refreshing = true
      this.$nextTick(() => {
        // 延长刷新时间，确保缓存完全清理
        setTimeout(() => {
          this.refreshing = false
          console.warn('router-view 刷新完成')
        }, 300)
      })
    }
  },
  watch: {
    '$router.options.routes': function (val) {
      this.excludeKeys = []
      this.loadCacheConfig(val)
    }
  }
}
</script>

<style scoped></style>
