import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import CommonRouters from './common'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {storage} from '@/utils/storage'
import config from '@/config'

Vue.use(VueRouter);

NProgress.configure({showSpinner: false}); // 禁用环形进度条

const getPageTitle = (pageTitle) => {
    return pageTitle ? `${pageTitle} - ${config.title}` : `${config.title}`
};

const getChildren = (router) => {
    let result = [];
    router.children.forEach((child) => {
        child.parent = router;
        child.path = `${child.parent.path}/${child.path}`
        if (child.parent.parent) { // 默认只显示2级菜单
            child.hidden = true;
        }
        if (child.children && child.children.length > 0) {
            result = result.concat(getChildren(child))
        }
        delete child.children
        if (router.path === "/element" && child.path === '/element/table') {
            console.log(child);
        }
        result.push(child);
        store.commit("tagsView/ADD_CACHED_VIEW", child);
    })
    return result;
}

// 将2级菜以下菜单放入2级菜单同级目录,这样可以使2级菜单可点击.
// 为保证navBar的正确性所有配置菜单时,按照navBar的逻辑配置菜单
 const  getRoutes = () => {
    return require('./modules/'+config.appName).default.concat(CommonRouters).map(router => {
        if (router.children) {
            router.children = getChildren(router)
        }
        store.commit("tagsView/ADD_CACHED_VIEW", router);
        return router
    })
}

const createRouter = () => {
    return new VueRouter({
        routes: getRoutes(),
        mode: 'history', // require service support
        base: process.env.BASE_URL,
        scrollBehavior: (to, from, savedPosition) => {
            if (to.hash)
                return {selector: to.hash}
        },
    })
};

const router = createRouter();

router.beforeEach(async (to, from, next) => {
        // 开始进度条
        NProgress.start();

        // 设置页面标题
        document.title = getPageTitle(to.meta.title);

        // cacheParam(from, to)

        // 确定用户是否已登录
        const hasToken = storage.getToken();
        if (hasToken) {
            console.log('账户啊哈哈哈',to)
            if (to.path === '/login') { // 如果已经登录则转发到首页
                next({path: '/'});
            } else {
                // 无权限检查：有权限定义，并且用户没有该权限
                if (to.meta && to.meta.permissions) {
                    let permissions = to.meta.permissions.split(",");
                    const hasPermissions = permissions.some(role => {
                        return storage.getPermissions().includes(role)
                    })
                    if (hasPermissions) {
                        next();
                    } else {
                        next({path: '/'});
                    }
                } else {
                    next();
                }
            }
        } else {
            if (to.meta && to.meta.whitelist) { // 白名单，免登录
                next()
            } else {
                next(`/login?redirect=${to.fullPath}`); // 其他页跳转到登录页，并携带转发信息
            }
        }
        NProgress.done();
    }
);

router.afterEach(() => {
    NProgress.done() // 完成进度栏
});

function cacheParam(from, to) {
    if (Object.keys(to.params).length > 0) {
        storage.setData(to.name, to.params);
    }
    storage.removeData(from.name)
}

export function resetRouter() {
    const newRouter = createRouter();
    router.matcher = newRouter.matcher; // 重置路由器
}

// 解决重复跳转同一个路由时的 NavigationDuplicated 问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
};
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
};
export default router

