import { type AuthState } from '@/stores/interface'
import { type RouteRecordRaw } from 'vue-router'
import { pinia } from '../index'
import { getAllBreadcrumbList, getFlatMenuList, getShowMenuList } from '@/utils'
const modules = import.meta.glob('../../views/**/**.vue')
const Layout = () => import('@/layouts/index.vue')

export const useAuthStore = defineStore('eco-auth', {
  state: (): AuthState => ({
    isLoaded: false,
    authButtonList: [],
    authMenuList: [],
    authRoleList: [],
    routeName: ''
  }),
  getters: {
    getLoaded: state => state.isLoaded,
    getAuthButtonList: state => state.authButtonList,
    getAuthMenuList: state => state.authMenuList,
    getAuthRoleList: state => state.authRoleList,
    getRouteName: state => state.routeName,
    showMenuListGet: state => {
      getShowMenuList(state.authMenuList)
    },
    flatMenuListGet: state => {
      return getFlatMenuList(state.authMenuList)
    },
    breadcrumbListGet: state => {
      return getAllBreadcrumbList(state.authMenuList)
    }
  },
  actions: {
    setLoaded() {
      this.isLoaded = true
    },
    setAuthButtonList() {
      // 获取 按钮权限
    },
    setAuthMenuList() {
      // 获取 菜单权限
    },
    setAuthRoleList() {
      // 获取 角色权限
    },
    setRouteName(name: string) {
      // 获取 路由
      this.routeName = name
    },
    clear() {
      this.isLoaded = false
      this.authButtonList = []
      this.authMenuList = []
      this.authRoleList = []
    }
  }
})

const conversionRouter = (routes: RouteRecordRaw[]) => {
  const asyncRoutes: RouteRecordRaw[] = []
  routes.forEach(route => {
    const tmpRoute = { ...route } as RouteRecordRaw
    if (tmpRoute.component?.toString() === 'ParentView') {
      delete tmpRoute.component
    }
    // 顶级 目录，替换为 Layout 组件
    if (tmpRoute.component?.toString() == 'Layout') {
      tmpRoute.component = Layout
    } else {
      // 其他菜单，根据组件路径动态加载组件
      const component = modules[`../../views/${tmpRoute.component}.vue`]
      if (component) {
        tmpRoute.component = component
      } else {
        tmpRoute.component = modules[`../../views/error/404.vue`]
      }
    }

    // 递归子菜单
    if (tmpRoute.children) {
      tmpRoute.children = conversionRouter(route.children as RouteRecordRaw[])
    }
    asyncRoutes.push(tmpRoute)
  })
  return asyncRoutes
}

export const useAuthStoreWithOut = () => {
  return useAuthStore(pinia)
}
