<script setup lang="ts">
import { createReusableTemplate } from '@vueuse/core';
import type { RouteKey } from '@elegant-router/types';
import { h } from 'vue';
import { useThemeStore } from '@/store/modules/theme';
import { useRouteStore } from '@/store/modules/route';
import { useRouterPush } from '@/hooks/common/router';
import { breadcrumbDark } from 'naive-ui';

defineOptions({
  name: 'GlobalBreadcrumb'
});

const themeStore = useThemeStore();
const routeStore = useRouteStore();
const { routerPushByKey } = useRouterPush();

interface BreadcrumbContentProps {
  breadcrumb: App.Global.Menu;
}

const [DefineBreadcrumbContent, BreadcrumbContent] = createReusableTemplate<BreadcrumbContentProps>();

function handleClickMenu(key: RouteKey) {
  routerPushByKey(key);
}
// 自定义图标渲染函数
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', style: 'width: 16px; height: 16px;' });
  }
  return h('i', { class: `fa ${menuOption.icons}`, style: 'font-size: 16px;' });
};
</script>

<template>
  <NBreadcrumb v-if="themeStore.header.breadcrumb.visible">
    <!-- define component start: BreadcrumbContent -->
    <DefineBreadcrumbContent v-slot="{ breadcrumb }">
      <div class="i-flex-y-center align-middle">
        <!-- 原代码 -->
        <!-- <component :is="breadcrumb.icon" v-if="themeStore.header.breadcrumb.showIcon" class="mr-4px text-icon" /> -->
        <!-- 新图标代码 -->
        <component :is="renderIcon(breadcrumb)" class="inline-block align-text-bottom text-16px" />
        {{ breadcrumb.label }}
      </div>
    </DefineBreadcrumbContent>
    <!-- define component end: BreadcrumbContent -->

    <NBreadcrumbItem v-for="item in routeStore.breadcrumbs" :key="item.key">
      <NDropdown v-if="item.options?.length" :options="item.options" @select="handleClickMenu">
        <BreadcrumbContent :breadcrumb="item" />
      </NDropdown>
      <BreadcrumbContent v-else :breadcrumb="item" />
    </NBreadcrumbItem>
  </NBreadcrumb>
</template>

<style scoped></style>
