import auth from '@/plugins/auth'
import router, { constantRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'
import { isHttp } from '@/utils/validate'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

const usePermissionStore = defineStore(
  'permission',
  {
    state: () => ({
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      topbarRouters: [],
      sidebarRouters: []
    }),
    actions: {
      setRoutes(routes) {
        this.addRoutes = routes
        this.routes = constantRoutes.concat(routes)
      },
      setDefaultRoutes(routes) {
        this.defaultRoutes = constantRoutes.concat(routes)
      },
      setTopbarRoutes(routes) {
        this.topbarRouters = routes
      },
      setSidebarRouters(routes) {
        this.sidebarRouters = routes
      },
      generateRoutes(roles) {
        return new Promise((resolve, reject) => {
          // 调用后端接口获取动态路由
          getRouters().then(res => {
            // 确保 res.data 是数组
            if (!res.data || !Array.isArray(res.data)) {
              console.error('路由数据格式错误:', res.data)
              reject(new Error('路由数据格式错误，期望数组'))
              return
            }

            try {
              const sdata = JSON.parse(JSON.stringify(res.data))
              const rdata = JSON.parse(JSON.stringify(res.data))
              const defaultData = JSON.parse(JSON.stringify(res.data))
              const sidebarRoutes = filterAsyncRouter(sdata)
              const rewriteRoutes = filterAsyncRouter(rdata, false, true)
              const defaultRoutes = filterAsyncRouter(defaultData)

              // 过滤权限路由
              const accessedRoutes = filterDynamicRoutes(rewriteRoutes)

              // 调试：打印路由信息
              console.log('动态路由加载成功，路由数量:', accessedRoutes.length)
              if (accessedRoutes.length > 0) {
                console.log('第一个路由示例:', accessedRoutes[0])
              }

              this.setRoutes(accessedRoutes)
              this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
              this.setDefaultRoutes(constantRoutes.concat(defaultRoutes))
              this.setTopbarRoutes(constantRoutes.concat(sidebarRoutes))

              // 动态添加路由到router
              accessedRoutes.forEach(route => {
                router.addRoute(route)
              })

              resolve(accessedRoutes)
            } catch (error) {
              console.error('路由处理错误:', error)
              reject(error)
            }
          }).catch(error => {
            console.error('获取路由失败:', error)
            reject(error)
          })
        })
      }
    }
  })

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  // 确保 asyncRouterMap 是数组
  if (!Array.isArray(asyncRouterMap)) {
    console.error('filterAsyncRouter: 期望数组，但收到:', asyncRouterMap)
    return []
  }

  return asyncRouterMap.filter(route => {
    // 处理外部链接路径：如果 path 是外部链接，需要转换为有效的内部路径
    if (route.path && isHttp(route.path)) {
      // 确保 meta.link 保存实际的外部链接
      if (!route.meta) {
        route.meta = {}
      }
      // 保存原始的外部链接到 meta.link
      const originalPath = route.path
      route.meta.link = originalPath
      
      // 将外部链接路径转换为内部路径
      // 使用简单的路径格式：/iframe/域名，避免路径冲突
      const domain = originalPath.replace(/^https?:\/\//, '').replace(/\/.*$/, '')
      const timestamp = Date.now()
      const encodedPath = '/iframe/' + encodeURIComponent(domain) + '-' + timestamp
      
      // 将 path 转换为有效的内部路径
      route.path = encodedPath
    } else if (!lastRouter && route.path && !route.path.startsWith('/')) {
      // 只对顶级路由（lastRouter 为 false）确保路径以 "/" 开头
      // 子路由的路径会在 filterChildren 中处理
      route.path = '/' + route.path
    }
    
    if (route.component) {
      // 检查是否有外部链接
      if (route.meta && route.meta.link && (route.meta.link.startsWith('http://') || route.meta.link.startsWith('https://'))) {
        route.component = InnerLink
      }
      // Layout ParentView 组件特殊处理
      else if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        const component = loadView(route.component)
        if (!component) {
          console.warn('找不到组件:', route.component)
        }
        route.component = component || (() => import('@/views/error/404.vue'))
      }
    }
    if (route.children != null && route.children && route.children.length) {
      // 如果 type 为 true，先使用 filterChildren 处理子路由路径
      if (type) {
        route.children = filterChildren(route.children, route)
      }
      // 然后递归处理子路由
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach(el => {
    if (lastRouter) {
      // 处理子路由路径：如果子路由路径以 / 开头，需要去掉，因为要拼接父路由路径
      let childPath = el.path || ''
      if (childPath.startsWith('/')) {
        childPath = childPath.substring(1)
      }
      // 拼接父路由路径和子路由路径
      const parentPath = lastRouter.path || ''
      // 确保父路径以 / 结尾（如果父路径不是根路径）
      const separator = parentPath.endsWith('/') ? '' : '/'
      el.path = parentPath + separator + childPath
    }
    // 确保最终路径以 / 开头（如果不是空路径）
    if (el.path && !el.path.startsWith('/')) {
      el.path = '/' + el.path
    }
    if (el.children && el.children.length && el.component === 'ParentView') {
      children = children.concat(filterChildren(el.children, el))
    } else {
      children.push(el)
    }
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    } else {
      // 没有权限控制的路由，直接通过
      res.push(route)
    }
  })
  return res
}

export const loadView = (view) => {
  if (!view) {
    return null
  }

  // 处理外部链接
  if (view.startsWith('http://') || view.startsWith('https://')) {
    return null
  }

  let res = null;
  for (const path in modules) {
    const dir = path.split('views/')[1]?.split('.vue')[0];
    if (dir && dir === view) {
      res = () => modules[path]();
      break;
    }
  }

  if (!res) {
    console.warn(`loadView: 找不到组件 "${view}"，请检查路径是否正确`)
  }

  return res
}

export default usePermissionStore

