<script setup lang="ts">
import { computed, h } from 'vue';
import { useRoute } from 'vue-router';
import { GLOBAL_HEADER_MENU_ID, GLOBAL_SIDER_MENU_ID } from '@/constants/app';
import { useAppStore } from '@/store/modules/app';
import { useThemeStore } from '@/store/modules/theme';
import { useRouterPush } from '@/hooks/common/router';
import FirstLevelMenu from '../components/first-level-menu.vue';
import { useMixMenuContext } from '../../../context';

defineOptions({
  name: 'HorizontalMixMenu'
});

const route = useRoute();
const appStore = useAppStore();
const themeStore = useThemeStore();
const { allMenus, childLevelMenus, activeFirstLevelMenuKey, setActiveFirstLevelMenuKey } = useMixMenuContext();
const { routerPushByKeyWithMetaQuery } = useRouterPush();

const selectedKey = computed(() => {
  const { hideInMenu, activeMenu } = route.meta;
  const name = route.name as string;

  const routeName = (hideInMenu ? activeMenu : name) || name;

  return routeName;
});

function handleSelectMixMenu(menu: App.Global.Menu) {
  setActiveFirstLevelMenuKey(menu.key);

  if (!menu.children?.length) {
    routerPushByKeyWithMetaQuery(menu.routeKey);
  }
}
// 自定义图标渲染函数
const renderIcon = (menuOption: any) => {
  if (!menuOption.icon) return null; // 没有图标时返回空
  const icon = String(menuOption.icons); // 确保 icon 是字符串
  if (icon.startsWith('/')) {
    // 如果图标以/开头，加上域名并以img形式展示
    const origin = window.location.origin;
    origin.split('/').slice(0, 3).join('/');
    const iconUrl = `${origin}${icon}`;
    // const iconUrl = `http://localhost:80${icon}`;

    return h('img', { src: iconUrl, alt: 'icon', class: 'menu-icon' });
  }
  return h('i', { class: `fa ${menuOption.icons}` });
};
</script>

<template>
  <Teleport :to="`#${GLOBAL_HEADER_MENU_ID}`">
    <NMenu
      mode="horizontal"
      :value="selectedKey"
      :options="childLevelMenus"
      :indent="18"
      responsive
      :render-icon="renderIcon"
      @update:value="routerPushByKeyWithMetaQuery"
    ></NMenu>
  </Teleport>
  <Teleport :to="`#${GLOBAL_SIDER_MENU_ID}`">
    <FirstLevelMenu
      :menus="allMenus"
      :active-menu-key="activeFirstLevelMenuKey"
      :sider-collapse="appStore.siderCollapse"
      :dark-mode="themeStore.darkMode"
      :theme-color="themeStore.themeColor"
      :render-icon="renderIcon"
      @select="handleSelectMixMenu"
      @toggle-sider-collapse="appStore.toggleSiderCollapse"
    ></FirstLevelMenu>
  </Teleport>
</template>

<style scoped></style>
