<template>
  <el-menu ref="menuRef" :default-active="activeMenu" mode="horizontal" :ellipsis="false" @select="handleSelect">
    <template v-for="(item, index) in topMenus">
      <el-menu-item 
        v-if="index < visibleNumber" 
        :key="index" 
        :style="{ '--theme': theme }" 
        :index="item.path"
        :ref="(el) => setMenuItemRef(el, index)"
      >
        <svg-icon v-if="item.meta && item.meta.icon && item.meta.icon !== '#'" :icon-class="item.meta ? item.meta.icon : ''" />
        {{ getMenuTitle(item) }}
      </el-menu-item>
    </template>

    <!-- 顶部菜单超出数量折叠 -->
    <el-sub-menu v-if="topMenus.length > visibleNumber" :style="{ '--theme': theme }" index="more">
      <template #title>{{ $t('components.topNav.moreMenu') }}</template>
      <template v-for="(item, index) in topMenus">
        <el-menu-item v-if="index >= visibleNumber" :key="index" :index="item.path"
          ><svg-icon :icon-class="item.meta ? item.meta.icon : ''" /> {{ getMenuTitle(item) }}</el-menu-item
        >
      </template>
    </el-sub-menu>
  </el-menu>
</template>

<script setup lang="ts">
import { constantRoutes } from '@/router';
import { isHttp } from '@/utils/validate';
import { useAppStore } from '@/store/modules/app';
import { useSettingsStore } from '@/store/modules/settings';
import { usePermissionStore } from '@/store/modules/permission';
import { RouteRecordRaw } from 'vue-router';
import { parseI18nName } from '@/utils/i18n';
import { useI18n } from 'vue-i18n';

// 顶部栏可见菜单数量
const visibleNumber = ref<number>(999); // 初始值设为较大数，确保首次渲染所有菜单用于测量
// 当前激活菜单的 index
const currentIndex = ref<string>();
// 隐藏侧边栏路由
const hideList = ['/index', '/user/profile'];
// 菜单容器引用
const menuRef = ref<any>(null);
// 菜单项引用数组
const menuItemRefs = ref<any[]>([]);
// 是否首次计算
const isFirstCalculation = ref(true);
// 计算定时器，用于防抖
let calculateTimer: any = null;
// 是否启用调试模式（开发时可设为true）
const DEBUG_MODE = false;

const appStore = useAppStore();
const settingsStore = useSettingsStore();
const permissionStore = usePermissionStore();
const route = useRoute();
const router = useRouter();
const { locale } = useI18n();

// 主题颜色
const theme = computed(() => settingsStore.theme);
// 所有的路由信息
const routers = computed(() => permissionStore.getTopbarRoutes());
// 侧边栏状态
const sidebarOpened = computed(() => appStore.sidebar.opened);
// 侧边栏是否隐藏
const sidebarHide = computed(() => appStore.sidebar.hide);
// 是否显示顶部导航
const topNav = computed(() => settingsStore.topNav);

// 顶部显示菜单
const topMenus = computed(() => {
  // 添加 locale 依赖，确保语言切换时更新
  const _ = locale.value;
  const topMenus: RouteRecordRaw[] = [];
  routers.value.map((menu) => {
    if (menu.hidden !== true) {
      // 兼容顶部栏一级菜单内部跳转
      if (menu.path === '/' && menu.children) {
        topMenus.push(menu.children ? menu.children[0] : menu);
      } else {
        topMenus.push(menu);
      }
    }
  });
  return topMenus;
});

// 解析菜单标题的国际化名称
const getMenuTitle = (item: RouteRecordRaw): string => {
  return parseI18nName(item.meta?.title);
};

// 设置子路由
const childrenMenus = computed(() => {
  const childrenMenus: RouteRecordRaw[] = [];
  routers.value.map((router) => {
    router.children?.forEach((item) => {
      if (item.parentPath === undefined) {
        if (router.path === '/') {
          item.path = '/' + item.path;
        } else {
          if (!isHttp(item.path)) {
            item.path = router.path + '/' + item.path;
          }
        }
        item.parentPath = router.path;
      }
      childrenMenus.push(item);
    });
  });
  return constantRoutes.concat(childrenMenus);
});

