import router from '@/router';
import store from '@/store';
// import { title as settingsTitle } from '@/settings'
import { checkSignedInStatus, setNotLoggedIn } from '@/utils/auth';

let loadedDynamicRoutes = false; // 是否已加载动态路由
const whiteList = ['/login'];
router.beforeEach(async (to, from, next) => {
	// 网页title跟随路由title
	document.title = 'OPS' + '-' + to.meta.title;
	if (checkSignedInStatus()) {
		// 身份验证通过
		if (to.path !== '/login') {
			// 不在登录页面，正常进入相应页面
			if (loadedDynamicRoutes) {
				store.dispatch('topNavTag/addNavTag', to); // 顶部页面标签处理
				console.log(
					to.path,
					'==================to,path================'
				);

				next();
			} else {
				try {
					// 获取用户信息
					await store.dispatch('user/getUserInfo');

					// 获取用户权限列表
					const authList = store.getters['user/getUserAuthList'];

					// 获取用户有权限操作权限的路由
					const accessRoutes = await store.dispatch(
						'routes/generateRoutes',
						authList
					);

					// 动态添加路由
					handleDynamicRoutes(accessRoutes).forEach((route) => {
						router.addRoute(route);
					});
					//404最后添加，不然会导致路由混乱
					router.addRoute({
						path: '/:pathMatch(.*)*',
						redirect: '/404',
					});
					// 设为已加载动态路由
					loadedDynamicRoutes = true;

					// 确保动态添加的路由已经被完全加载上去并替换浏览器路由使浏览器没有浏览历史可回退
					next({
						...to,
						replace: true,
					});
				} catch (error) {
					// 设为非登录状态
					setNotLoggedIn();
					next('/login');
				}
			}
		} else {
			// 在登录页面
			next({
				path: '/',
			});
		}
	} else {
		// 身份验证不过
		// 设为非登录状态
		setNotLoggedIn();
		if (whiteList.indexOf(to.path) !== -1) {
			// 处于不用登录页面
			next();
		} else {
			next('/login');
		}
	}
});

// 处理动态路由
function handleDynamicRoutes(routes) {
	const result = [];
	routes.forEach((route) => {
		if (route.children) {
			route.children = recursionReduce(route.children);
		}
		result.push(route);
	});
	return result;
}

// 递归还原
function recursionReduce(data) {
	let result = [];
	data.forEach((it) => {
		if (it.children) {
			result = result.concat(recursionReduce(it.children));
			delete it.children;
		}
		result.push(it);
	});
	return result;
}
