import Vue from 'vue'
import Router from 'vue-router'
import axios from '@/axios'
import store from '@/store'
import Home from '@/view/system/home/home'
import Login from '@/view/system/login/login'
import NotFound from '@/view/system/404'
import ModifyPassword from '@/components/modifyPassword'
import Main from '@/view/system/main'

Vue.use(Router)

const router = new Router({
	routes: [{
		path: '/',
		name: '登录',
		component: Login
	}, {
		path: '/login',
		name: '登录',
		component: Login
	}, {
		path: '/home',
		name: '主页',
		component: Home,
		children: [{
			path: 'modifyPassword',
			name: '修改密码',
			component: ModifyPassword,
		}, {
			path: 'main',
			name: '主页',
			component: Main
		}]
	}, {
		path: '/404',
		name: 'notFound',
		component: NotFound
	}]
})
router.beforeEach((to, from, next) => {
	//console.log('路由拦截：to.path=' + to.path)
	// 登录界面登录成功之后，会把用户信息保存在会话
	// 存在时间为会话生命周期，页面关闭即失效。
	var activePage = ''
	let user = localStorage.getItem('userId')
	let token = localStorage.getItem('token')
	if (store.state.tabsbar.activePage) {
		activePage = store.state.tabsbar.activePage.path
	} else {
		activePage = '/home/main'
	}

	if (to.path === '/') {
		// 如果是访问登录界面，如果用户会话信息存在，代表已登录过，跳转到主页
		if (token) {
			next({
				path: activePage
			})
		} else {
			next()
		}
	} else if (to.path === '/login') {
		next()
	} else {
		if (!token) {

			// 如果访问非登录界面，且户会话信息不存在，代表未登录，则跳转到登录界面
			////console.log('路由拦截：未登录，跳转到登录界面 user=' + user)
			next({
				path: '/login'
			})
		} else {
			// 加载动态菜单和路由
			//console.log('路由拦截：加载动态菜单和路由 user=' + user)
			addroute(user, to, from)
			addmenu(user, to, from)
			// 			store.commit('addTab', {
			// 				name: to.name,
			// 				ptah: to.path
			// 			});
			let flag = false
			for (let openedPage of store.state.tabsbar.openedPageList) {
				if (openedPage.path === to.path) {
					flag = true;
					store.commit('setActive', {
						name: to.name,
						path: to.path
					});
					break
				}
				//console.log("检查store已经打开的页面List" + openedPage.name)
			}
			if (!flag) {
				if (to.path === '/login') {

				} else if (to.path === '/home') {

				} else {
					//console.log("store.commit(addTab:::"+ to.name)
					store.commit('addTab', {
						name: to.name,
						path: to.path
					});
					//console.log("store.commit(setActive:::"+ to.path)
					store.commit('setActive', {
						name: to.name,
						path: to.path
					});

				}
			}
			for (let openedPage of store.state.tabsbar.openedPageList) {
				//console.log("检查store已经打开的页面List" + openedPage.name)
			}
			next()
		}
	}


	// 	if (to.path === '/home') {
	// 		addDynamicMenuAndRoutes('admin', to, from)
	// 		next()
	// 	}  else {
	// 		next()
	// 	}
})

router.onError((error) => {
	const pattern = /Loading chunk (\d)+ failed/g;
	const isChunkLoadFailed = error.message.match(pattern);
	const targetPath = router.history.pending.fullPath;
	if (isChunkLoadFailed) {
		router.replace(targetPath);
	}
})
/**
 * 加载动态菜单和路由
 */
function addroute(userId, to, from) {
	if (store.state.app.routeLoaded) {
		return
	}
	var url = 'SysParent/queryRoute.do'
	var param = {
		userId: userId
	}
	axios.get(url, param).then(response => {
		let dynamicRoutes = addDynamicRoutes(response.data)
		router.options.routes = router.options.routes.concat(dynamicRoutes)
		router.addRoutes(router.options.routes)
		store.commit('setRouteLoaded', true)
		 
	})
}


/**
 * 加载动态菜单和路由
 */
function addmenu(userId, to, from) {
	if (store.state.app.menuLoaded) {
		return
	}
	var url = 'SysParent/queryMenu.do'
	var param = {
		userId: userId
	}
	axios.get(url, param).then(response => {
		store.commit('setMenuTree', response.data)
		store.commit('setMenuLoaded', true)
	})
}



function addDynamicRoutes(menuList = [], routes = []) {

	for (var i = 0; i < menuList.length; i++) {

		if (menuList[i].children && menuList[i].children.length >= 1) {
			//temp = temp.concat(menuList[i].children)
			//console.log('i' + i + menuList[i].text)
			var temp = {
				path: menuList[i].url,
				name: menuList[i].text,
				component: Home,
				children: []
			}


			temp.children = addDynamicRoutes(menuList[i].children, temp.children)
			//temp.children = addDynamicRoutes(menuList[i].children, routes)
			routes.push(temp)
		} else if (menuList[i].url) {
			//menuList[i].url = menuList[i].url.replace(/^\//, '')
			// 创建路由配置
			const url = menuList[i].url
			const route = {
				path: menuList[i].url,
				component: null,
				//component: resolve => require([`@view/system`], resolve),
				name: menuList[i].text,
				meta: {
					keepAlive: true
				}
			}
			//////console.log(route)
			try {
				route['component'] = resolve => require([`@/view${url}`], resolve)
				//	route['component'] = resolve => require([`@/view/system/user`], resolve)
			} catch (e) {}

			routes.push(route)
		}

	}
	// 	if (temp.length >= 1) {
	// 		addDynamicRoutes(temp, routes)
	// 	} else {
	// 		// 		//console.log('动态路由加载...')
	// 		// 		//console.log(routes)
	// 		// 		//console.log('动态路由加载完成.')
	// 	}

	return routes
}

export default router
