import {
	createRouter,
	createWebHashHistory
} from "vue-router"
import {
	useSettingsStore
} from "@/stores/settings"
import {
	useMenuStore
} from "@/stores/menu"
import {
	useTabsBarStore
} from "@/stores/tabsbar"
import axios from '@/axios'

const routes = [{
		path: '/',
		name: 'dist',
		component: () => import('@/views/frame/login.vue'),

	},
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/frame/login.vue'),
	},
	{
		path: '/application',
		name: 'application',
		component: () => import('@/views/frame/applications.vue'),
	},
	{
		path: '/home',
		name: '主页',
		component: () => import('@/views/frame/home.vue'),
		children: [{
			path: '/main',
			name: '主页',
			component: () => import('@/views/frame/main.vue'),
		}, {
			path: '/userInfo',
			name: '个人信息',
			component: () => import('@/views/frame/userInfo.vue'),
			meta: {
				name: '个人信息',
			}
		}, {
			path: '/workflow/detail',
			name: '流程详情',
			component: () => import('@/views/workflow/detail.vue'),
			meta: {
				name: '流程详情',
			}
		}, {
			path: '/schedule',
			name: '待办中心',
			component: () => import('@/views/frame/Schedule.vue'),
			meta: {
				name: '待办中心',
			}
		}, ],
		meta: {
			name: '主页',
		}
	},
	{
		path: '/formdesigner',
		name: 'formdesigner',
		component: () => import('@/views/frame/formdesigner.vue'),
	},

	// {
	// 	name: '404',
	// 	path: '/:pathMatch(.*)*',
	// 	component: () => import(`@/views/frame/404.vue`)
	// }
]


const router = createRouter({
	history: createWebHashHistory('/'),
	routes
})
router.beforeEach(async (to, from, next) => {
	console.log('路由拦截：to.path=' + to.path)
	const menu = useMenuStore()
	const settings = useSettingsStore()
	const tabsBar = useTabsBarStore()


	var activePage = ''
	let user = localStorage.getItem('userId')
	let token = localStorage.getItem('token')
	localStorage.setItem('menuId', to.meta.id)
	// if (tabsBar.activePage) {
	// 	activePage == tabsBar.activePage.path
	// } else {
	// 	activePage = '/main'
	// }


	if (to.path == '/' || to.path == '/login') {
		// console.log('to /')
		next()
		return
	} else if (to.path == '/home') {
		next({
			path: '/main'
		})
		return
	} else if (to.path == '/workflow/detail' && to.query.from == 'oa') {
		//localhost:5173/#/workflow/detail?userId=2&from=oa&flowId=1&workId=2&trackId=3 
		var url = 'framework/SysLogin/queryPublicKeyToken'
		var param = {
			param: to.query.userId,
		}
		await axios.post(url, param).then(response => {
			menu.setMenuLoaded(false)
			menu.setRouteLoaded(false)
			localStorage.setItem('publicKey', response.data.data.publicKey)
			localStorage.setItem('userId', response.data.data.id)
			localStorage.setItem('userCode', response.data.data.userCode)
			localStorage.setItem('userName', response.data.data.userName)
			localStorage.setItem('userDesc', response.data.data.userDesc)
			localStorage.setItem('userType', response.data.data.userType)
			localStorage.setItem('token', response.data.data.token)
			token = response.data.data.token
			localStorage.setItem('belongId', response.data.data.belongId)
			localStorage.setItem('applications', JSON.stringify(response.data.data
				.applications))
			localStorage.setItem('application', JSON.stringify(response.data.data.applications[
				0]))

			sessionStorage.setItem('workflowQuery', JSON.stringify({
				flowId: to.query.flowId,
				workId: to.query.workId,
				trackId: to.query.trackId,
				date: new Date().getTime()
			}))
		})
		next() 
	} else if (to.path == '/application' || to.path == '/test') {
		next()
		return
	}

	if (!token || token == '') {
		next({
			path: '/',
			replace: true
		})
		return
	}


	// console.log('路由拦截：menu.routeLoaded=' + menu.routeLoaded)
	// console.log('路由拦截：menu.menuLoaded=' + menu.menuLoaded)
	//刷新时加载
	if (!menu.menuLoaded) {
		await addmenu(menu)
	}

	let flag = false
	for (let openedPage of tabsBar.openedPageList) {
		if (openedPage.path == to.path) {
			flag = true;
			tabsBar.setActive({
				name: to.meta.name,
				path: to.path
			});
			break
		}
	}
	// console.log('路由拦截：tabsBar.openedPageList=' + JSON.stringify(tabsBar.openedPageList))
	// console.log('路由拦截：tabsBar.activePage=' + JSON.stringify(tabsBar.activePage))
	// console.log('路由拦截：flag=' + flag)
	if (!flag) {
		tabsBar.addTab({
			name: to.meta.name,
			path: to.path
		})
		tabsBar.setActive({
			name: to.meta.name,
			path: to.path
		})
	}

	//刷新后 异步重新获取路由 改为同步执行，执行完必须紧跟next  防止刷新白屏
	if (!menu.routeLoaded) {
		await addroute(menu)
		next({
			...to,
			replace: true
		})
		return
	}

	// console.log('路由拦截 结束')

	// console.log('路由拦截：menu.routeLoaded=' + menu.routeLoaded)
	// console.log('路由拦截：menu.menuLoaded=' + menu.menuLoaded)


	// console.log('router.getRoutes()：：：' + router.getRoutes().length)
	// console.log('router.getRoutes()：：：' + JSON.stringify(router.getRoutes()))
	next()


})

