<template>
  <el-breadcrumb class="h-[50px] flex items-center">
    <transition-group name="breadcrumb-transition">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="item.path">
        <span v-if="item.redirect === 'noredirect' || index === breadcrumbs.length - 1" class="text-[var(--el-disabled-text-color)]">
          {{ translateRouteTitle(item.meta.title) }}
        </span>
        <a v-else @click.prevent="handleLink(item)">
          {{ translateRouteTitle(item.meta.title) }}
        </a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script setup>
import { get } from 'lodash-es'
import { onBeforeMount, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { compile } from 'path-to-regexp'
import { translateRouteTitle } from '@/utils/i18n'
import router from '@/router'
import { UserStore } from '@/store/user'
const userStore = UserStore()
const menus = computed(() => userStore.menus)

const currentRoute = useRoute()
const pathCompile = (path) => {
  const { params } = currentRoute
  const toPath = compile(path)
  return toPath(params)
}

const breadcrumbs = ref([])

function getBreadcrumb() {
  let matched = currentRoute.matched.filter((item) => item.meta && item.meta.title)
  let menus = matched.map((i) => getMenu(i))
  const first = menus[0]
  if (!isDashboard(first)) {
    menus = [{ path: '/', meta: { title: '首页' } }].concat(matched)
  }
  breadcrumbs.value = menus.filter((item) => {
    return item.meta && item.meta.title && item.meta.breadcrumb !== false
  })
}

const getMenu = (route) => {
  const menu = menus.value.find((f) => f.path === route.path)
  if (menu) route.meta.title = get(menu, 'name')
  return route
}

function isDashboard(route) {
  return route.path === '/'
}

function handleLink(item) {
  const { redirect, path, meta } = item
  if (meta.type == '0') return
  if (redirect) {
    router.push(redirect).catch((err) => {
      console.warn(err)
    })
    return
  }
  router.push(pathCompile(path)).catch((err) => {
    console.warn(err)
  })
}

watch(
  () => currentRoute.path,
  (path) => {
    if (path.startsWith('/redirect/')) {
      return
    }
    getBreadcrumb()
  }
)

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

// 覆盖 element-plus 的样式
.el-breadcrumb__inner,
.el-breadcrumb__inner a {
  font-weight: 400 !important;
}
</style>
