import { defineStore } from "pinia"
import { ref, computed } from "vue"
import type { User, LoginForm } from "@/types/auth"
import { authApi } from "@/api/auth"
import { menusApi, type Menu } from "@/api/menus"
import { getToken, setToken, removeToken, getTenantCode } from "@/utils/auth"

export const useAuthStore = defineStore("auth", () => {
  const user = ref<User | null>(null)
  const token = ref<string>(getToken() || "")
  const loading = ref<boolean>(false)
  const menus = ref<Menu[]>([])

  const isAuthenticated = computed(() => !!token.value)

  // 获取当前用户的租户编码（优先从用户信息获取，其次从 URL 获取）
  const tenantCode = computed(() => {
    return user.value?.tenantCode || getTenantCode()
  })

  // 检查是否有指定角色
  const hasRole = (role: string): boolean => {
    return user.value?.roles?.includes(role) ?? false
  }

  // 检查是否为超级管理员
  const isSuperAdmin = (): boolean => {
    return user.value?.roles?.includes('super_admin') ?? false
  }

  // 检查是否有指定权限
  const hasPermission = (permission: string): boolean => {
    // 超级管理员拥有所有权限
    if (isSuperAdmin()) return true
    return user.value?.permissions?.includes(permission) ?? false
  }

  // 检查是否有任一角色
  const hasAnyRole = (roles: string[]): boolean => {
    if (!roles || roles.length === 0) return true
    return roles.some((role) => hasRole(role))
  }

  // 检查是否有任一权限
  const hasAnyPermission = (permissions: string[]): boolean => {
    if (!permissions || permissions.length === 0) return true
    // 超级管理员拥有所有权限
    if (isSuperAdmin()) return true
    return permissions.some((perm) => hasPermission(perm))
  }

  const login = async (form: LoginForm) => {
    const response = await authApi.login(form)
    token.value = response.token
    user.value = response.user

    // 使用租户编码作为 cookie path（不再存储到 localStorage）
    if (response.user.tenantCode) {
      setToken(response.token, response.user.tenantCode)
    } else {
      setToken(response.token)
    }

    // 登录后获取用户菜单
    await fetchUserMenus()
    return response
  }

  const logout = async () => {
    try {
      await authApi.logout()
    } finally {
      token.value = ""
      // 删除 token cookie，使用当前用户的租户编码或 URL 中的租户编码
      const tenantCode = user.value?.tenantCode || getTenantCode()
      removeToken(tenantCode || undefined)
      user.value = null
      menus.value = []
      // 重置动态路由标记
      if (typeof window !== "undefined") {
        const { resetDynamicRoutes } = await import("@/router")
        resetDynamicRoutes()
      }
    }
  }

  const fetchUserInfo = async () => {
    if (!token.value) {
      throw new Error("未登录")
    }

    try {
      loading.value = true
      const response = await authApi.getUserInfo()
      user.value = response
      // 获取用户菜单
      await fetchUserMenus()
      return response
    } catch (error) {
      // 如果获取用户信息失败，清除 token
      token.value = ""
      user.value = null
      menus.value = []
      removeToken()
      throw error
    } finally {
      loading.value = false
    }
  }

  const fetchUserMenus = async () => {
    if (!token.value) {
      return
    }

    try {
      const userMenus = await menusApi.getUserMenus()
      menus.value = userMenus
      return userMenus
    } catch (error) {
      console.error("获取用户菜单失败:", error)
      menus.value = []
      throw error
    }
  }

  const updateToken = (newToken: string) => {
    token.value = newToken
    // 使用当前用户的租户编码更新 token cookie
    const tenantCode = user.value?.tenantCode || getTenantCode()
    setToken(newToken, tenantCode || undefined)
  }

  // 初始化：如果有 token 但没有用户信息，自动获取
  const initAuth = async () => {
    if (token.value && !user.value) {
      try {
        await fetchUserInfo()
      } catch (error) {
        console.error("自动获取用户信息失败:", error)
      }
    }
  }

  return {
    user,
    token,
    loading,
    menus,
    isAuthenticated,
    tenantCode,
    hasRole,
    hasPermission,
    hasAnyRole,
    hasAnyPermission,
    login,
    logout,
    fetchUserInfo,
    fetchUserMenus,
    updateToken,
    initAuth,
  }
})
