import { PermissionState } from '@/types'
import { AppRouteRecordRaw } from '@/router/types'
// import { RouteRecordRaw } from 'vue-router'
import { defineStore } from 'pinia'
import { constantRoutes, noFoundRouters } from '@/router'
import { listRoutes } from '@/api/system/menu'

const modules = import.meta.glob('@/views/**/**.vue')
export const Layout = () => import('@/layout/index.vue')

// const hasPermission = (roles: string[], route: AppRouteRecordRaw) => {
// 	if (route.meta && route.meta.roles) {
// 		if (roles.includes('ROOT')) {
// 			return true
// 		}
// 		return roles.some(role => {
// 			if (route.meta?.roles !== undefined) {
// 				return (route.meta.roles as string[]).includes(role)
// 			}
// 		})
// 	}
// 	return false
// }

export const filterAsyncRoutes = (routes: AppRouteRecordRaw[], roles: string[]) => {
	const res: AppRouteRecordRaw[] = []
	routes.forEach(route => {
		const tmp = { ...route } as any
		tmp.meta = tmp.meta ? tmp.meta : {}
		// if (hasPermission(roles, tmp)) {
		// todo be delete
		// }
		// 特殊Layout 配置 标识
		if (!tmp.component || tmp.component === 'Layout') {
			tmp.component = Layout
		} else {
			const component = modules[`/src/views/${tmp.component}.vue`] as any
			// console.error(component, 'component....')
			if (component) {
				tmp.component = component
			} else {
				tmp.component = modules[`/src/views/error-page/404.vue`]
			}
		}
		/*if (tmp.component) {
			const component = modules[`/src/views/${tmp.component}.vue`] as any
			if (component) {
				tmp.component = component
			} else {
				tmp.component = modules[`/src/views/error-page/404.vue`]
			}
		}*/
		tmp.path && res.push(tmp)

		// 递归
		if (tmp.children) {
			tmp.children = filterAsyncRoutes(tmp.children, roles)
		}
	})
	// console.log(res, 'res........')
	return res
}

const usePermissionStore = defineStore({
	id: 'permission',
	state: (): PermissionState => ({
		routes: [],
		addRoutes: []
	}),
	actions: {
		setRoutes(routes: AppRouteRecordRaw[]) {
			this.addRoutes = routes
			this.routes = constantRoutes.concat(routes, noFoundRouters)
		},
		generateRoutes(roles: string[]) {
			return listRoutes().then((data: any) => {
				// 过滤掉顶级菜单组 没有/path 的数据(避免报错)
				const accessedRoutes = filterAsyncRoutes(
					data.menu.filter((v: any) => /\/.*/.test(v.path)),
					roles
				)
				// console.error(accessedRoutes, 'accessedRoutes')
				this.setRoutes(accessedRoutes)
				return accessedRoutes
			})
		}
	}
})

export default usePermissionStore
