import {createRouter, createWebHashHistory} from 'vue-router';
import {ElNotification} from 'element-plus';
import config from "@/config"
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import tools from '@/utils/tools'
import api from "@/api"
import sRouter from './system'
import {treeFilter, filterAsyncRouter, flatAsyncRoutes} from '@/utils/route'
import {beforeEach, afterEach, makeMenu} from '@/utils/route'
import i18n from "@/locales"

//系统路由
const routes = sRouter

const router = createRouter({
	history: createWebHashHistory(),
	routes: routes
})

//设置标题
document.title = config.APP_NAME

//判断是否已加载过动态/静态路由
let isGetRouter = false;

router.beforeEach(async (to, from, next) => {
	NProgress.start()
	//动态标题
	document.title = to.meta.title ? `${to.meta.title} - ${config.APP_NAME}` : `${config.APP_NAME}`

	let token = tools.data.get("TOKEN");
	if (to.path === "/login") {
		//删除路由(替换当前layout路由)
		router.addRoute(routes[0])
		isGetRouter = false;
		next();
		return false;
	}

	if (routes.findIndex(r => r.path === to.path) >= 0) {
		next();
		return false;
	}

	if (!token) {
		next(`/login?redirect=${to.fullPath}`);
		return false;
	}

	//整页路由处理
	if (to.meta.fullpage) {
		to.matched = [to.matched[to.matched.length - 1]]
	}

	//加载动态/静态路由
	if (!isGetRouter) {
		// 动态加载菜单
		/* @ts-ignore */
		const res = await api.auth.menu()
		/* @ts-ignore */
		tools.data.set("MENU", makeMenu(res.data.menus, 0))
		/* @ts-ignore */
		tools.data.set("PERMISSIONS", res.data.buttons)
		/* @ts-ignore */
		tools.data.set("ROLE", res.data.roles)

		let apiMenu = tools.data.get("MENU") || []
		let userInfo = tools.data.get("USER_INFO")
		let userMenu = treeFilter([], node => {
			return node.meta.role ? node.meta.role.filter(item => userInfo.role.indexOf(item) > -1).length > 0 : true
		})

		let menu = [...userMenu, ...apiMenu]
		let menuRouter = filterAsyncRouter(menu);
		menuRouter = flatAsyncRoutes(menuRouter)
		menuRouter.forEach(item => {
			router.addRoute("layout", item)
		})
		if (to.matched.length != 0) {
			router.push(to.fullPath);
		}
		isGetRouter = true;
	}
	beforeEach(to, from)
	next();
});

router.afterEach((to, from) => {
	afterEach(to)
	NProgress.done()
});

router.onError((error) => {
	NProgress.done();
	ElNotification.error({
		title: i18n.global.t('menu.routingError'),
		message: error.message
	});
});

export default router
