import viewTagsStore from "@/store/viewTags";
import {nextTick} from 'vue'
import {RouteLocationNormalized, RouteLocationNormalizedLoaded} from "vue-router";
import tools from "@/utils/tools";

const modules: Record<string, () => Promise<any>> = import.meta.glob('@/views/**/*.vue')
const notFound = () => import('/src/layout/404.vue')

export function beforeEach(to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded) {
	const piMain = document.querySelector('#pi-main');
	const viewTags = viewTagsStore()
	if (!piMain) {
		return false
	}
	viewTags.updateViewTags({
		fullPath: from.fullPath,
		scrollTop: piMain.scrollTop
	})
}

export function afterEach(to: RouteLocationNormalized) {
	const piMain = document.querySelector('#pi-main');
	const viewTags = viewTagsStore()
	if (!piMain) {
		return false
	}
	nextTick(() => {
		// @ts-ignore
		const beforeRoute = viewTags.viewTags.filter(v => v.fullPath == to.fullPath)[0];
		if (beforeRoute) {
			piMain.scrollTop = beforeRoute.scrollTop || 0
		}
	})
}

//转换
export function filterAsyncRouter(routerMap) {
	const accessedRouters = []
	routerMap.forEach(item => {
		item.meta = item.meta ? item.meta : {};
		//处理外部链接特殊路由
		if (item.meta.type == 'iframe') {
			item.meta.url = item.path;
			item.path = `/i/${item.name}`;
		}
		//MAP转路由对象
		var route = {
			path: item.path,
			name: item.name,
			meta: item.meta,
			redirect: item.redirect,
			children: item.children ? filterAsyncRouter(item.children) : null,
			component: loadComponent(item.component)
		}
		if (item.path.includes(':')) {
			route['props'] = true
		}
		accessedRouters.push(route)
	})
	return accessedRouters
}

export function loadComponent(component: string) {
	// 替换路径中的动态参数（例如 :id, :name）
	component = component.replace(/\/(:\w+)/g, '')
	// 构建可能的路径
	const fullPath = `/src/views/${component}.vue`
	const fullPathWithIndex = `/src/views/${component}/index.vue`
	// 先尝试直接路径，再尝试添加/index的路径
	return modules[fullPath] || modules[fullPathWithIndex] || notFound
}

//路由扁平化
export function flatAsyncRoutes(routes, breadcrumb = []) {
	let res = []
	routes.forEach(route => {
		const tmp = {...route}
		if (tmp.children) {
			let childrenBreadcrumb = [...breadcrumb]
			childrenBreadcrumb.push(route)
			let tmpRoute = {...route}
			tmpRoute.meta.breadcrumb = childrenBreadcrumb
			delete tmpRoute.children
			res.push(tmpRoute)
			let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb)
			childrenRoutes.map(item => {
				res.push(item)
			})
		} else {
			let tmpBreadcrumb = [...breadcrumb]
			tmpBreadcrumb.push(tmp)
			tmp.meta.breadcrumb = tmpBreadcrumb
			res.push(tmp)
		}
	})
	return res
}

//过滤树
export function treeFilter(tree, func) {
	return tree.map(node => ({...node})).filter(node => {
		node.children = node.children && treeFilter(node.children, func)
		return func(node) || (node.children && node.children.length)
	})
}

export function getMenu() {
	const 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
	})
	return [...userMenu, ...apiMenu]
}

export function makeMenu(menus, parent_id = 0) {
	const arr = [];
	for (let item of menus) {
		if (item.parent_id === parent_id) {
			// 数据格式处理
			const tmp = {
				name: item['name'],
				path: item['type'] == 0 ? '/' + item['path'] : item['path'],
				component: item['path'],
				meta: {
					'title': item['title'],
					'icon': item['icon'],
					'hidden': item['hidden'],
					'type': item['type'] == 0 ? 'menu' : 'link'
				}
			};
			const children = makeMenu(menus, item.menu_id);
			if (children.length > 0) {
				tmp['children'] = children
			}
			arr.push(tmp)
		}
	}
	return arr
}
