<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import navTop from './_nav-top.vue'
import navLeft from './_nav-left.vue'
import ThemeCustomizer from '../admin/_theme.vue'

const route = useRoute()

// 当前布局类型
const getLayoutFromConfig = () => {
  const savedConfig = localStorage.getItem('_mis_acis_theme')
  if (savedConfig) {
    try {
      const config = JSON.parse(savedConfig)
      return config.layout || 'horizontal'
    } catch (e) {
      return 'horizontal'
    }
  }
  return 'horizontal'
}
const currentLayout = ref(getLayoutFromConfig())

// ThemeCustomizer 的 ref
const themeCustomizerRef = ref(null)

// 根据布局类型返回对应的组件
const layoutComponent = computed(() => {
  switch (currentLayout.value) {
  case 'topside':
    return navLeft
  case 'horizontal':
  default:
    return navTop
  }
})

// 判断当前路由是否需要缓存
const shouldKeepAlive = computed(() => {
  return route.meta?.keepAlive ?? false
})

// 监听 localStorage 变化（用于跨组件通信）
const handleStorageChange = e => {
  if (e.key === '_mis_acis_theme') {
    try {
      const config = JSON.parse(e.newValue)
      currentLayout.value = config.layout || 'horizontal'
    } catch (err) {
      currentLayout.value = 'horizontal'
    }
  }
}

// 监听自定义事件（用于同一窗口内的通信）
const handleLayoutChange = e => {
  currentLayout.value = e.detail || 'horizontal'
}

onMounted(() => {
  // 监听 storage 事件（跨标签页）
  window.addEventListener('storage', handleStorageChange)

  // 监听自定义事件（同一窗口）
  window.addEventListener('layoutChange', handleLayoutChange)
})

// 监听布局变化，保存到 localStorage
watch(currentLayout, newLayout => {
  const savedConfig = localStorage.getItem('_mis_acis_theme')
  let config = {
    themeMode: 'light',
    primaryColor: '#9155FD',
    layout: 'horizontal',
    cardSkin: 'default',
  }

  if (savedConfig) {
    try {
      config = JSON.parse(savedConfig)
    } catch (e) {
      // Use default config
    }
  }

  config.layout = newLayout
  localStorage.setItem('_mis_acis_theme', JSON.stringify(config))
})
</script>

<template>
  <component
    :is="layoutComponent"
    :theme-customizer-ref="themeCustomizerRef"
  >
    <RouterView v-slot="{ Component }">
      <KeepAlive>
        <component :is="Component" v-if="shouldKeepAlive" :key="route.name" />
      </KeepAlive>
      <component :is="Component" v-if="!shouldKeepAlive" :key="route.fullPath" />
    </RouterView>
  </component>

  <!-- 主题定制器 - 在所有布局中都可用 -->
  <ThemeCustomizer ref="themeCustomizerRef" />

</template>

<style lang="scss">

</style>
