/**
 * @description 所有人可使用的参数配置列表
 * @params hideMenu: 是否隐藏当前路由结点不在导航中展示
 * @params alwaysShow: 只有一个子路由时是否总是展示菜单，默认false
 */
import {createRouter, createWebHistory} from 'vue-router'
import store from '@/store'
import NProgress from '@/utils/system/nprogress'
import {changeTitle} from '@/utils/system/title'

// 动态路由相关引入数据
// 引入modules
import Dashboard from './modules/dashboard'
import System from './modules/system'

let modules = [...Dashboard]

const routes = modules

const router = createRouter({
    history: createWebHistory(),
    routes,
})

let routesAsynced = false

const vueFile = import.meta.glob('/src/views/**/*.vue')

//   这个方法可以动态添加 路由
function text() {
    let a = [{
        path: 'test',
        component: '/src/views/settings/Test.vue',
        title: '测试页面',
        icon: 'iconfont icon-dianhua'
    }]
    a.forEach(item => {
        let data = {
            path: '/' + item.path,
            name: item.title,
            meta: {
                title: item.title
            },
            component: vueFile[`${item.component}`]
        }
        router.addRoute(data)
    })
}

export function addRoutes() {
    text()
    let modules = [...Dashboard]
    System.forEach((item) => {
        modules.push(item)
        router.addRoute(item)
    })
    routesAsynced = true
}

const whiteList = ['/login', '/dashboard', '/404', '/401', '/', '/triageRoomScreen']

router.beforeEach((to, _from, next) => {
    if (to.meta.passRule) {
        to.meta.title ? changeTitle(to.meta.title) : ''
        next()
        return
    } else if (to.meta.blankPage) {
        to.meta.title ? changeTitle(to.meta.title) : ''
        next(to.query.path)
        return
    }
    if (to.meta.parent) {
        to.meta.title ? changeTitle(to.meta.title) : ''
        next(to.meta.parent)
        return
    }
    if (whiteList.indexOf(to.path) === -1) {
        const userPaths = [...store.state.user.paths]
        const toPathArr = to.path.split('/')
        const target = toPathArr[toPathArr.length - 1]
        // if (userPaths.indexOf(target) === -1 && userPaths.indexOf('/' + target) === -1) {
        //     next('/401')
        // }
    }
    NProgress.start()
    if (!routesAsynced) {
        addRoutes()
    }
    if (store.state.user.token || whiteList.indexOf(to.path) !== -1) {
        to.meta.title ? changeTitle(to.meta.title) : '' // 动态title
        next()
    } else {
        next('/login') // 全部重定向到登录页
        to.meta.title ? changeTitle(to.meta.title) : '' // 动态title
    }
})

router.afterEach((to, _from) => {
    const keepAliveComponentsName = store.getters['keepAlive/keepAliveComponentsName'] || []
    const name = to.matched[to.matched.length - 1].components.default.name
    if (to.meta && to.meta.cache && name && !keepAliveComponentsName.includes(name)) {
        store.commit('keepAlive/addKeepAliveComponentsName', name)
    }
    NProgress.done()
})

export {modules}

export default router
