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

<script>
import { ref, watch, computed } from 'vue';
import { useRoute } from 'vue-router';

export default {
  name: 'Breadcrumb',
  setup() {
    const route = useRoute();
    const breadcrumbs = ref([]);

    // 匹配路由路径对应的名称
    const routeMap = {
      '/': '首页',
      '/category': '分类',
      '/ranking': '排行榜',
      '/bookshelf': '书架',
      '/user/center': '个人中心',
      '/book': '书籍详情',
      '/notice': '公告详情'
    };

    // 计算面包屑
    const getBreadcrumbs = (path) => {
      const result = [];
      
      // 首页始终是第一个面包屑
      result.push({
        path: '/',
        title: '首页'
      });

      if (path === '/') return result;

      const paths = path.split('/').filter(Boolean);
      let currentPath = '';

      paths.forEach((segment, index) => {
        currentPath += '/' + segment;
        
        // 处理动态路由参数
        if (segment.match(/^\d+$/)) {
          // 如果是数字参数，使用前一段路由的基本名称
          if (index > 0) {
            const basePath = '/' + paths[index - 1];
            result.push({
              path: currentPath,
              title: routeMap[basePath] || segment
            });
          }
        } else {
          const exactPath = Object.keys(routeMap).find(key => key === currentPath);
          const basePath = Object.keys(routeMap).find(key => currentPath.startsWith(key) && key !== '/');
          
          result.push({
            path: currentPath,
            title: routeMap[exactPath] || routeMap[basePath] || segment
          });
        }
      });

      return result;
    };

    watch(() => route.path, (path) => {
      breadcrumbs.value = getBreadcrumbs(path);
    }, { immediate: true });

    return {
      breadcrumbs
    };
  }
};
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as vars;

.breadcrumb-container {
  margin-bottom: 20px;
  padding: 8px 0;
}
</style> 