<template>
  <a-menu
    :selectedKeys="selectedKeys"
    :openKeys="openKeys"
    mode="inline"
    theme="dark"
    :inline-collapsed="collapsed"
    @click="handleMenuClick"
    @update:selectedKeys="selectedKeys = $event"
    @openChange="handleOpenChange"
  >
    <template v-for="menu in menuTree">
      <!-- 有子菜单的父菜单 -->
      <a-sub-menu v-if="menu.children && menu.children.length > 0" :key="menu.id">
        <template #icon>
          <component :is="menu.icon" v-if="menu.icon" />
          <HomeOutlined v-else />
        </template>
        <template #title>{{ menu.name }}</template>
        
        <template v-for="subMenu in menu.children">
          <!-- 子菜单还有子菜单 -->
          <a-sub-menu v-if="subMenu.children && subMenu.children.length > 0" :key="subMenu.id">
            <template #title>{{ subMenu.name }}</template>
            
            <a-menu-item v-for="item in subMenu.children" :key="item.id">
              {{ item.name }}
            </a-menu-item>
          </a-sub-menu>
          
          <!-- 子菜单是叶子节点 -->
          <a-menu-item v-else :key="subMenu.id">
            {{ subMenu.name }}
          </a-menu-item>
        </template>
      </a-sub-menu>
      
      <!-- 没有子菜单的叶子菜单 -->
      <a-menu-item v-else :key="menu.id">
        <template #icon>
          <component :is="menu.icon" v-if="menu.icon" />
          <HomeOutlined v-else />
        </template>
        {{ menu.name }}
      </a-menu-item>
    </template>
  </a-menu>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { 
  HomeOutlined, 
  SettingOutlined, 
  FileOutlined,
  DashboardOutlined,
  UserOutlined,
  ShopOutlined,
  ShoppingCartOutlined,
  AlertOutlined,
  BarChartOutlined,
  EnvironmentOutlined,
  TeamOutlined,
  SafetyOutlined
} from '@ant-design/icons-vue'
import { menuService } from '../utils/dataService'
import { message } from 'ant-design-vue'
import { useUserStore } from '../stores'