// 默认激活的菜单
const activeMenu = computed(() => {
  let path = route.path;
  if (path === '/index') {
    path = '/system/user';
  }
  let activePath = path;
  if (path !== undefined && path.lastIndexOf('/') > 0 && hideList.indexOf(path) === -1) {
    const tmpPath = path.substring(1, path.length);
    if (!route.meta.link) {
      activePath = '/' + tmpPath.substring(0, tmpPath.indexOf('/'));
      appStore.toggleSideBarHide(false);
    }
  } else if (!route.children) {
    activePath = path;
    appStore.toggleSideBarHide(true);
  }
  activeRoutes(activePath);
  return activePath;
});

// 设置菜单项引用
const setMenuItemRef = (el: any, index: number) => {
  if (el) {
    menuItemRefs.value[index] = el;
  }
};

// 带防抖的计算菜单可见数量（用于频繁触发的场景）
const debouncedCalculateVisibleMenus = (delay: number = 100) => {
  if (calculateTimer) {
    clearTimeout(calculateTimer);
  }
  calculateTimer = setTimeout(() => {
    calculateVisibleMenus();
  }, delay);
};

// 动态计算可见菜单数量
const calculateVisibleMenus = () => {
  nextTick(() => {
    if (!menuRef.value || topMenus.value.length === 0) {
      return;
    }

    const menuElement = menuRef.value.$el as HTMLElement;
    if (!menuElement) {
      return;
    }

    // 获取右侧菜单元素的位置
    const rightMenu = document.querySelector('.navbar .right-menu') as HTMLElement;
    if (!rightMenu) {
      // 如果还没有找到右侧菜单，延迟重试
      if (isFirstCalculation.value) {
        setTimeout(() => calculateVisibleMenus(), 100);
      }
      return;
    }

    // 计算可用宽度：右侧菜单的左边界 - 顶部菜单的左边界 - 安全边距
    const menuLeft = menuElement.getBoundingClientRect().left;
    const rightMenuLeft = rightMenu.getBoundingClientRect().left;
    const safeMargin = 20; // 安全边距，避免紧贴
    const availableWidth = Math.max(100, rightMenuLeft - menuLeft - safeMargin); // 最小宽度100px

    if (DEBUG_MODE) {
      console.log('[TopNav] 计算可用宽度:', {
        menuLeft,
        rightMenuLeft,
        safeMargin,
        availableWidth,
        menuCount: topMenus.value.length
      });
    }

    let accumulatedWidth = 0;
    let visibleCount = 0;

    // 临时将所有菜单设为可见以测量宽度
    if (isFirstCalculation.value) {
      visibleNumber.value = topMenus.value.length;
      nextTick(() => {
        calculateActualWidths();
      });
      return;
    }

    calculateActualWidths();

    function calculateActualWidths() {
      const menuItems = menuElement.querySelectorAll('.el-menu-item:not(.is-disabled)');
      // "更多"按钮的大概宽度（包含margin和padding）
      const moreButtonWidth = 100;
      
      for (let i = 0; i < menuItems.length && i < topMenus.value.length; i++) {
        const item = menuItems[i] as HTMLElement;
        // 获取包含 margin 的实际宽度
        const itemWidth = item.offsetWidth + 20; // 20px 是左右 margin (0 10px)
        
        // 如果不是最后一项，且剩余空间不足以容纳当前项+更多按钮，则停止
        if (i < topMenus.value.length - 1) {
          if (accumulatedWidth + itemWidth + moreButtonWidth <= availableWidth) {
            accumulatedWidth += itemWidth;
            visibleCount++;
          } else {
            break;
          }
        } else {
          // 最后一项，直接判断是否有空间
          if (accumulatedWidth + itemWidth <= availableWidth) {
            accumulatedWidth += itemWidth;
            visibleCount++;
          }
        }
      }

      // 如果所有菜单都能显示，则不需要"更多"按钮
      if (visibleCount >= topMenus.value.length) {
        visibleNumber.value = topMenus.value.length;
      } else {
        // 确保至少显示一个菜单项
        visibleNumber.value = Math.max(1, visibleCount);
      }

      if (DEBUG_MODE) {
        console.log('[TopNav] 计算结果:', {
          totalMenus: topMenus.value.length,
          visibleCount,
          visibleNumber: visibleNumber.value,
          accumulatedWidth,
          availableWidth
        });
      }

      isFirstCalculation.value = false;
    }
  });
};

