import { staticRoutes } from '@/router';
import Request from '@/utils/request';
import Layout from '@/components/layout/index';
import { defineAsyncComponent } from 'vue';

const modules = import.meta.glob('/src/views/**/*.vue');

// 从服务器获取菜单
async function fetchAsyncRoutes4Server() {
	return new Request().post('Home/GetMenuList').then((r) => {
		if (r.status === 200) {
			return r.data;
		} else {
			return [];
		}
	});
}

// 菜单路由
function menuBuildTreeAsyncRoutes(routes) {
	const menus = [];
	routes.forEach((item) => {
		const it = {
			id: item.id,
			path: item.path,
			name: item.name,
			meta: item.meta,
			alwaysShow: item.alwaysShow,
			hidden: item.hidden,
		};
		if (item.children && item.children.length) {
			it.children = menuBuildTreeAsyncRoutes(item.children);
		}
		menus.push(it);
	});
	return menus;
}

// 组装路由结构
function buildTreeAsyncRoutes(routes) {
	const menus = [];
	routes.forEach((item) => {
		const it = {
			id: item.id,
			path: item.path,
			name: item.name,
			meta: item.meta,
			alwaysShow: item.alwaysShow,
			hidden: item.hidden,
		};
		if (item.redirect != null) {
			it.redirect = item.redirect;
		}
		if (item.component) {
			if (item.component === '/layout') {
				it.component = Layout;
			} else {
				if (
					modules[`/src/views${item.component}.vue`] &&
					modules[`/src/views${item.component}.vue`] !=
						'() => import("/src/views/index.vue")'
				) {
					it.component = modules[`/src/views${item.component}.vue`];
				}
				// it.component = modules[`/src/views${item.component}.vue`]
				// console.log(modules[`/src/views${item.component}.vue`])
			}
			if (item.children && item.children.length) {
				item.children.forEach((v) => {
					if (!it.meta.permission) {
						it.meta.permission = [];
					}
					if (item.path.startsWith('/')) {
						item.path = item.path.substring(1);
					}
					it.meta.permission.push(item.name + '.' + v.name);
				});
				it.children = buildTreeAsyncRoutes(item.children);
			}
			menus.push(it);
		}
	});
	return menus;
}

const state = {
	routes: [],
};

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.routes = routes;
	},
};

const actions = {
	async generateRoutes(context) {
		// 服务器获取菜单
		const routes = await fetchAsyncRoutes4Server();
		// 权限过滤
		// const accessRoutes = routes.filter(v => authList.indexOf(v.id) >= 0)
		// console.log('权限过滤',accessRoutes)
		// 组装路由
		const treeRoutes = buildTreeAsyncRoutes(routes);
		const menuRoutes = menuBuildTreeAsyncRoutes(routes);
		// 不合规路由
		const mergeTreeRoutes = staticRoutes
			.filter((it) => it.name != undefined)
			.concat(treeRoutes);
		context.commit('SET_ROUTES', menuRoutes);
		return mergeTreeRoutes;
	},
};

export default {
	namespaced: true,
	state,
	mutations,
	actions,
};