router.onError((error) => {
	console.log("router Error")
	console.log(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);
	}
})


/**
 * 加载动态菜单和路由
 */
async function addroute(menu, userId, to, from) {
	return new Promise((resolve, reject) => {
		// var url = 'framework/SysParent/queryRoute'
		var applicationId = JSON.parse(localStorage.getItem('application')).id
		// console.log('addroute applicationId:' + applicationId)
		var url = 'framework/SysParent/queryRouteByUserIdAppId'
		var param = {
			applicationId: applicationId
		}
		axios.get(url, param).then(response => {
			let dynamicRoutes = addDynamicRoutes(response.data.data)
			// console.log('dynamicRoutes：：：' + dynamicRoutes.length)
			for (let route of dynamicRoutes) {
				// console.log('route: ' + route)
				router.addRoute(route)
			}
			// console.log(router)
			menu.setRouteLoaded(true)
			resolve(true)
		})
	})
}


/**
 * 加载动态菜单和路由
 */
async function addmenu(menu, userId, to, from) {
	return new Promise((resolve, reject) => {
		// var url = 'framework/SysParent/queryLeftMenu'
		var applicationId = JSON.parse(localStorage.getItem('application')).id
		var url = 'framework/SysParent/queryLeftMenuByUserIdAppId'
		var param = {
			applicationId: applicationId
		}
		axios.get(url, param).then(response => {
			// console.log('123')
			// console.log(response.data.data)
			menu.setMenuTree(response.data.data)
			menu.setMenuLoaded(true)
			resolve(true)
		})
	})
}

// name使用id  防止重名菜单导致路由无法使用
function addDynamicRoutes(menuList = [], routes = []) {
	//vite 必须加载所有文件
	const modules = import.meta.glob('../views/**/*.vue')
	for (let item of menuList) {
		if (item.children && item.children.length >= 1) {
			var temp = {
				path: item.url,
				name: item.id,
				component: () => import('@/views/frame/home.vue'),
				children: [],
				meta: {
					id: item.id,
					name: item.text
				}
			}
			temp.children = addDynamicRoutes(item.children, temp.children)
			routes.push(temp)
		} else if (item.url) {
			const mod = modules[`../views${item.url}.vue`] //根据加载所有文件匹配为组件  引入
			const route = {
				path: item.url,
				component: mod,
				name: item.id,
				meta: {
					keepAlive: true,
					id: item.id,
					name: item.text
				}
			}
			routes.push(route)
		}
	}
	return routes
}

export default router