<template>
  <el-menu
    router
    :default-active="state.defaultActive"
    background-color="transparent"
    :collapse="state.isCollapse"
    :unique-opened="getThemeConfig.isUniqueOpened"
    :collapse-transition="false"
  >
    <template v-for="val in menuLists">
      <el-sub-menu :index="val.path" v-if="val.children && val.children.length > 0" :key="val.path">
        <template #title>
          <SvgIcon :name="val.meta?.icon || ''" />
          <span>{{ $t(val.meta?.title || '') }}</span>
        </template>
        <SubItem :chil="val.children" />
      </el-sub-menu>
      <template v-else>
        <el-menu-item :index="val.path" :key="val.path">
          <SvgIcon :name="val.meta?.icon || ''" />
          <template
            #title
            v-if="!val.meta?.isLink || (val.meta?.isLink && val.meta?.isIframe)"
          >
            <span>{{ $t(val.meta?.title || '') }}</span>
          </template>
          <template #title v-else>
            <a class="w100" @click.prevent="onALinkClick(val)">
              {{ $t(val.meta?.title || '') }}
            </a>
          </template>
        </el-menu-item>
      </template>
    </template>
  </el-menu>
</template>

<script setup lang="ts" name="navMenuVertical">
import { defineAsyncComponent, reactive, computed, ref, watch, onMounted } from 'vue'
import type { PropType } from 'vue'
import { useRoute, onBeforeRouteUpdate, RouteRecordRaw } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useThemeConfig } from '/@/stores/themeConfig'
import other from '/@/utils/other'
import mittBus from '/@/utils/mitt'

// 引入组件
const SubItem = defineAsyncComponent(() => import('/@/layout/navMenu/subItem.vue'))

// 定义父组件传过来的值
const props = defineProps({
  // 菜单列表
  menuList: {
    type: Array as PropType<RouteItem[]>,
    default: () => [],
  },
})

// 定义变量内容
const storesThemeConfig = useThemeConfig()
const { themeConfig } = storeToRefs(storesThemeConfig)
const route = useRoute()
const state = reactive({
  defaultActive: route.meta.isDynamic ? route.meta.isDynamicPath : route.path,
  isCollapse: false,
})

// 本地菜单列表，用于响应水平菜单传递的菜单数据
const localMenuList = ref<RouteItem[]>([])

// 初始化本地菜单
localMenuList.value = props.menuList
// 监听父组件传入的 menuList
watch(
  () => props.menuList,
  (newList) => {
    localMenuList.value = newList
  },
  { immediate: true }
)

// 订阅水平菜单发送的菜单数据
mittBus.on('setSendColumnsChildren', (res) => {
  console.log('📨 [Vertical Menu] 接收到水平菜单数据:', {
    event: 'setSendColumnsChildren',
    data: res,
    childrenLength: res.children?.length || 0
  })
  localMenuList.value = res.children || []
  console.log('📨 [Vertical Menu] 更新本地菜单列表:', localMenuList.value?.length)
})

// 获取父级菜单数据
const menuLists = computed(() => localMenuList.value)
// 获取布局配置信息
const getThemeConfig = computed(() => {
  return themeConfig.value
})
// 菜单高亮（详情时，父级高亮）
const setParentHighlight = (currentRoute: RouteToFrom) => {
  const { path, meta } = currentRoute
  console.log('🔍 [Vertical Menu] setParentHighlight - 路由信息:', {
    path,
    meta,
    isDynamic: meta?.isDynamic,
    isDynamicPath: meta?.isDynamicPath,
    isHide: meta?.isHide
  })

  const pathSplit = meta?.isDynamic ? meta.isDynamicPath!.split('/') : path!.split('/')
  console.log('🔍 [Vertical Menu] setParentHighlight - 路径分割:', pathSplit)

  let highlightPath = ''
  if (pathSplit.length >= 4 && meta?.isHide) {
    highlightPath = pathSplit.splice(0, 3).join('/')
    console.log('🔍 [Vertical Menu] setParentHighlight - 隐藏路由高亮父级:', highlightPath)
  } else {
    highlightPath = path!
    console.log('🔍 [Vertical Menu] setParentHighlight - 常规路由高亮:', highlightPath)
  }

  return highlightPath
}
// 打开外部链接
const onALinkClick = (val: RouteItem) => {
  other.handleOpenLink(val)
}
// 页面加载时
onMounted(() => {
  console.log('🚀 [Vertical Menu] onMounted - 初始化菜单:', {
    currentRoute: route.path,
    menuLists: menuLists.value?.length
  })
  state.defaultActive = setParentHighlight(route)
  console.log('🚀 [Vertical Menu] onMounted - 设置默认激活菜单:', state.defaultActive)
})
// 路由更新时
onBeforeRouteUpdate((to) => {
  console.log('🔄 [Vertical Menu] onBeforeRouteUpdate - 路由更新:', {
    from: route.path,
    to: to.path,
    meta: to.meta
  })
  state.defaultActive = setParentHighlight(to)
  console.log('🔄 [Vertical Menu] onBeforeRouteUpdate - 更新默认激活菜单:', state.defaultActive)

  const clientWidth = document.body.clientWidth
  console.log('🔄 [Vertical Menu] onBeforeRouteUpdate - 屏幕宽度检查:', {
    clientWidth,
    needCollapse: clientWidth < 1000
  })
  if (clientWidth < 1000) themeConfig.value.isCollapse = false
})
// 设置菜单的收起/展开
watch(
  () => themeConfig.value.isCollapse,
  (isCollapse) => {
    document.body.clientWidth <= 1000 ? (state.isCollapse = false) : (state.isCollapse = isCollapse)
  },
  {
    immediate: true,
  }
)
</script>
