import Vue from 'vue';
import VueRouter from 'vue-router';
import Store from '@/store/index';
import RouterPlugin from './plugin';
import { viewRoutes, pageRoutes } from './routes/index';
import { routerMode, env } from '@/config/env';

Vue.use(VueRouter);

const Router = new VueRouter({
	mode: routerMode || 'history',
	base: env.BASE_URL,
	scrollBehavior(to, from, savedPosition) {
		if (savedPosition) {
			return savedPosition;
		} else {
			return { x: 0, y: 0 };
		}
	},
	routes: [...pageRoutes]
});

// Add process
Router.beforeEach((to, from, next) => {
	if (Store.state.user.token) {
		const errorPage = ['/404', '/403', '/500', '/503'];
		const routes = [...viewRoutes, ...Store.state.menu.routes];

		if (!errorPage.includes(to.path)) {
			const deep = list => {
				return list.find(e => (e.type === 0 ? deep(e.children) : e.path == to.path));
			};

			if (deep(routes)) {
				Store.commit('ADD_PROCESS', {
					label: to.name,
					value: to.path
				});
			} else {
				return next('/404');
			}
		}
	} else {
		if (!to.path.includes('/login')) {
			return next('/login');
		}
	}

	next();
});

// Remove Navigating to current location (XXX) is not allowed
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
	return routerPush.call(this, location).catch(error => error);
};

RouterPlugin.install(Vue, Router, Store);
Router.$plugin.addRoutes(viewRoutes);

export default Router;
