<!-- src/components/Breadcrumb.vue -->
<template>
  <el-breadcrumb separator="/" class="app-breadcrumb">
    <el-breadcrumb-item :to="{ path: '/' }">{{ $t('common.home') }}</el-breadcrumb-item>
    <el-breadcrumb-item
      v-for="(item, index) in breadcrumbItems"
      :key="item.path"
      :to="isLastItem(index) ? undefined : {path: item.path}"
    >
      {{ item.name }}
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute,useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n' 
const { t } = useI18n() // 获取t函数// 导入useI18n

const route = useRoute()
const router = useRouter()

const breadcrumbItems = computed(() => {
  const items = []
  const processedPaths = new Set() // 用于跟踪已处理的路径
  // 获取匹配的路由记录
  const matchedRoutes = route.matched.filter(item => item.meta && item.meta.title)
  
  // 遍历匹配的路由，生成面包屑项
  matchedRoutes.forEach((matchedRoute) => {
    // 跳过首页 '/'
    if (matchedRoute.path === '/') return
    
    // 获取路由标题
    // 使用 $t() 函数翻译标题
    const title = t(matchedRoute.meta.title)
    
    // 构造完整路径
    let path = matchedRoute.path
    
    // 如果路径中有参数，需要替换参数
    if (route.params) {
      Object.keys(route.params).forEach(param => {
        path = path.replace(`:${param}`, route.params[param])
      })
    }
    //如果路径中有query参数，需要添加到路径中
    // if (route.query) {
    //   const queryParams = new URLSearchParams(route.query)
    //   console.log(111111111,queryParams,queryParams.toString())
    //   path += '?' + queryParams.toString()
    // }
    
    
    // 避免重复添加相同路径的项目
    if (!processedPaths.has(path)) {
      items.push({
        name: title,
        path: path,
      })
      processedPaths.add(path)
    }
  })
  
  return items
});
// 辅助函数：判断是否为最后一个面包屑项
const isLastItem = (index) => {
  return index === breadcrumbItems.value.length - 1
};
</script>

<style scoped>
.app-breadcrumb {
  padding: 20px 0 20px;
}
</style>