import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { getUserMenus, type MenuTree } from '@/api/menu'
import Layout from '@/layout/index.vue'

// 视图模块映射
const viewModules = import.meta.glob('@/views/**/*.vue')

export const usePermissionStore = defineStore('permission', () => {
  const routes = ref<RouteRecordRaw[]>([])
  const menus = ref<MenuTree[]>([])

  // 生成路由
  async function generateRoutes(): Promise<RouteRecordRaw[]> {
    const res = await getUserMenus()
    menus.value = res.data
    
    const accessRoutes = generateRoutesFromMenus(res.data)
    routes.value = accessRoutes
    
    return accessRoutes
  }

  // 从菜单生成路由
  function generateRoutesFromMenus(menuList: MenuTree[]): RouteRecordRaw[] {
    const result: RouteRecordRaw[] = []
    
    for (const menu of menuList) {
      // 跳过按钮类型
      if (menu.menuType === 3) continue
      
      const route: RouteRecordRaw = {
        path: menu.path || '',
        name: `Menu_${menu.id}`,
        meta: {
          title: menu.name,
          icon: menu.icon,
          permission: menu.permission,
          keepAlive: menu.isCache
        },
        children: []
      }
      
      // 顶级菜单使用 Layout
      if (menu.parentId === 0) {
        route.component = Layout
        
        if (menu.children && menu.children.length > 0) {
          route.children = generateRoutesFromMenus(menu.children)
          // 设置默认重定向到第一个子菜单
          const firstChild = route.children[0]
          if (firstChild) {
            route.redirect = firstChild.path
          }
        } else if (menu.component) {
          // 单级菜单
          route.children = [{
            path: '',
            name: `Menu_${menu.id}_index`,
            component: loadComponent(menu.component),
            meta: route.meta
          }]
        }
      } else {
        // 子菜单
        if (menu.component) {
          route.component = loadComponent(menu.component)
        }
        
        if (menu.children && menu.children.length > 0) {
          route.children = generateRoutesFromMenus(menu.children)
        }
      }
      
      result.push(route)
    }
    
    return result
  }

  // 加载组件
  function loadComponent(component: string) {
    const path = `/src/views/${component}.vue`
    return viewModules[path] || (() => import('@/views/error/404.vue'))
  }

  // 重置状态
  function resetState() {
    routes.value = []
    menus.value = []
  }

  return {
    routes,
    menus,
    generateRoutes,
    resetState
  }
})
