import { defineStore } from 'pinia'
import { ref } from 'vue'
import { GetLoginResourceTree } from '@/api/system/index'
import router, { constantRoutes } from '@/router'
const modules = import.meta.glob('../views/**/index.vue')
const layoutModule = import.meta.glob('../components/layouts/defaultLayout.vue')

export const usePermissionStore = defineStore('permission', () => {
  const routes = ref([...constantRoutes])
  const dynamicRoutes = ref([])
  const isRoutesGenerated = ref(false)

  // 处理组件路径
  const loadComponent = (path) => {
    try {
      const formattedPath = path.replace(/^\/+/, '').replace(/\/+/g, '/')
      const componentPath = `../views/${formattedPath}/index.vue`
      if (modules[componentPath]) {
        return modules[componentPath]
      }
      return modules['../views/error/404.vue']
    } catch (error) {
      console.error('Failed to load component:', error)
      return modules['../views/error/404.vue']
    }
  }

  const getLayoutComponent = () => {
    const layoutPath = '../components/layouts/defaultLayout.vue'
    return layoutModule[layoutPath]
  }

  // 生成动态路由
  const generateRoutes = async () => {
    const token = sessionStorage.getItem('token')
    if(!token) return
    
    try {
      // 如果路由已经生成过，直接返回
      if (isRoutesGenerated.value) {
        return dynamicRoutes.value
      }

      const system = JSON.parse(sessionStorage.getItem('system'))
      if (!system.systemId) {
        console.error('未找到系统信息')
        isRoutesGenerated.value = true 
        return []
      }

      const params = {
        serviceID: system.systemId
      }
      
      const response = await GetLoginResourceTree(params)
      isRoutesGenerated.value = true
      

      if (response.StatusCode === 200 && response.Data) {
        sessionStorage.setItem('routers', JSON.stringify(response.Data))
        const routerData = response.Data
        const newRoutes = []

        // 处理路由数据
        routerData.forEach(item => {
          if (item.ResType === '菜单') {
            const route = {
              path: '/' + item.Path,
              name: item.Path,
              meta: {
                title: item.Name,
                icon: item.IconPath,
                requiresAuth: true,
              },
              component: getLayoutComponent(),
              children: item.Children ? item.Children.filter(child => child.ResType === '菜单').map(child => {
                const childPath = `${item.Path}/${child.Path}`
                return {
                  path: child.Path,
                  name: childPath,
                  meta: {
                    title: child.Name,
                    requiresAuth: true,
                  },
                  component: loadComponent(childPath),
                  children: child.Children ? child.Children.filter(grandChild => grandChild.ResType === '菜单').map(grandChild => {
                    const grandChildPath = `${childPath}/${grandChild.Path}`
                    return {
                      path: grandChild.Path,
                      name: grandChildPath,
                      meta: {
                        title: grandChild.Name,
                        requiresAuth: true,
                      },
                      component: loadComponent(grandChildPath)
                    }
                  }) : []
                }
              }) : []
            }
            newRoutes.push(route)
          }
        })

        // 清除现有的动态路由
        dynamicRoutes.value.forEach(route => {
          if (router.hasRoute(route.name)) {
            router.removeRoute(route.name)
          }
        })

        // 添加新的动态路由
        newRoutes.forEach(route => {
          if (!router.hasRoute(route.name)) {
            router.addRoute(route)
          }
        })

        // 更新路由状态
        dynamicRoutes.value = newRoutes
        routes.value = [...constantRoutes, ...newRoutes]
        return newRoutes
      }
      return []
    } catch (error) {
      console.error('获取路由数据失败:', error)
      window.open(import.meta.env.VITE_HOME_URL, '_self')
      return []
    }
  }

  return {
    routes,
    dynamicRoutes,
    isRoutesGenerated,
    generateRoutes
  }
}) 
