import VueRouter from "vue-router"
import store from "@/store"

const routes = [
    {
        path: '/',
        name: 'Index',
        component: () => import(/* webpackChunkName: "index" */ '@/pages/index/index'),
        meta: {
            title: '首页',
            keepAlive: true,
            requireAuth: true
        }
    }, {
        path: '/auth',
        component: () => import(/* webpackChunkName: "auth" */ '@/pages/layouts/common'),
        children: [
            {
                path: 'login',
                name: 'AuthLogin',
                component: () => import(/* webpackChunkName: "auth" */ '@/pages/auth/login'),
                meta: {
                    title: '登录'
                }
            }, {
                path: 'verify',
                name: 'AuthVerify',
                component: () => import(/* webpackChunkName: "auth" */ '@/pages/auth/verify'),
                meta: {
                    title: '验证手机号'
                }
            }
        ]
    }
];

const router = new VueRouter({
    mode: 'history',
    routes
});

router.beforeEach((to, from, next) => {
    let hasLogin = store.state.hasLogin;
    console.log('ROUTE' + to.name + '||' + hasLogin)
    if (to.name === 'AuthLogin') {
        // 如果已经登录，直接跳转到首页去
        if (hasLogin) {
            next({
                name: 'Index'
            });
            return
        }

        let tk = localStorage.getItem('accessToken')

        if (tk) {
            store.commit('login', tk);
            next({
                name: 'Index'
            });
            return
        }
    } else if (to.meta.requireAuth === true) {
        if (hasLogin === false) {
            next({
                name: 'AuthLogin',
                params: {
                    next: to.path
                }
            });
            return
        }
    }
    store.state.showFooter = to.meta.showFooter || false;

    next()
});

export default router