import { createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { useLoginStore, useRouterStore, i18n } from '@/stores'
import dynamicRouter from './dynamicRouter'
import historyRouter from './historyRouter'
import service from '@/services'

const loginStore = useLoginStore()
const routerStore = useRouterStore()

// 获取首页地址
const getHomeUrl = () => {
    const findNode = (tree: Model.MenusRsp[]): string => {
        for (const node of tree) {
            if (node.children?.length) {
                const res = findNode(node.children)
                if (res) return res
            } else {
                return node.url
            }
        }
        return '/404'
    }
    return findNode(routerStore.filterMenus(routerStore.userRoutes))
}

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        redirect: () => loginStore.token ? getHomeUrl() : '/login', // 重定向到默认页面
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/auth/login/index.vue'),
        meta: {
            title: '登录',
            keepAlive: false
        },
    },
    {
        path: '/boot',
        name: 'boot',
        component: () => import('../views/boot/index.vue'),
        meta: {
            title: '初始化',
            keepAlive: false
        },
    }
]

// 开发环境
if (process.env.NODE_ENV === 'development') {
    routes.push({
        path: '/router',
        name: 'router',
        component: () => import('../components/layouts/page/index.vue'),
        meta: {
            title: '路由管理',
            keepAlive: true
        },
        children: [
            {
                path: 'menu',
                name: 'router_menu',
                component: () => import('../views/system/menu/index.vue'),
                meta: {
                    title: '菜单管理',
                    keepAlive: true
                }
            }
        ]
    })
}

const router = historyRouter.create({
    history: createWebHashHistory(),
    routes
})

// 路由跳转拦截
router.beforeEach((to, from, next) => {
    const isLoginOrRegister = to.name === 'login' || to.name === 'register'
    document.title = i18n.global.t('app.name')

    // 判断服务是否加载完成
    if (service.isReady) {
        if (loginStore.token) {
            if (dynamicRouter.isReady) {
                if (isLoginOrRegister) {
                    next('/')
                } else {
                    next()
                }
            } else {
                // 注册动态路由
                dynamicRouter.registerRoutes()
                next({ ...to, replace: true })
            }
        } else {
            if (isLoginOrRegister) {
                next()
            } else {
                next({
                    name: 'login',
                    query: { redirect: to.fullPath },
                })
            }
        }
    } else {
        if (to.name === 'boot' || to.name === 'login') {
            next()
        } else {
            next({
                name: 'boot',
                query: { redirect: to.fullPath },
            })
        }
    }
})

export default router
