import staticRoutes from '_platform/router/staticRoutes'
import store from '_platform/store'
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
    return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
    routes: staticRoutes,
    mode: process.env.NODE_ENV === 'production' ? 'history' : 'hash'
})

router.beforeEach((to, from, next) => {
    // 如果跳转到登录页面
    if (to.name === 'login') {
        return next()
    } else if (!store.state.token) {
        return next({ path: '/' })
    } else {
        return next()
    }
})

router.afterEach(to => {
    window.scrollTo(0, 0)
})

// 解决Loading chunk chunk-4ca844f1 failed 问题
router.onError((error) => {
    const pattern = /chunk-(\w)+ failed/g
    const isChunkLoadFailed = error.message.match(pattern)
    const targetPath = router.history.pending.fullPath
    if (isChunkLoadFailed) {
        // 用路由的replace方法，并没有相当于F5刷新页面，失败的js文件并没有从新请求，会导致一直尝试replace页面导致死循环，
        // 而用 location.reload 方法，相当于触发F5刷新页面，虽然用户体验上来说会有刷新加载察觉，但不会导致页面卡死及死循环，从而曲线救国解决该问题
        location.reload()
    }
})

export default router