// Props
const props = defineProps({
  collapsed: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['menu-click'])

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

// 响应式数据
const selectedKeys = ref([])
const openKeys = ref([])
const menuTree = ref([])

// 监听selectedKeys变化，用于调试
watch(selectedKeys, (newKeys) => {
  console.log('selectedKeys变化:', newKeys)
}, { deep: true })

// 图标映射
const iconMap = {
  'DashboardOutlined': DashboardOutlined,
  'UserOutlined': UserOutlined,
  'ShopOutlined': ShopOutlined,
  'ShoppingCartOutlined': ShoppingCartOutlined,
  'AlertOutlined': AlertOutlined,
  'BarChartOutlined': BarChartOutlined,
  'EnvironmentOutlined': EnvironmentOutlined,
  'TeamOutlined': TeamOutlined,
  'SafetyOutlined': SafetyOutlined,
  'SettingOutlined': SettingOutlined,
  'FileOutlined': FileOutlined
}

// 根据用户权限过滤菜单树
const filterMenuTreeByPermission = (menuTree) => {
  console.log('开始权限过滤菜单树，原始菜单树数量:', menuTree.length)
  console.log('用户可访问菜单:', userStore.userData?.accessibleMenus)
  
  if (!userStore.userData?.accessibleMenus || userStore.userData.accessibleMenus.length === 0) {
    console.log('用户无菜单权限，返回空数组')
    return []
  }
  
  const filterMenu = (menu) => {
    // 检查当前菜单是否有权限
    const hasPermission = userStore.canAccessMenu(menu.menu_key)
    console.log(`菜单权限检查 ${menu.name} (${menu.menu_key}):`, hasPermission)
    
    // 递归过滤子菜单
    const filteredChildren = menu.children ? menu.children.map(filterMenu).filter(child => child !== null) : []
    console.log(`子菜单过滤结果 ${menu.name}:`, filteredChildren.length, '个子菜单')
    
    // 如果当前菜单有权限，或者有子菜单有权限，则保留
    if (hasPermission || filteredChildren.length > 0) {
      const result = {
        ...menu,
        children: filteredChildren
      }
      console.log(`保留菜单 ${menu.name}:`, result)
      return result
    }
    
    console.log(`过滤掉菜单 ${menu.name}`)
    return null
  }
  
  const filteredMenus = menuTree.map(filterMenu).filter(menu => menu !== null)
  
  console.log('权限过滤完成，过滤后菜单树数量:', filteredMenus.length)
  return filteredMenus
}

// 加载菜单数据
const loadMenus = async () => {
  try {
    console.log('开始加载菜单数据...')
    const response = await menuService.getAllMenus()
    console.log('菜单API响应:', response)
    
    let allMenus = []
    // 检查响应格式
    if (response && Array.isArray(response)) {
      // 直接是数组
      allMenus = response
    } else if (response && response.data && Array.isArray(response.data)) {
      // 包含data字段，直接是数组
      allMenus = response.data
    } else if (response && response.data && response.data.list && Array.isArray(response.data.list)) {
      // 包含data.list字段
      allMenus = response.data.list
    } else if (response && response.list && Array.isArray(response.list)) {
      // 直接包含list字段
      allMenus = response.list
    } else {
      console.warn('菜单数据格式不正确，使用默认菜单')
      console.warn('响应数据:', response)
      menuTree.value = getDefaultMenus()
      return
    }
    
    // 先构建菜单树，再过滤权限
    const fullMenuTree = buildMenuTree(allMenus)
    console.log('构建的完整菜单树:', fullMenuTree)
    
    // 根据用户权限过滤菜单树
    const filteredMenus = filterMenuTreeByPermission(fullMenuTree)
    console.log('权限过滤后的菜单树:', filteredMenus)
    
    menuTree.value = filteredMenus
    console.log('菜单树构建完成:', menuTree.value)
    console.log('菜单树长度:', menuTree.value.length)
    
    // 设置当前选中的菜单项，使用nextTick确保DOM更新完成
    nextTick(() => {
      setActiveMenu()
    })
  } catch (error) {
    console.error('加载菜单数据失败:', error)
    message.error('加载菜单数据失败')
    
    // 使用默认菜单作为后备
    console.log('使用默认菜单作为后备')
    menuTree.value = getDefaultMenus()
    console.log('默认菜单设置完成:', menuTree.value.length, '个菜单项')
  }
}

// 构建菜单树
const buildMenuTree = (menus) => {
  console.log('开始构建菜单树，原始菜单数量:', menus.length)
  
  // 转换字段名
  const convertMenuFields = (menu) => {
    return {
      id: menu.id,
      name: menu.menu_name || menu.name,
      path: menu.menu_path || menu.path,
      icon: menu.icon,
      parent_id: menu.parent_id,
      sort_order: menu.sort_order || 0,
      menu_key: menu.menu_key,
      children: []
    }
  }
  
  // 转换所有菜单项
  const convertedMenus = menus.map(convertMenuFields)
  console.log('转换后的菜单:', convertedMenus)
  
  // 创建菜单映射表
  const menuMap = new Map()
  const rootMenus = []
  
  // 先创建所有菜单项
  convertedMenus.forEach(menu => {
    menuMap.set(menu.id, menu)
  })
  
  // 构建父子关系
  convertedMenus.forEach(menu => {
    if (menu.parent_id && menuMap.has(menu.parent_id)) {
      // 有父级，添加到父级的children中
      const parent = menuMap.get(menu.parent_id)
      parent.children.push(menu)
    } else {
      // 没有父级，是根级菜单
      rootMenus.push(menu)
    }
  })
  
  // 对每个层级的菜单进行排序
  const sortMenus = (menuList) => {
    menuList.sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0))
    menuList.forEach(menu => {
      if (menu.children && menu.children.length > 0) {
        sortMenus(menu.children)
      }
    })
  }
  
  sortMenus(rootMenus)
  
  console.log('构建完成的菜单树:', rootMenus)
  console.log('根级菜单数量:', rootMenus.length)
  
  return rootMenus
}

