<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRoute, type RouteLocationMatched } from 'vue-router'

// 当路由有redirect时，面包屑不显示这条路由
const isDashboard = (route: RouteLocationMatched): boolean => {
  const name = route && route.name
  if (!name) {
    return false
  }
  return name.toString().trim().toLowerCase() === 'Home'.toLowerCase()
}

const getBreadcrumb = (route: RouteLocationMatched): { name: string, redirect?: string } => {
  if (route.meta?.title) {
    return { name: route.meta.title as string, redirect: route.redirect as string | undefined }
  }
  return { name: route.name as string }
}

const route = useRoute()
const levelList = ref<{ name: string, path?: string }[]>([])

const getBreadcrumbs = () => {
  // 只显示有meta.title且不是隐藏的路由
  const matched = route.matched.filter(item => item.meta && item.meta.title && !item.meta.hidden)
  
  // 如果第一条不是首页则添加首页
  if (matched.length > 0 && !isDashboard(matched[0])) {
    matched.unshift({
      path: '/',
      name: 'Home',
      meta: { title: '首页' }
    } as unknown as RouteLocationMatched)
  }
  
  levelList.value = matched.map(item => {
    const bread = getBreadcrumb(item)
    return { name: bread.name, path: bread.redirect || item.path }
  })
}

getBreadcrumbs()

// 监听路由变化
watch(
  () => route.path,
  () => {
    getBreadcrumbs()
  }
)
</script>

<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span v-if="index === levelList.length - 1" class="no-redirect">{{ item.name }}</span>
        <router-link v-else :to="item.path!">{{ item.name }}</router-link>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