const handleSelect = (key: string) => {
  currentIndex.value = key;
  const route = routers.value.find((item) => item.path === key);
  if (isHttp(key)) {
    // http(s):// 路径新窗口打开
    window.open(key, '_blank');
  } else if (!route || !route.children) {
    // 没有子路由路径内部打开
    const routeMenu = childrenMenus.value.find((item) => item.path === key);
    if (routeMenu && routeMenu.query) {
      const query = JSON.parse(routeMenu.query);
      router.push({ path: key, query: query });
    } else {
      router.push({ path: key });
    }
    appStore.toggleSideBarHide(true);
  } else {
    // 显示左侧联动菜单
    activeRoutes(key);
    appStore.toggleSideBarHide(false);
  }
};

const activeRoutes = (key: string) => {
  const routes: RouteRecordRaw[] = [];
  if (childrenMenus.value && childrenMenus.value.length > 0) {
    childrenMenus.value.map((item) => {
      if (key == item.parentPath || (key == 'index' && '' == item.path)) {
        routes.push(item);
      }
    });
  }
  if (routes.length > 0) {
    permissionStore.setSidebarRouters(routes);
  } else {
    appStore.toggleSideBarHide(true);
  }
  return routes;
};

// 监听窗口大小变化
onMounted(() => {
  // 使用防抖优化性能
  let resizeTimer: any = null;
  const handleResize = () => {
    if (resizeTimer) {
      clearTimeout(resizeTimer);
    }
    resizeTimer = setTimeout(() => {
      isFirstCalculation.value = true;
      calculateVisibleMenus();
    }, 200);
  };
  
  window.addEventListener('resize', handleResize);
  
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
    if (resizeTimer) {
      clearTimeout(resizeTimer);
    }
  });
});

// 初始化计算
onMounted(() => {
  calculateVisibleMenus();
});

// 监听菜单变化和语言切换，重新计算
watch([topMenus, locale], () => {
  isFirstCalculation.value = true;
  calculateVisibleMenus();
}, { deep: true });

// 监听侧边栏展开/收起状态变化，重新计算菜单宽度
watch(sidebarOpened, () => {
  // 使用 setTimeout 等待侧边栏动画完成（transition 时间约 0.28s）
  setTimeout(() => {
    isFirstCalculation.value = true;
    calculateVisibleMenus();
  }, 300);
});

// 监听侧边栏隐藏状态变化
watch(sidebarHide, () => {
  setTimeout(() => {
    isFirstCalculation.value = true;
    calculateVisibleMenus();
  }, 300);
});

// 监听顶部导航模式切换
watch(topNav, (newVal) => {
  if (newVal) {
    // 切换到顶部导航模式时，延迟计算确保 DOM 已更新
    nextTick(() => {
      isFirstCalculation.value = true;
      calculateVisibleMenus();
    });
  }
});

// 监听路由变化，因为切换菜单可能影响布局
watch(() => route.path, () => {
  // 路由变化时使用防抖计算
  nextTick(() => {
    debouncedCalculateVisibleMenus(150);
  });
});

// 清理定时器
onBeforeUnmount(() => {
  if (calculateTimer) {
    clearTimeout(calculateTimer);
  }
});
</script>

<style lang="scss">
.topmenu-container.el-menu--horizontal > .el-menu-item {
  float: left;
  height: 50px !important;
  line-height: 50px !important;
  color: #999093 !important;
  padding: 0 5px !important;
  margin: 0 10px !important;
}

.topmenu-container.el-menu--horizontal > .el-menu-item.is-active,
.el-menu--horizontal > .el-sub-menu.is-active .el-submenu__title {
  border-bottom: 2px solid #{'var(--theme)'} !important;
  color: #303133;
}

/* sub-menu item */
.topmenu-container.el-menu--horizontal > .el-sub-menu .el-sub-menu__title {
  float: left;
  height: 50px !important;
  line-height: 50px !important;
  color: #999093 !important;
  padding: 0 5px !important;
  margin: 0 10px !important;
}

/* 背景色隐藏 */
.topmenu-container.el-menu--horizontal > .el-menu-item:not(.is-disabled):focus,
.topmenu-container.el-menu--horizontal > .el-menu-item:not(.is-disabled):hover,
.topmenu-container.el-menu--horizontal > .el-submenu .el-submenu__title:hover {
  background-color: #ffffff !important;
}

/* 图标右间距 */
.topmenu-container .svg-icon {
  margin-right: 4px;
}
</style>
