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

export const useAuthStore = defineStore('eco-auth', {
  state: (): AuthState => ({
    isLoaded: false,
    permissionCodes: [],
    menuList: [],
    roleCodes: [],
    routeName: ''
  }),
  getters: {
    getLoaded: state => state.isLoaded,
    getPermissionCodes: state => state.permissionCodes,
    getMenuList: state => state.menuList,
    getRoleCodes: state => state.roleCodes,
    getRouteName: state => state.routeName,
    showMenuListGet: state => getShowMenuList(state.menuList),
    flatMenuListGet: state => getFlatMenuList(state.menuList),
    breadcrumbListGet: state => getAllBreadcrumbList(state.menuList)
  },
  actions: {
    setLoaded() {
      this.isLoaded = true
    },
    setPermissionCodes(codes: string[]) {
      // 获取 按钮权限
      this.permissionCodes = codes
    },
    async setMenuList() {
      // 获取 菜单权限 API获取
      const { data } = await MenuApi.getMenuList()
      this.menuList = data
    },
    setRoleCodes(codes: string[]) {
      // 获取 角色权限
      this.roleCodes = codes
    },
    setRouteName(name: string) {
      // 获取 路由
      this.routeName = name
    },
    clear() {
      this.isLoaded = false
      this.permissionCodes = []
      this.menuList = []
      this.roleCodes = []
    }
  }
})

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)
}
