<template>
  <div class="breadcrumb-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index"
        :class="{ 'is-link': index < breadcrumbList.length - 1 }" @click="handleBreadcrumbClick(item, index)">
        {{ item.title }}
      </el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 关闭按钮组 -->
    <div class="breadcrumb-actions" v-if="breadcrumbList.length > 1">
      <el-dropdown trigger="click" @command="handleCloseAction">
        <el-button type="text" size="small" class="close-btn">
          <el-icon>
            <Close />
          </el-icon>
          关闭
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="close-current">关闭当前页</el-dropdown-item>
            <el-dropdown-item command="close-other" :disabled="breadcrumbList.length <= 2">关闭其他页</el-dropdown-item>
            <el-dropdown-item command="close-left" :disabled="currentIndex === 0">关闭左侧</el-dropdown-item>
            <el-dropdown-item command="close-right"
              :disabled="currentIndex === breadcrumbList.length - 1">关闭右侧</el-dropdown-item>
            <el-dropdown-item command="close-all" :disabled="breadcrumbList.length <= 1">全部关闭</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Close } from '@element-plus/icons-vue'

// 从路由实例获取所有路由配置
const router = useRouter()
const routes = router.getRoutes()
const route = useRoute()

const props = defineProps({
  homeTitle: {
    type: String,
    default: '首页'
  }
})

const emit = defineEmits(['breadcrumb-change'])

const breadcrumbList = ref([])
const currentIndex = ref(0)


  // 生成面包屑数据
  const generateBreadcrumb = () => {
    const matched = route.matched.filter(item => item.meta && item.meta.breadcrumb !== false)

    // 基础面包屑：首页
    breadcrumbList.value = [
      {
        title: props.homeTitle,
        path: '/',
        name: 'Home'
      }
    ]

    const currentRoute = route.matched[route.matched.length - 1]
    const currentPath = route.path

    // 如果有父路由配置，自动构建父子结构
    if (currentRoute && currentRoute.meta && currentRoute.meta.parentRoute) {
      const parentRouteName = currentRoute.meta.parentRoute
      
      // 查找父路由信息
      const parentRoute = routes.find(r => r.name === parentRouteName)
      if (parentRoute && parentRoute.meta && parentRoute.meta.title) {
        // 添加父级路由
        breadcrumbList.value.push({
          title: parentRoute.meta.title,
          path: parentRoute.path,
          name: parentRoute.name,
          meta: parentRoute.meta
        })
      }
    }

    // 普通路由处理（包括子页面）
    matched.forEach((record, index) => {
      // 跳过根路径（已经在上面添加了首页）
      if (record.path === '/') return

      // 如果是子页面且已经有父级，跳过重复添加
      if (index === matched.length - 1 && currentRoute && currentRoute.meta && currentRoute.meta.parentRoute) {
        // 检查当前记录是否就是父路由本身，如果是则跳过（因为上面已经添加了）
        const isParentAlreadyAdded = breadcrumbList.value.some(item => item.name === currentRoute.meta.parentRoute)
        if (isParentAlreadyAdded && record.name === currentRoute.meta.parentRoute) {
          return
        }
      }

      if (record.meta && record.meta.title) {
        let fullPath = record.path

        // 处理相对路径
        if (!fullPath.startsWith('/') && index > 0) {
          const parentPath = breadcrumbList.value[breadcrumbList.value.length - 1]?.path || ''
          if (parentPath) {
            fullPath = parentPath + (parentPath.endsWith('/') ? '' : '/') + record.path
          }
        }

        breadcrumbList.value.push({
          title: record.meta.title,
          path: fullPath,
          name: record.name,
          meta: record.meta
        })
      }
    })

    // 更新当前索引
    const currentIndexInList = breadcrumbList.value.findIndex(item => item.path === currentPath)
    currentIndex.value = currentIndexInList >= 0 ? currentIndexInList : breadcrumbList.value.length - 1
  }

// 处理面包屑点击
const handleBreadcrumbClick = (item, index) => {
  if (index < breadcrumbList.value.length - 1) {
    router.push(item.path)
  }
}

// 处理关闭操作
const handleCloseAction = (command) => {
  switch (command) {
    case 'close-current':
      closeCurrentPage()
      break
    case 'close-other':
      closeOtherPages()
      break
    case 'close-left':
      closeLeftPages()
      break
    case 'close-right':
      closeRightPages()
      break
    case 'close-all':
      closeAllPages()
      break
  }
}

// 关闭当前页
const closeCurrentPage = () => {
  if (breadcrumbList.value.length <= 1) return

  const currentPath = route.path
  const currentIndex = breadcrumbList.value.findIndex(item => item.path === currentPath)

  if (currentIndex > 0) {
    // 跳转到前一个页面
    const prevPage = breadcrumbList.value[currentIndex - 1]
    breadcrumbList.value.splice(currentIndex, 1)
    router.push(prevPage.path)
  }
}

// 关闭其他页
const closeOtherPages = () => {
  if (breadcrumbList.value.length <= 2) return

  const currentPath = route.path
  const currentItem = breadcrumbList.value.find(item => item.path === currentPath)

  if (currentItem) {
    breadcrumbList.value = [
      breadcrumbList.value[0], // 保留首页
      currentItem
    ]

    // 触发路由跳转逻辑
    emit('breadcrumb-change', breadcrumbList.value)
  }
}

// 关闭左侧页
const closeLeftPages = () => {
  if (currentIndex.value <= 1) return

  const currentItem = breadcrumbList.value[currentIndex.value]
  breadcrumbList.value = [
    breadcrumbList.value[0], // 保留首页
    currentItem
  ]

  // 如果当前不在首页，需要重新构建路径
  let targetPath = '/'
  if (currentItem.path !== '/') {
    targetPath = currentItem.path
  }
  router.push(targetPath)
}

// 关闭右侧页
const closeRightPages = () => {
  if (currentIndex.value >= breadcrumbList.value.length - 1) return

  breadcrumbList.value = breadcrumbList.value.slice(0, currentIndex.value + 1)

  // 跳转到最后一个保留的页面
  const lastItem = breadcrumbList.value[breadcrumbList.value.length - 1]
  router.push(lastItem.path)
}

// 关闭所有页（回到首页）
const closeAllPages = () => {
  breadcrumbList.value = [breadcrumbList.value[0]]
  router.push('/')
}

// 监听路由变化
watch(() => route.path, () => {
  generateBreadcrumb()
}, { immediate: true })

onMounted(() => {
  generateBreadcrumb()
})

// 暴露方法给父组件
defineExpose({
  breadcrumbList,
  refreshBreadcrumb: generateBreadcrumb
})
</script>

<style scoped lang="scss">
.breadcrumb-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 40px;
  padding: 0 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

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

    .el-breadcrumb__item {
      .el-breadcrumb__inner {
        color: #606266;
        font-weight: 400;

        &.is-link {
          color: #409eff;
          cursor: pointer;
          transition: color 0.3s;

          &:hover {
            color: #66b1ff;
          }
        }
      }

      &:last-child .el-breadcrumb__inner {
        color: #303133;
        font-weight: 500;
      }
    }
  }
}

.breadcrumb-actions {
  display: flex;
  align-items: center;

  .close-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #606266;
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      background-color: #f5f7fa;
      color: #409eff;
    }

    .el-icon {
      font-size: 12px;
    }
  }
}
</style>