// 设置当前激活的菜单项
const setActiveMenu = () => {
  const currentPath = route.path
  console.log('当前路径:', currentPath)
  console.log('当前菜单树:', menuTree.value)
  
  // 查找匹配的菜单项
  const findMenuByPath = (menus, path) => {
    for (const menu of menus) {
      console.log('检查菜单项:', menu.name, menu.path, '匹配路径:', path)
      if (menu.path === path) {
        console.log('找到匹配的菜单项:', menu.name, menu.id)
        return menu
      }
      if (menu.children) {
        const found = findMenuByPath(menu.children, path)
        if (found) return found
      }
    }
    return null
  }
  
  const activeMenu = findMenuByPath(menuTree.value, currentPath)
  console.log('找到的激活菜单:', activeMenu)
  
  if (activeMenu && activeMenu.id != null) {
    // 保持与模板中key绑定的数据类型一致（数字类型）
    const activeMenuId = activeMenu.id
    console.log('设置激活菜单项:', activeMenuId, '当前selectedKeys:', selectedKeys.value)
    
    // 强制更新选中状态，确保高亮显示
    selectedKeys.value = [activeMenuId]
    console.log('更新selectedKeys为:', selectedKeys.value)
    
    // 强制触发响应式更新
    nextTick(() => {
      console.log('nextTick后selectedKeys:', selectedKeys.value)
    })
    
    // 设置打开的父菜单，但保持已有的展开状态
    const parentIds = getParentMenuIds(activeMenu.id, menuTree.value)
    if (parentIds && parentIds.length > 0) {
      const parentKeys = parentIds.map(id => id != null ? id.toString() : '').filter(id => id)
      console.log('设置父级菜单展开:', parentKeys)
      // 合并已有的展开状态和新的父级菜单
      openKeys.value = [...new Set([...openKeys.value, ...parentKeys])]
    }
  } else {
    console.log('未找到匹配的菜单项，当前路径:', currentPath)
  }
}

// 获取父菜单ID
const getParentMenuIds = (menuId, menus, parentIds = []) => {
  for (const menu of menus) {
    if (menu && menu.id === menuId) {
      return parentIds
    }
    if (menu && menu.children) {
      const found = getParentMenuIds(menuId, menu.children, [...parentIds, menu.id])
      if (found) return found
    }
  }
  return null
}

// 处理菜单展开/收起
const handleOpenChange = (keys) => {
  console.log('菜单展开状态变化:', keys)
  openKeys.value = keys
  
  // 当一级菜单展开时，自动选中第一个二级菜单项
  if (keys.length > 0) {
    const lastOpenedKey = keys[keys.length - 1]
    console.log('最后展开的菜单:', lastOpenedKey)
    
    // 查找对应的一级菜单
    const findMenuById = (menus, id) => {
      for (const menu of menus) {
        if (menu && menu.id != null && menu.id.toString() === id.toString()) {
          return menu
        }
        if (menu && menu.children) {
          const found = findMenuById(menu.children, id)
          if (found) return found
        }
      }
      return null
    }
    
    const openedMenu = findMenuById(menuTree.value, lastOpenedKey)
    if (openedMenu && openedMenu.children && openedMenu.children.length > 0) {
      // 找到第一个二级菜单项
      const firstChild = openedMenu.children[0]
      if (firstChild && firstChild.id != null) {
        console.log('自动选中第一个二级菜单项:', firstChild.name, firstChild.id)
        selectedKeys.value = [firstChild.id]
        
        // 如果第一个子菜单还有子菜单，继续查找
        if (firstChild.children && firstChild.children.length > 0) {
          const firstGrandChild = firstChild.children[0]
          if (firstGrandChild && firstGrandChild.id != null) {
            console.log('自动选中第一个三级菜单项:', firstGrandChild.name, firstGrandChild.id)
            selectedKeys.value = [firstGrandChild.id]
          }
        }
      }
    }
  }
}

// 处理菜单点击
const handleMenuClick = ({ key }) => {
  console.log('菜单点击:', key)
  
  // 检查key是否为null或undefined
  if (!key) {
    console.warn('菜单点击事件中key为空:', key)
    return
  }
  
  // 直接使用key作为ID，不再需要处理前缀
  const actualKey = key.toString()
  console.log('实际查找的key:', actualKey)
  
  // 查找菜单项
  const findMenuById = (menus, id) => {
    for (const menu of menus) {
      // 检查menu和menu.id是否存在
      if (menu && menu.id != null && menu.id.toString() === id) {
        return menu
      }
      if (menu && menu.children) {
        const found = findMenuById(menu.children, id)
        if (found) return found
      }
    }
    return null
  }
  
  const menuItem = findMenuById(menuTree.value, actualKey)
  if (menuItem && menuItem.path) {
    console.log('导航到:', menuItem.path)
    
    // 确保父级菜单保持展开状态
    const parentIds = getParentMenuIds(menuItem.id, menuTree.value)
    if (parentIds && parentIds.length > 0) {
      const parentKeys = parentIds.map(id => id != null ? id.toString() : '').filter(id => id)
      console.log('保持父级菜单展开:', parentKeys)
      // 使用Set确保不重复，并保持原有展开状态
      const newOpenKeys = [...new Set([...openKeys.value, ...parentKeys])]
      openKeys.value = newOpenKeys
    }
    
    // 先设置选中的菜单项，确保高亮显示
    // 将字符串转换为数字类型以匹配模板中的key绑定
    const menuId = parseInt(actualKey)
    selectedKeys.value = [menuId]
    console.log('设置选中菜单项:', menuId)
    
    // 然后导航到对应路径
    router.push(menuItem.path)
    emit('menu-click', menuItem)
  } else {
    console.warn('未找到菜单项:', actualKey)
    console.log('当前菜单树:', menuTree.value)
  }
}

