import { RouteRecordRaw } from 'vue-router';
import pinia from '/@/stores/index';
import { useUserInfo } from '/@/stores/userInfo';
import { useRequestOldRoutes } from '/@/stores/requestOldRoutes';
import { Session } from '/@/utils/storage';
import { NextLoading } from '/@/utils/loading';
import { dynamicRoutes, defaultDynamicRouteChildren, notFoundAndNoPower } from '/@/router/route';
import { formatTwoStageRoutes, formatFlatteningRoutes, router } from '/@/router/index';
import { useRoutesList } from '/@/stores/routesList';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { getUserMenus } from '/@/api/system/menu/index';

// 扩展Window接口，添加nextLoading属性
declare global {
	interface Window {
		nextLoading?: boolean;
	}
}

const layouModules: any = import.meta.glob('../layout/routerView/*.{vue,tsx}');
const viewsModules: any = import.meta.glob('../views/**/*.{vue,tsx}');
const parentView = layouModules['../layout/routerView/parent.vue'];
const notFoundView = viewsModules['../views/error/404.vue'];

// 后端控制路由

/**
 * 获取目录下的 .vue、.tsx 全部文件
 * @method import.meta.glob
 * @link 参考：https://cn.vitejs.dev/guide/features.html#json
 */
const dynamicViewsModules: Record<string, Function> = Object.assign({}, { ...layouModules }, { ...viewsModules });

const normalizeRouteComponent = (component?: string) => {
	if (!component) return '';
	return component
		.trim()
		.replace(/^\/@\//, '')
		.replace(/^\//, '')
		.replace(/^views\//, '')
		.replace(/\.(vue|tsx)$/i, '')
		.replace(/\/index$/i, '');
};

const resolveRouteComponent = (component?: string, path?: string, isParent = false) => {
	const normalizedComponent = normalizeRouteComponent(component);
	const normalizedPath = normalizeRouteComponent(path);
	const candidates = [normalizedComponent, normalizedPath].filter(Boolean);

	for (const candidate of candidates) {
		const exactViewIndexVueKey = `../views/${candidate}/index.vue`;
		if (dynamicViewsModules[exactViewIndexVueKey]) {
			return dynamicViewsModules[exactViewIndexVueKey];
		}

		const exactViewVueKey = `../views/${candidate}.vue`;
		if (dynamicViewsModules[exactViewVueKey]) {
			return dynamicViewsModules[exactViewVueKey];
		}

		const exactViewTsxKey = `../views/${candidate}.tsx`;
		if (dynamicViewsModules[exactViewTsxKey]) {
			return dynamicViewsModules[exactViewTsxKey];
		}

		const exactLayoutVueKey = `../${candidate}.vue`;
		if (dynamicViewsModules[exactLayoutVueKey]) {
			return dynamicViewsModules[exactLayoutVueKey];
		}

		const exactLayoutTsxKey = `../${candidate}.tsx`;
		if (dynamicViewsModules[exactLayoutTsxKey]) {
			return dynamicViewsModules[exactLayoutTsxKey];
		}

		if (candidate === 'layout/routerView/parent') {
			return parentView;
		}
	}

	if (isParent) return parentView;
	return notFoundView || parentView;
};

/**
 * 后端控制路由：初始化方法，防止刷新时路由丢失
 * @method NextLoading 界面 loading 动画开始执行
 * @method useUserInfo().setUserInfos() 触发初始化用户信息 pinia
 * @method useRequestOldRoutes().setRequestOldRoutes() 存储接口原始路由（未处理component），根据需求选择使用
 * @method setAddRoute 添加动态路由
 * @method setFilterMenuAndCacheTagsViewRoutes 设置路由到 vuex routesList 中（已处理成多级嵌套路由）及缓存多级嵌套数组处理后的一维数组
 */
export async function initBackEndControlRoutes() {
	if (window.nextLoading === undefined) NextLoading.start();
	if (!Session.get('token')) return false;

	await useUserInfo().setUserInfos();
	await useUserInfo().setPermissions();
	await getBackEndControlRoutes();
	const menuRoute = Session.get('userMenu');

	useRequestOldRoutes().setRequestOldRoutes(JSON.parse(JSON.stringify(menuRoute)));
	dynamicRoutes[0].children = [...defaultDynamicRouteChildren];
	dynamicRoutes[0].children?.push(...(await backEndComponent(menuRoute)));
	await setAddRoute();
	await setFilterMenuAndCacheTagsViewRoutes();
}

/**
 * 设置路由到 vuex routesList 中（已处理成多级嵌套路由）及缓存多级嵌套数组处理后的一维数组
 * @description 用于左侧菜单、横向菜单的显示
 * @description 用于 tagsView、菜单搜索中：未过滤隐藏的(isHide)
 */
export function setFilterMenuAndCacheTagsViewRoutes() {
	const storesRoutesList = useRoutesList(pinia);
	storesRoutesList.setRoutesList(dynamicRoutes[0].children as any);
	setCacheTagsViewRoutes();
}

/**
 * 缓存多级嵌套数组处理后的一维数组
 * @description 用于 tagsView、菜单搜索中：未过滤隐藏的(isHide)
 */
export function setCacheTagsViewRoutes() {
	const storesTagsView = useTagsViewRoutes(pinia);
	storesTagsView.setTagsViewRoutes(formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes))[0].children);
}

/**
 * 处理路由格式及添加捕获所有路由或 404 Not found 路由
 * @description 替换 dynamicRoutes（/@/router/route）第一个顶级 children 的路由
 * @returns 返回替换后的路由数组
 */
export function setFilterRouteEnd() {
	const filterRouteEnd: any = formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes));
	filterRouteEnd[0].children = [...filterRouteEnd[0].children, ...notFoundAndNoPower];
	return filterRouteEnd;
}

