<template>
  <a-menu
    mode="inline"
    :selected-keys="selectedKeys"
    :open-keys="openKeys"
    @openChange="handleOpenChange"
    :style="{ height: '100%', borderRight: 0 }"
  >
    <template v-for="route in menuRoutes">
      <!-- 有子菜单的路由 -->
      <a-sub-menu v-if="route.children && route.children.length > 0" :key="route.name">
        <template #title>
          <component :is="route.meta.icon" />
          <span>{{ route.meta.title }}</span>
        </template>
        <a-menu-item v-for="child in route.children" :key="child.name">
          <router-link :to="child.path">
            <span>{{ child.meta.title }}</span>
          </router-link>
        </a-menu-item>
      </a-sub-menu>
      
      <!-- 普通菜单项 -->
      <a-menu-item v-else :key="`menu-${route.name}`">
        <router-link :to="route.path">
          <component :is="route.meta.icon" />
          <span>{{ route.meta.title }}</span>
        </router-link>
      </a-menu-item>
    </template>
  </a-menu>
</template>

<script setup>
import { computed, ref, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '../stores/user'
import * as Icons from '@ant-design/icons-vue'
import { setupGlobalDebugger, debugMenuPermissions } from '../utils/menuDebugger'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 菜单状态
const openKeys = ref([])

// 检查路由权限
const hasRoutePermission = (routeItem) => {
  console.log('检查路由权限:', routeItem.name, routeItem.meta)
  console.log('用户数据:', userStore.userData)
  console.log('用户权限:', userStore.getUserPermissions())
  console.log('用户角色:', userStore.getUserRoleName())
  
  // 检查权限
  if (routeItem.meta?.permission) {
    const hasPerm = userStore.hasPermission(routeItem.meta.permission)
    console.log('权限检查结果:', routeItem.meta.permission, hasPerm)
    return hasPerm
  }
  
  // 检查角色权限
  if (routeItem.meta?.roles && routeItem.meta.roles.length > 0) {
    const hasRole = userStore.hasRole(routeItem.meta.roles)
    console.log('角色检查结果:', routeItem.meta.roles, hasRole)
    return hasRole
  }
  
  // 检查菜单权限
  if (routeItem.meta?.menu) {
    const canAccess = userStore.canAccessMenu(routeItem.meta.menu)
    console.log('菜单权限检查结果:', routeItem.meta.menu, canAccess)
    return canAccess
  }
  
  console.log('无权限要求，允许访问')
  return true
}

// 获取所有需要在菜单中显示的路由
const menuRoutes = computed(() => {
  console.log('所有路由:', router.options.routes)
  
  const filteredRoutes = router.options.routes
    .filter(route => {
      console.log('检查路由:', route.name, route.meta)
      
      // 只显示需要认证的路由，主路由需要图标，子路由不需要
      if (!route.meta || !route.meta.requiresAuth) {
        console.log('路由被过滤 - 无meta/requiresAuth:', route.name)
        return false
      }
      
      // 主路由必须有图标，子路由不需要
      if (!route.meta.icon && (!route.children || route.children.length === 0)) {
        console.log('路由被过滤 - 主路由无图标:', route.name)
        return false
      }
      
      // 检查主路由权限 - 优先检查菜单权限
      if (route.meta?.menu) {
        const canAccess = userStore.canAccessMenu(route.meta.menu)
        console.log(`菜单权限检查 ${route.name} (${route.meta.menu}):`, canAccess)
        if (!canAccess) {
          console.log('路由被过滤 - 无菜单权限:', route.name)
          return false
        }
      } else if (!hasRoutePermission(route)) {
        console.log('路由被过滤 - 无权限:', route.name)
        return false
      }
      
      console.log('路由通过过滤:', route.name)
      return true
    })
    .map(route => {
      // 如果有子路由，过滤有权限的子路由
      if (route.children && route.children.length > 0) {
        console.log('处理子路由:', route.name, route.children)
        const accessibleChildren = route.children.filter(child => {
          const hasAccess = child.meta && hasRoutePermission(child)
          console.log('子路由权限检查:', child.name, hasAccess)
          return hasAccess
        })
        
        console.log('可访问的子路由:', route.name, accessibleChildren)
        return {
          ...route,
          children: accessibleChildren
        }
      }
      
      return route
    })
    .filter(route => {
      // 如果是子菜单，至少要有一个可访问的子项
      if (route.children && route.children.length === 0) {
        console.log('子菜单无子项，过滤掉:', route.name)
        return false
      }
      return true
    })
  
  console.log('最终菜单路由:', filteredRoutes)
  return filteredRoutes
})

// 当前选中的菜单项
const selectedKeys = computed(() => {
  const currentRoute = route.name
  return [currentRoute]
})

// 监听路由变化，自动展开对应的子菜单
watch(() => route.name, (newRouteName) => {
  const currentRoute = router.options.routes.find(r => 
    r.children && r.children.some(child => child.name === newRouteName)
  )
  
  if (currentRoute && !openKeys.value.includes(currentRoute.name)) {
    console.log('自动展开父级菜单:', currentRoute.name)
    openKeys.value = [...openKeys.value, currentRoute.name]
  }
}, { immediate: true })

// 监听路由变化，确保父级菜单保持展开状态
watch(() => route.path, (newPath) => {
  // 查找当前路径对应的父级菜单
  const findParentRoute = (routes, targetPath) => {
    for (const route of routes) {
      if (route.children) {
        for (const child of route.children) {
          if (child.path === targetPath) {
            return route
          }
        }
        // 递归查找更深层的子路由
        const found = findParentRoute(route.children, targetPath)
        if (found) return found
      }
    }
    return null
  }
  
  const parentRoute = findParentRoute(router.options.routes, newPath)
  if (parentRoute && !openKeys.value.includes(parentRoute.name)) {
    console.log('保持父级菜单展开:', parentRoute.name)
    openKeys.value = [...openKeys.value, parentRoute.name]
  }
}, { immediate: true })

// 处理子菜单展开/收起
const handleOpenChange = (keys) => {
  openKeys.value = keys
  
  // 当一级菜单展开时，自动选中第一个二级菜单项
  if (keys.length > 0) {
    const lastOpenedKey = keys[keys.length - 1]
    console.log('最后展开的菜单:', lastOpenedKey)
    
    // 查找对应的一级菜单
    const findRouteByName = (routes, name) => {
      for (const route of routes) {
        if (route.name === name) {
          return route
        }
        if (route.children) {
          const found = findRouteByName(route.children, name)
          if (found) return found
        }
      }
      return null
    }
    
    const openedRoute = findRouteByName(router.options.routes, lastOpenedKey)
    if (openedRoute && openedRoute.children && openedRoute.children.length > 0) {
      // 找到第一个二级菜单项
      const firstChild = openedRoute.children[0]
      if (firstChild && firstChild.name) {
        console.log('自动选中第一个二级菜单项:', firstChild.meta?.title, firstChild.name)
        // 导航到第一个子菜单
        router.push(firstChild.path)
      }
    }
  }
}

// 组件挂载时设置调试工具
onMounted(() => {
  setupGlobalDebugger()
  
  // 调试菜单权限
  if (userStore.userData) {
    console.log('🔍 开始调试菜单权限...')
    debugMenuPermissions(userStore.userData, router.options.routes)
  }
})
</script>