// 获取默认菜单（作为后备）
const getDefaultMenus = () => {
  return [
    {
      id: 1,
      name: '系统概览',
      path: '/dashboard',
      icon: 'DashboardOutlined',
      children: []
    },
    {
      id: 2,
      name: '智能设备',
      path: '/smart-devices',
      icon: 'SettingOutlined',
      children: [
        {
          id: 21,
          name: '智能耳标',
          path: '/smart-devices/eartag',
          children: []
        },
        {
          id: 22,
          name: '智能项圈',
          path: '/smart-devices/collar',
          children: []
        },
        {
          id: 23,
          name: '智能主机',
          path: '/smart-devices/host',
          children: []
        },
        {
          id: 24,
          name: '电子围栏',
          path: '/smart-devices/fence',
          children: []
        }
      ]
    },
    {
      id: 3,
      name: '智能预警总览',
      path: '/smart-alerts',
      icon: 'AlertOutlined',
      children: [
        {
          id: 31,
          name: '智能耳标预警',
          path: '/smart-alerts/eartag',
          children: []
        },
        {
          id: 32,
          name: '智能项圈预警',
          path: '/smart-alerts/collar',
          children: []
        }
      ]
    },
    {
      id: 4,
      name: '牛只管理',
      path: '/cattle-management',
      icon: 'BugOutlined',
      children: [
        {
          id: 41,
          name: '牛只档案',
          path: '/cattle-management/archives',
          children: []
        },
        {
          id: 42,
          name: '栏舍设置',
          path: '/cattle-management/pens',
          children: []
        },
        {
          id: 43,
          name: '批次设置',
          path: '/cattle-management/batches',
          children: []
        },
        {
          id: 44,
          name: '转栏记录',
          path: '/cattle-management/transfer-records',
          children: []
        },
        {
          id: 45,
          name: '离栏记录',
          path: '/cattle-management/exit-records',
          children: []
        }
      ]
    },
    {
      id: 5,
      name: '养殖场管理',
      path: '/farm-management',
      icon: 'HomeOutlined',
      children: [
        {
          id: 51,
          name: '养殖场信息管理',
          path: '/farm-management/info',
          children: []
        },
        {
          id: 52,
          name: '栏舍管理',
          path: '/farm-management/pens',
          children: []
        },
        {
          id: 53,
          name: '用户管理',
          path: '/farm-management/users',
          children: []
        },
        {
          id: 54,
          name: '角色权限管理',
          path: '/farm-management/role-permissions',
          children: []
        }
      ]
    },
    {
      id: 6,
      name: '系统管理',
      path: '/system',
      icon: 'SettingOutlined',
      children: []
    }
  ]
}

// 监听路由变化
watch(() => route.path, () => {
  // 确保菜单树已加载完成后再设置激活状态
  if (menuTree.value && menuTree.value.length > 0) {
    nextTick(() => {
      setActiveMenu()
    })
  }
})

// 监听用户数据变化，当用户数据加载完成后再加载菜单
watch(() => userStore.userData, (newUserData) => {
  console.log('用户数据变化，重新加载菜单:', newUserData)
  if (newUserData && newUserData.id) {
    loadMenus()
  }
}, { immediate: true })

// 组件挂载时也尝试加载菜单（作为后备）
onMounted(() => {
  console.log('DynamicMenu组件挂载，当前用户数据:', userStore.userData)
  if (userStore.userData && userStore.userData.id) {
    loadMenus()
  }
})
</script>

<style scoped>
.ant-menu {
  border-right: none;
}
</style>
