<template>
  <div class="breadcrumb-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item
        v-for="(item, index) in breadcrumbList"
        :key="index"
        :to="item.path"
      >
        {{ item.title }}
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores/modules/user'
import type { BreadcrumbItem } from '@/stores/modules/tabs'

const route = useRoute()
const userStore = useUserStore()

// 监听路由变化，直接计算面包屑
const breadcrumbList = computed<BreadcrumbItem[]>(() => {
  const path = route.path
  const list: BreadcrumbItem[] = []

  // 如果是首页，直接返回首页
  if (path === '/dashboard') {
    list.push({ title: '首页', path: '/dashboard' })
    return list
  }

  // 从菜单中查找当前路由的层级信息
  const findMenuPath = (menus: any[], targetPath: string, parentMenu: any = null): any => {
    for (const menu of menus) {
      const menuPath = menu.path || menu.api || `/menu-${menu.id}`

      if (menuPath === targetPath) {
        return { current: menu, parent: parentMenu }
      }

      const subMenus = menu.children || menu.son
      if (subMenus && subMenus.length > 0) {
        const result = findMenuPath(subMenus, targetPath, menu)
        if (result) return result
      }
    }
    return null
  }

  const menuResult = findMenuPath(userStore.sideMenu, path)

  if (menuResult) {
    const { current, parent } = menuResult

    if (parent) {
      const firstChildMenus = parent.children || parent.son
      const firstChildPath = firstChildMenus && firstChildMenus.length > 0
        ? (firstChildMenus[0].path || firstChildMenus[0].api || `/menu-${firstChildMenus[0].id}`)
        : parent.path || parent.api || `/menu-${parent.id}`

      list.push({ title: parent.label, path: firstChildPath })
    }

    list.push({
      title: current.label,
      path: current.path || current.api || `/menu-${current.id}`
    })
  }

  // 如果没有找到菜单信息，默认添加首页
  if (list.length === 0) {
    list.push({ title: '首页', path: '/dashboard' })
  }

  return list
})
</script>

<style scoped lang="scss">
.breadcrumb-container {
  display: flex;
  align-items: center;
  height: 100%;

  :deep(.el-breadcrumb) {
    font-size: 14px;
    white-space: nowrap;

    .el-breadcrumb__item {
      .el-breadcrumb__inner {
        color: var(--el-text-color-regular);
        font-weight: normal;

        &:hover {
          color: var(--el-color-primary);
        }

        &.is-link {
          color: var(--el-text-color-regular);
        }
      }

      &:last-child {
        .el-breadcrumb__inner {
          color: var(--el-text-color-primary);
          cursor: default;

          &:hover {
            color: var(--el-text-color-primary);
          }
        }
      }
    }
  }
}
</style>
