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

const joinRoutePath = (parentPath, routePath) => {
    const base = parentPath.endsWith('/') ? parentPath.slice(0, -1) : parentPath
    const segment = routePath.startsWith('/') ? routePath : `/${routePath}`
    return `${base}${segment}`.replace(/\/+/g, '/')
}

const buildRouteMenuKeyMap = (routeList, parentPath = '', map = {}) => {
    routeList.forEach((route) => {
        const fullPath = joinRoutePath(parentPath, route.path)

        if (route.children?.length > 0) {
            const childPrefix = fullPath.endsWith('/') ? fullPath : `${fullPath}/`
            const visibleChildren = route.children.filter((child) => !child.meta?.hideInMenu)

            if (route.meta?.flatMenu && visibleChildren.length === 1) {
                const child = visibleChildren[0]
                const menuKey = joinRoutePath(childPrefix, child.path)
                if (route.name) map[route.name] = menuKey
                if (child.name) map[child.name] = menuKey
            }

            buildRouteMenuKeyMap(route.children, childPrefix, map)
        }

        if (route.name && !route.meta?.hideInMenu && !map[route.name]) {
            map[route.name] = fullPath
        }
    })

    return map
}

const routeMenuKeyMap = buildRouteMenuKeyMap(routes)

const getRouteHierarchy = (path) => {
    const segments = path.split('/').filter(Boolean)
    return segments.map((_, index) => '/' + segments.slice(0, index + 1).join('/'))
}

const resolveActiveMenuPath = (route) => {
    const leaf = route.matched[route.matched.length - 1]
    const routeName = leaf?.meta?.parent || route.name

    if (routeName && routeMenuKeyMap[routeName]) {
        return routeMenuKeyMap[routeName]
    }

    return route.path
}

/**
 * 路由监听器
 * @returns {object} selectedKey - 当前选中的菜单项及其父级
 */
export function useRouteListener() {
    const route = useRoute()

    const selectedKey = ref(getRouteHierarchy(resolveActiveMenuPath(route)))

    watch(
        () => [route.path, route.name, route.matched.length],
        () => {
            selectedKey.value = getRouteHierarchy(resolveActiveMenuPath(route))
        }
    )

    return { selectedKey }
}
