import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'

/**
 * 路由监听器
 * @returns {object} selectedKey - 当前选中的菜单项及其父级
 */
export function useRouteListener() {
    const route = useRoute()
    
    // 计算当前路径及其所有父级路径
    const getRouteHierarchy = (path) => {
        const segments = path.split('/').filter(Boolean)
        return segments.map((_, index) => '/' + segments.slice(0, index + 1).join('/'))
    }
    
    const selectedKey = ref(getRouteHierarchy(route.path))

    // 监听路径变化并更新选中项
    watch(() => route.path, (newPath) => {
        selectedKey.value = getRouteHierarchy(newPath)
    })

    return { selectedKey }
}