/**
 * 添加动态路由
 * @method router.addRoute
 * @description 此处循环为 dynamicRoutes（/@/router/route）第一个顶级 children 的路由一维数组，非多级嵌套
 * @link 参考：https://next.router.vuejs.org/zh/api/#addroute
 */
export async function setAddRoute() {
	await setFilterRouteEnd().forEach((route: RouteRecordRaw) => {
		const routeName: any = route.name;
		if (!router.hasRoute(routeName)) router.addRoute(route);
	});
}

/**
 * 请求后端路由菜单接口
 * @description isRequestRoutes 为 true，则开启后端控制路由
 * @returns 返回后端路由菜单数据
 */
export async function getBackEndControlRoutes() {
	const menuRoute = Session.get('userMenu');
	const permissions = Session.get('permissions');
	if (!menuRoute || !permissions) {
		await refreshBackEndControlRoutes();
	}
}

/**
 * 请求后端路由菜单接口刷新菜单及权限
 * @description isRequestRoutes 为 true，则开启后端控制路由
 * @returns 返回后端路由菜单数据
 */
export async function refreshBackEndControlRoutes() {
	await getUserMenus().then((res: any) => {
		Session.set('userMenu', res.data.menuList);
		Session.set('permissions', res.data.permissions);
	});
	await useUserInfo().setPermissions();
}

/**
 * 重新请求后端路由菜单接口
 * @description 用于菜单管理界面刷新菜单（未进行测试）
 * @description 路径：/src/views/system/menu/component/addMenu.vue
 */
export function setBackEndControlRefreshRoutes() {
	getBackEndControlRoutes();
}

/**
 * 后端路由 component 转换
 * @param routes 后端返回的路由表数组
 * @returns 返回处理成函数后的 component
 */
export function backEndComponent(routes: any) {
	if (!routes) return [];
	return routes.map((item: any) => {
		const hasChildren = Array.isArray(item.children) && item.children.length > 0;

		if (hasChildren) {
			item.children = backEndComponent(item.children);
			const firstVisibleChild = item.children.find((ci: any) => !ci.meta?.isHide);
			if (firstVisibleChild) {
				item.redirect = firstVisibleChild.path;
			}

			const routeComponent = resolveRouteComponent(item.component as string, item.path as string, false);
			item.component = routeComponent === notFoundView ? parentView : routeComponent;
		} else {
			item.component = resolveRouteComponent(item.component as string, item.path as string, false);
		}

		return item;
	});
}

/**
 * 后端路由 component 转换函数
 * @param dynamicViewsModules 获取目录下的 .vue、.tsx 全部文件
 * @param component 当前要处理项 component
 * @returns 返回处理成函数后的 component
 */
export function dynamicImport(dynamicViewsModules: Record<string, Function>, component: string) {
	const normalizedComponent = normalizeRouteComponent(component);
	if (!normalizedComponent) return false;

	const directViewIndexVueKey = `../views/${normalizedComponent}/index.vue`;
	if (dynamicViewsModules[directViewIndexVueKey]) return dynamicViewsModules[directViewIndexVueKey];

	const directViewVueKey = `../views/${normalizedComponent}.vue`;
	if (dynamicViewsModules[directViewVueKey]) return dynamicViewsModules[directViewVueKey];

	const directViewTsxKey = `../views/${normalizedComponent}.tsx`;
	if (dynamicViewsModules[directViewTsxKey]) return dynamicViewsModules[directViewTsxKey];

	const directLayoutVueKey = `../${normalizedComponent}.vue`;
	if (dynamicViewsModules[directLayoutVueKey]) return dynamicViewsModules[directLayoutVueKey];

	const directLayoutTsxKey = `../${normalizedComponent}.tsx`;
	if (dynamicViewsModules[directLayoutTsxKey]) return dynamicViewsModules[directLayoutTsxKey];

	const keys = Object.keys(dynamicViewsModules);
	const fuzzyKey = keys.find((key) => key.includes(`/${normalizedComponent}/`) || key.includes(`/${normalizedComponent}.`));
	if (fuzzyKey) return dynamicViewsModules[fuzzyKey];

	return false;
}
