<template>
  <div class="el-menu-horizontal-warp">
    <!-- 新增二级菜单导航 -->
    <el-menu
      class="sub-menu"
      mode="horizontal"
      :default-active="currentSubMenuPath"
      background-color="transparent"
      @select="onSubMenuClick"
    >
      <el-menu-item
        v-for="item in subMenuList"
        :index="item.path"
        :key="item.path"
      >
        <SvgIcon :name="item.meta?.icon" class="submenu-icon" :size="20" />
        <span>{{ $t(item.meta?.title) }}</span>
      </el-menu-item>
    </el-menu>

    <!-- 将四个模块合并为一个下拉菜单，类似语言切换 -->
    <el-dropdown
      :show-timeout="70"
      :hide-timeout="50"
      trigger="click"
      @command="onModuleCommand"
      class="module-dropdown"
    >
      <div class="module-selector">
        <SvgIcon :name="currentModule.icon" :size="20" />
        <span class="module-title">{{ currentModule.title }}</span>
        <el-icon class="el-icon--right">
          <ele-ArrowDown />
        </el-icon>
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
            v-for="module in moduleList"
            :key="module.path"
            :command="module.path"
            :class="{ 'is-active': isCurrentModule(module.path) }"
          >
            <SvgIcon :name="module.icon" class="dropdown-icon" />
            {{ module.title }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts" name="navMenuHorizontal">
import { reactive, computed, onBeforeMount } from 'vue'
import { useRoute, onBeforeRouteUpdate, RouteRecordRaw, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'
import { useRoutesList } from '/@/stores/routesList'
import { useThemeConfig } from '/@/stores/themeConfig'
import mittBus from '/@/utils/mitt'
import { treeToList, listToTree, filterList } from '/@/utils/tree'
import { cloneDeep } from 'lodash-es'

const router = useRouter()
const { t } = useI18n()

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

// 定义变量内容
const stores = useRoutesList()
const storesThemeConfig = useThemeConfig()
const { routesList } = storeToRefs(stores)
const { themeConfig } = storeToRefs(storesThemeConfig)
const route = useRoute()
const state = reactive({
  defaultActive: '' as string | undefined,
  currentModulePath: '' as string,
})

// 获取父级菜单数据
const menuLists = computed(() => {
  return <RouteItems>props.menuList
})

// 模块列表 - 将顶级菜单转换为模块选项
const moduleList = computed(() => {
  return menuLists.value.map(item => ({
    path: item.path,
    title: item.meta?.title ? t(item.meta.title) : '未命名模块',
    icon: item.meta?.icon || 'ele-Menu'
  }))
})

// 当前选中的模块
const currentModule = computed(() => {
  const current = moduleList.value.find(module =>
    state.currentModulePath === module.path ||
    route.path.startsWith(module.path)
  )

  return current || moduleList.value[0] || {
    path: '',
    title: '选择模块',
    icon: 'ele-Menu'
  }
})
// 路由过滤递归函数
const filterRoutesFun = <T extends RouteItem>(arr: T[]): T[] => {
  return arr
    .filter((item: T) => !item.meta?.isHide)
    .map((item: T) => {
      item = Object.assign({}, item)
      if (item.children) item.children = filterRoutesFun(item.children)
      return item
    })
}

// 获得根菜单路径
const getRootPath = (path: string) => {
  let rootPath = ''
  let routeTree = listToTree(
    filterList(treeToList(cloneDeep(routesList.value)), path, {
      filterWhere: (item: any, filterword: string) => {
        return item.path?.toLocaleLowerCase() === filterword
      },
    })
  )
  if (routeTree.length > 0 && routeTree[0]?.path) {
    rootPath = routeTree[0].path
  }
  return rootPath
}

// 传送当前子级数据到菜单中
const setSendClassicChildren = (path: string) => {
  let rootPath = getRootPath(path)
  rootPath = rootPath || path
  const currentPathSplit = rootPath.split('/')
  let currentData: MittMenu = { children: [] }
  filterRoutesFun(routesList.value).map((v, k) => {
    if (v.path === `/${currentPathSplit[1]}`) {
      v['k'] = k
      currentData['item'] = { ...v }
      currentData['children'] = [{ ...v }]
      if (v.children) currentData['children'] = v.children
    }
  })

  return currentData
}
// 设置页面当前路由高亮
const setCurrentRouterHighlight = (currentRoute: RouteToFrom) => {
  const { path, meta } = currentRoute
  if (themeConfig.value.layout === 'classic') {
    let rootPath = getRootPath(path || '')
    rootPath = rootPath || path || ''
    state.defaultActive = `/${rootPath?.split('/')[1]}`
    if (!state.defaultActive || state.defaultActive === '/') router.push(routesList.value[0].path)
  } else {
    const pathSplit = meta?.isDynamic ? meta.isDynamicPath!.split('/') : path!.split('/')
    if (pathSplit.length >= 4 && meta?.isHide) state.defaultActive = pathSplit.splice(0, 3).join('/')
    else state.defaultActive = path
  }
}

// 处理模块切换命令
const onModuleCommand = (path: string) => {
  console.log('🎯 [Horizontal Menu] onModuleCommand - 模块切换:', {
    selectedPath: path,
    currentModulePath: state.currentModulePath
  })

  // 更新当前模块路径
  state.currentModulePath = path
  console.log('🎯 [Horizontal Menu] onModuleCommand - 更新当前模块路径:', state.currentModulePath)

  // 查找选中的模块
  const selectedModule = menuLists.value.find(item => item.path === path)
  console.log('🎯 [Horizontal Menu] onModuleCommand - 查找选中模块:', {
    selectedModule: selectedModule ? {
      path: selectedModule.path,
      title: selectedModule.meta?.title,
      hasChildren: !!selectedModule.children,
      childrenLength: selectedModule.children?.length || 0
    } : null
  })

  if (!selectedModule) return

  // 如果模块有子菜单，跳转到第一个可用的子菜单，并更新左侧菜单为第三级
  if (selectedModule.children && selectedModule.children.length > 0) {
    const firstChild = selectedModule.children.find((child: RouteRecordRaw) => !child.meta?.isHide)
    console.log('🎯 [Horizontal Menu] onModuleCommand - 查找第一个子菜单:', {
      firstChild: firstChild ? {
        path: firstChild.path,
        title: firstChild.meta?.title,
        isHide: firstChild.meta?.isHide
      } : null
    })

    if (firstChild) {
      console.log('🎯 [Horizontal Menu] onModuleCommand - 跳转到子菜单:', firstChild.path)
      router.push(firstChild.path)
      // 更新左侧显示为第三级菜单
      const subMenuData = setSendSubMenuChildren(firstChild.path)
      console.log('🎯 [Horizontal Menu] onModuleCommand - 发送子菜单数据:', subMenuData)
      mittBus.emit('setSendColumnsChildren', subMenuData)
    } else {
      console.log('🎯 [Horizontal Menu] onModuleCommand - 无可用子菜单，跳转到模块根路径:', selectedModule.path)
      router.push(selectedModule.path)
      mittBus.emit('setSendColumnsChildren', { children: [] })
    }
  } else {
    console.log('🎯 [Horizontal Menu] onModuleCommand - 模块无子菜单，跳转到模块路径:', selectedModule.path)
    router.push(selectedModule.path)
    mittBus.emit('setSendColumnsChildren', { children: [] })
  }
}

// 新增：计算二级菜单列表
const subMenuList = computed(() => {
  const module = menuLists.value.find(item => item.path === state.currentModulePath)
  return module && module.children
    ? module.children.filter((child: RouteRecordRaw) => !child.meta?.isHide)
    : []
})

// 新增：当前选中的二级菜单路径
const currentSubMenuPath = computed(() => {
  const sub = subMenuList.value.find((child: RouteRecordRaw) => route.path.startsWith(child.path))
  return sub?.path || subMenuList.value[0]?.path || ''
})

// 新增：传送当前二级子级数据到左侧菜单
const setSendSubMenuChildren = (path: string) => {
  let res: MittMenu = { children: [] }
  const module = menuLists.value.find(item => item.path === state.currentModulePath)
  if (module && module.children) {
    const sub = module.children.find((child: RouteRecordRaw) => child.path === path)
    if (sub) {
      res.item = { ...sub }
      res.children = sub.children ? [...sub.children] : []
    }
  }

  return res
}

const setBeforeRouteUpdateClassicChildren = (path: string) => {
  console.log('🔧 [Horizontal Menu] setBeforeRouteUpdateClassicChildren - 开始解析路径:', {
    targetPath: path,
    currentModulePath: state.currentModulePath
  })

  let res: MittMenu = { children: [] }

  // 解析路径层级
  const pathSegments = path.split('/').filter(Boolean)
  console.log('🔧 [Horizontal Menu] setBeforeRouteUpdateClassicChildren - 路径分割:', {
    pathSegments,
    level: pathSegments.length
  })

  //解析菜单路径
  const module = menuLists.value.find(item => item.path === state.currentModulePath)
  console.log('🔧 [Horizontal Menu] setBeforeRouteUpdateClassicChildren - 查找模块:', {
    module: module ? {
      path: module.path,
      title: module.meta?.title,
      hasChildren: !!module.children,
      childrenCount: module.children?.length || 0
    } : null
  })

  if (module && module.children) {
    console.log('🔧 [Horizontal Menu] setBeforeRouteUpdateClassicChildren - 模块子菜单列表:',
      module.children.map((child: RouteRecordRaw) => ({
        path: child.path,
        title: child.meta?.title,
        pathStartsWithTarget: path.startsWith(child.path)
      }))
    )

    // 递归查找匹配的菜单项，返回其父级的children
    const findMatchingMenuAndParent = (menuItems: RouteRecordRaw[], targetPath: string, depth: number = 0): { parent: RouteRecordRaw | null, matchedItem: RouteRecordRaw | null } => {
      console.log(`🔧 [Horizontal Menu] findMatchingMenuAndParent - 第${depth}层查找:`, {
        menuItemsCount: menuItems.length,
        targetPath
      })

      for (const item of menuItems) {
        console.log(`🔧 [Horizontal Menu] findMatchingMenuAndParent - 检查菜单项:`, {
          itemPath: item.path,
          targetPath,
          exactMatch: item.path === targetPath,
          startsWithMatch: targetPath.startsWith(item.path),
          hasChildren: !!item.children
        })

        // 精确匹配当前路径
        if (item.path === targetPath) {
          console.log(`🔧 [Horizontal Menu] findMatchingMenuAndParent - 找到精确匹配:`, {
            matchedPath: item.path,
            title: item.meta?.title,
            hasChildren: !!item.children,
            childrenCount: item.children?.length || 0
          })
          return { parent: null, matchedItem: item }
        }

        // 如果当前路径是某个菜单项的子路径，且该菜单项有子菜单
        if (targetPath.startsWith(item.path) && item.children && item.children.length > 0) {
          console.log(`🔧 [Horizontal Menu] findMatchingMenuAndParent - 路径匹配，递归查找子菜单:`, {
            parentPath: item.path,
            parentTitle: item.meta?.title
          })

          const result = findMatchingMenuAndParent(item.children, targetPath, depth + 1)
          if (result.matchedItem) {
            // 如果在子菜单中找到了匹配项，返回当前项作为父级
            return { parent: item, matchedItem: result.matchedItem }
          }
        }
      }

      return { parent: null, matchedItem: null }
    }

    const { parent, matchedItem } = findMatchingMenuAndParent(module.children, path)

    console.log('🔧 [Horizontal Menu] setBeforeRouteUpdateClassicChildren - 匹配结果:', {
      matchedItem: matchedItem ? {
        path: matchedItem.path,
        title: matchedItem.meta?.title,
        hasChildren: !!matchedItem.children,
        childrenCount: matchedItem.children?.length || 0
      } : null,
      parent: parent ? {
        path: parent.path,
        title: parent.meta?.title,
        hasChildren: !!parent.children,
        childrenCount: parent.children?.length || 0
      } : null
    })

    if (matchedItem) {
      // 如果有父级，显示父级的children（即匹配项的同级菜单）
      // 如果没有父级，显示匹配项的children（即子菜单）
      if (parent) {
        res.item = { ...parent } as RouteItem
        res.children = parent.children ? [...parent.children] as RouteItem[] : []
        console.log('🔧 [Horizontal Menu] setBeforeRouteUpdateClassicChildren - 使用父级菜单的children:', {
          parentPath: parent.path,
          parentTitle: parent.meta?.title,
          childrenCount: res.children.length
        })
      } else {
        res.item = { ...matchedItem } as RouteItem
        res.children = matchedItem.children ? [...matchedItem.children] as RouteItem[] : []
        console.log('🔧 [Horizontal Menu] setBeforeRouteUpdateClassicChildren - 使用匹配项的children:', {
          itemPath: matchedItem.path,
          itemTitle: matchedItem.meta?.title,
          childrenCount: res.children.length
        })
      }

      console.log('🔧 [Horizontal Menu] setBeforeRouteUpdateClassicChildren - 构建结果数据:', {
        itemPath: res.item?.path,
        itemTitle: res.item?.meta?.title,
        childrenCount: res.children?.length || 0,
        children: res.children?.map(c => ({ path: c.path, title: c.meta?.title })) || []
      })
    }
  }

  console.log('🔧 [Horizontal Menu] setBeforeRouteUpdateClassicChildren - 最终返回数据:', res)
  return res
}

// 新增：二级菜单点击处理
const onSubMenuClick = (path: string) => {
  console.log('📋 [Horizontal Menu] onSubMenuClick - 二级菜单点击:', {
    clickedPath: path,
    currentRoute: route.path,
    currentModule: state.currentModulePath
  })

  // 跳转到选中的二级路由
  console.log('📋 [Horizontal Menu] onSubMenuClick - 执行路由跳转:', path)
  router.push(path)

  const subMenuData = setSendSubMenuChildren(path)
  console.log('📋 [Horizontal Menu] onSubMenuClick - 发送子菜单数据到左侧:', subMenuData)
  mittBus.emit('setSendColumnsChildren', subMenuData)
}

// 判断是否为当前模块
const isCurrentModule = (path: string): boolean => {
  return state.currentModulePath === path || route.path.startsWith(path)
}
// 页面加载前
onBeforeMount(() => {
  console.log('🚀 [Horizontal Menu] onBeforeMount - 页面加载前初始化:', {
    currentRoute: route.path,
    menuListsLength: menuLists.value?.length || 0
  })

  setCurrentRouterHighlight(route)
  console.log('🚀 [Horizontal Menu] onBeforeMount - 设置路由高亮完成')

  // 初始化当前模块
  initCurrentModule()
  console.log('🚀 [Horizontal Menu] onBeforeMount - 初始化完成:', {
    currentModulePath: state.currentModulePath,
    defaultActive: state.defaultActive
  })

  // 初始化完成后，主动发送当前路由对应的子菜单数据
  const classicChildrenData = setBeforeRouteUpdateClassicChildren(route.path)
  console.log('🚀 [Horizontal Menu] onBeforeMount - 发送初始子菜单数据:', {
    currentPath: route.path,
    data: classicChildrenData
  })
  mittBus.emit('setSendColumnsChildren', classicChildrenData)
})

// 初始化当前模块
const initCurrentModule = () => {
  console.log('🚀 [Horizontal Menu] initCurrentModule - 初始化当前模块:', {
    currentPath: route.path,
    availableModules: menuLists.value.map(m => ({ path: m.path, title: m.meta?.title }))
  })

  // 根据当前路由确定所属模块
  const currentPath = route.path
  const matchedModule = menuLists.value.find(module =>
    currentPath.startsWith(module.path) && module.path !== '/'
  )

  console.log('🚀 [Horizontal Menu] initCurrentModule - 模块匹配结果:', {
    matchedModule: matchedModule ? {
      path: matchedModule.path,
      title: matchedModule.meta?.title
    } : null
  })

  if (matchedModule) {
    state.currentModulePath = matchedModule.path
    console.log('🚀 [Horizontal Menu] initCurrentModule - 设置匹配的模块:', state.currentModulePath)
  } else if (menuLists.value.length > 0) {
    // 如果没有匹配的模块，默认选择第一个
    state.currentModulePath = menuLists.value[0].path
    console.log('🚀 [Horizontal Menu] initCurrentModule - 设置默认模块:', state.currentModulePath)
  }
}

// 路由更新时
onBeforeRouteUpdate((to) => {
  console.log('🔄 [Horizontal Menu] onBeforeRouteUpdate - 路由更新开始:', {
    from: route.path,
    to: to.path,
    toMeta: to.meta
  })

  // 修复：https://gitee.com/lyt-top/vue-next-admin/issues/I3YX6G
  setCurrentRouterHighlight(to)

  // 更新当前模块
  const matchedModule = menuLists.value.find(module =>
    to.path.startsWith(module.path) && module.path !== '/'
  )
  console.log('🔄 [Horizontal Menu] onBeforeRouteUpdate - 匹配模块:', {
    matchedModule: matchedModule ? {
      path: matchedModule.path,
      title: matchedModule.meta?.title
    } : null,
    previousModule: state.currentModulePath
  })

  if (matchedModule) {
    state.currentModulePath = matchedModule.path
    console.log('🔄 [Horizontal Menu] onBeforeRouteUpdate - 更新当前模块路径:', state.currentModulePath)
  }

  const classicChildrenData = setBeforeRouteUpdateClassicChildren(to.path)
  console.log('🔄 [Horizontal Menu] onBeforeRouteUpdate - 发送经典布局子级数据:', {
    targetPath: to.path,
    data: classicChildrenData
  })
  mittBus.emit('setSendClassicChildren', classicChildrenData)

  // // 修复经典布局开启切割菜单时，点击tagsView后左侧导航菜单数据不变的问题
  // let { layout, isClassicSplitMenu } = themeConfig.value
  // if (layout === 'classic' && isClassicSplitMenu) {
  //   mittBus.emit('setSendClassicChildren', setSendClassicChildren(to.path))
  // }
})
</script>

<style scoped lang="scss">
.el-menu-horizontal-warp {
  height: 100%;
  display: flex;
  align-items: center;
  flex: 1;
  padding: 0 16px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);

  /* 二级菜单，左侧 */
  .sub-menu {
    padding: 0 !important;
    margin: 0 !important;
    height: 100%;
    overflow-x: auto;
    white-space: nowrap;
    &::-webkit-scrollbar { display: none; }

    .el-menu-item {
      min-width: 150px;
      height: 100%;
      line-height: initial;
      margin: 0 12px;
      padding: 0;
      color: var(--next-bg-topBarColor);
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 14px;
      border-bottom: 2px solid transparent;
      transition: color 0.3s, border-color 0.3s;
      cursor: pointer;

      .submenu-icon {
        margin-top: 0;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 4px;
      }

      &.is-active {
        color: var(--el-color-primary);
        border-color: var(--el-color-primary);
        font-weight: 600;
      }
      &:hover { color: var(--el-color-primary); }
    }
  }

  /* 模块切换下拉，右侧 */
  .module-dropdown {
    flex: none;
    margin-left: 16px;
    height: 100%;
    display: flex;
    align-items: center;

    .module-selector {
      display: flex;
      align-items: center;
      height: 100%;
      line-height: initial;
      padding: 0 12px;
      gap: 8px;
      color: var(--next-bg-topBarColor);
      background: var(--el-bg-color);
      font-size: 14px;
      transition: background 0.3s, color 0.3s, border-color 0.3s;
      cursor: pointer;

      .module-title { font-weight: 500; }
      &:hover {
        background: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
        border-color: var(--el-color-primary-light-7);
      }

      /* ensure module icon and dropdown arrow align */
      .el-icon, i.el-icon {
        font-size: 20px;
        line-height: 20px;
      }
    }

    :deep(.el-dropdown-menu) {
      border-radius: 8px;
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
      border: 1px solid var(--el-border-color-light);
      min-width: 180px;

      .el-dropdown-menu__item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        margin: 4px 6px;
        border-radius: 6px;
        transition: background 0.3s, color 0.3s;
        cursor: pointer;

        .dropdown-icon {
          margin-right: 10px;
          font-size: 16px;
          width: 16px;
          height: 16px;
        }
        &:hover {
          background: var(--el-color-primary-light-9);
          color: var(--el-color-primary);
        }
        &.is-active {
          background: var(--el-color-primary-light-8);
          color: var(--el-color-primary);
          font-weight: 600;
          .dropdown-icon { color: var(--el-color-primary); }
        }
      }
    }
  }
}
</style>
