import router from '@/router'
import { nextTick } from 'vue'
import { addActiveMenu, addCustomRoute, updateCustomRoute } from '@/utils/menu'

interface CompRouter {
    title: string
    parentRoutePath: string
    parentName: string
    path: string
    name: string
    componentUrl: any
}
/**
 *
 * @param route
 * @param compRouter  title: 路由名称，parentRoutePath: 父级路由路径，parentName: 父级路由名称，path: 路由路径，name: 路由名称，component: 路由组件地址
 * @returns
 */
export const addCompRouter = (route: CompRouter) => {
    return new Promise(async (resolve, reject) => {
        const { parentRoutePath, path, name, componentUrl } = route

        // 检查路由是否已存在的更全面方法
        const isRouteExists = (): boolean => {
            const routes = router.getRoutes()
            // 检查路由name是否已存在
            if (router.hasRoute(name)) return true

            // 检查完整路径是否已存在
            const fullPath = `${parentRoutePath}/${path}`.replace(/\/+/g, '/')

            return routes.some((r) => r.path === fullPath)
        }
        if (!isRouteExists()) {
            if (!router.hasRoute(parentRoutePath)) {
                console.error('父级路由不存在')
                reject(false)
                return
            }
            if (!componentUrl) {
                console.error('请传入要添加的路由的component')
                reject(false)
                return
            }

            // 使用 Vite 的 glob 导入来处理动态路径
            const modules = import.meta.glob('@/views/**/*.vue')
            const component = modules[componentUrl]

            if (!component) {
                console.error(`组件路径不存在: ${componentUrl}`)
                reject(false)
                return
            }

            const routeObj = {
                path,
                name,
                component
            }

            router.addRoute(parentRoutePath, routeObj)

            addCustomRoute(parentRoutePath, { path, name, componentUrl })
            addActiveMenu(route)
            await nextTick()
            resolve(true)
        } else {
            // 检查现有路由的组件是否正确
            const existingRoute = router.getRoutes().find((r) => r.name === name)
            if (existingRoute) {
                // 如果组件路径不匹配，删除旧路由并添加新路由
                const modules = import.meta.glob('@/views/**/*.vue')
                const newComponent = modules[componentUrl]
                if (newComponent && existingRoute.components?.default !== newComponent) {
                    router.removeRoute(name)
                    await nextTick()

                    const routeObj = {
                        path,
                        name,
                        component: newComponent
                    }
                    router.addRoute(parentRoutePath, routeObj)

                    // 更新 store 中的路由信息
                    updateCustomRoute(parentRoutePath, { path, name, componentUrl })
                }
            }
            resolve(true)
        }
    })
}

export const removeCompRouter = (name: string) => {
    return new Promise(async (resolve, reject) => {
        if (!router.hasRoute(name)) {
            console.error('路由不存在')
            reject(false)
        }
        router.removeRoute(name)
        await nextTick()
        resolve(true)
    })
}
