import * as vueRouter from 'vue-router'
import baseData from "./modules/base";
import {getToken} from '~src/api/util/auth'
import {getRouterData, getTokenRouter} from './routers'
import NProgress from "nprogress";
import "~src/styles/app/nprogress.scss";
import {getStoreValue} from "~uti/storage";
import website from '~src/config/index'

//设置路由数据
const router = vueRouter.createRouter({
    history: vueRouter.createWebHashHistory(),
    routes: baseData
});

//路由拦截
router.beforeResolve(async (to) => {
    NProgress.start();
    const token = getToken()

    if (to.path === '/login') {
        return true
    } else if (to.path === '/auth') {
        return true
    } else if (!token) {
        return '/login'
    } else if (getTokenRouter(to.path)) {
        return true
    } else {
        //判断角色组
        const projectId = getStoreValue('projectId')
        const role_id = getStoreValue('role_id')
        if (role_id === website.role_id) {
            //如果等于总管理，判断项目ID（总管理时，进入其他页面，必须先选择项目）
            if (!projectId) {
                window.$message?.warning('请先选择项目');
                return '/user/project'
            } else {
                const res = await getRouterData(to.name)
                if (res) {
                    return true
                } else {
                    return '/login'
                }
            }
        } else {
            const res = await getRouterData(to.name)
            if (res) {
                return true
            } else {
                return '/login'
            }
        }
    }
})

router.afterEach((to) => {
    //根据当前跳转的路由设置显示在浏览器标签的title
    let pageTitle = to.meta['title'];
    if (to.path !== "/") {
        window.document.title =  pageTitle ? pageTitle : '';
    } else {
        window.document.title = '';
    }
    window.scrollTo(0, 0)
    NProgress.done();
})

export function setupRouter(app){
    app.use(router)
    return router
}

export default router;
