/**
 * 用户状态管理
 * @file user.js
 * @description 用户相关的状态管理
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { SECURITY_CONFIG } from '@/config/env'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem(SECURITY_CONFIG.tokenKey) || '')
  const userData = ref(JSON.parse(localStorage.getItem(SECURITY_CONFIG.userKey) || 'null'))
  const isLoggedIn = computed(() => !!token.value && !!userData.value)

  // 检查登录状态
  function checkLoginStatus() {
    const savedToken = localStorage.getItem(SECURITY_CONFIG.tokenKey)
    const savedUser = localStorage.getItem(SECURITY_CONFIG.userKey)
    
    if (savedToken && savedUser) {
      try {
        token.value = savedToken
        userData.value = JSON.parse(savedUser)
        return true
      } catch (error) {
        console.error('解析用户数据失败', error)
        logout()
        return false
      }
    }
    return false
  }

  // 检查token是否有效
  async function validateToken() {
    if (!token.value) {
      return false
    }
    
    try {
      const { api } = await import('@/utils/api')
      // 尝试调用一个需要认证的API来验证token
      await api.auth.getCurrentUser()
      return true
    } catch (error) {
      if (error.message && error.message.includes('认证已过期')) {
        logout()
        return false
      }
      // 其他错误可能是网络问题，不清除token
      return true
    }
  }

  // 登录操作
  async function login(username, password, retryCount = 0) {
    try {
      const { api } = await import('@/utils/api')
      const result = await api.auth.login(username, password)
      
      // 登录成功后设置token和用户数据
      if (result.success && result.data.token) {
        token.value = result.data.token
        userData.value = {
          id: result.data.user.id,
          username: result.data.user.username,
          email: result.data.user.email,
          real_name: result.data.user.name,
          phone: result.data.user.phone,
          avatar: result.data.user.avatar,
          role: { name: result.data.user.role },
          status: result.data.user.status
        }
        
        // 保存到本地存储
        localStorage.setItem(SECURITY_CONFIG.tokenKey, result.data.token)
        localStorage.setItem(SECURITY_CONFIG.userKey, JSON.stringify(userData.value))
      }
      
      return result
    } catch (error) {
      console.error('登录错误:', error)
      // 重试逻辑（仅对500错误且重试次数<2）
      if (error.message.includes('500') && retryCount < 2) {
        return login(username, password, retryCount + 1)
      }
      // 直接抛出错误，由调用方处理
      throw error
    }
  }

  // 登出操作
  async function logout() {
    try {
      // 调用后端登出接口
      const { api } = await import('@/utils/api')
      await api.auth.logout()
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除本地状态
      token.value = ''
      userData.value = null
      
      // 清除本地存储
      localStorage.removeItem(SECURITY_CONFIG.tokenKey)
      localStorage.removeItem(SECURITY_CONFIG.userKey)
    }
  }

  // 更新用户信息
  function updateUserInfo(newUserInfo) {
    userData.value = { ...userData.value, ...newUserInfo }
    localStorage.setItem(SECURITY_CONFIG.userKey, JSON.stringify(userData.value))
  }

  // 权限检查方法
  function hasPermission(permission) {
    if (!userData.value || !userData.value.role) {
      return false
    }
    
    // 管理员拥有所有权限
    if (userData.value.role.name === 'admin') {
      return true
    }
    
    // 根据角色检查权限
    const rolePermissions = {
      'admin': ['*'], // 所有权限
      'manager': ['user:read', 'user:write', 'account:read', 'account:write', 'transaction:read', 'transaction:write'],
      'teller': ['user:read', 'account:read', 'account:write', 'transaction:read', 'transaction:write'],
      'user': ['account:read', 'transaction:read']
    }
    
    const userRole = userData.value.role.name
    const permissions = rolePermissions[userRole] || []
    
    if (Array.isArray(permission)) {
      return permission.some(p => permissions.includes(p) || permissions.includes('*'))
    }
    
    return permissions.includes(permission) || permissions.includes('*')
  }

  // 角色检查方法
  function hasRole(role) {
    if (!userData.value || !userData.value.role) {
      return false
    }
    
    if (Array.isArray(role)) {
      return role.includes(userData.value.role.name)
    }
    
    return userData.value.role.name === role
  }

  // 检查是否可以访问菜单
  function canAccessMenu(menuKey) {
    if (!userData.value) {
      return false
    }
    
    // 管理员可以访问所有菜单
    if (userData.value.role.name === 'admin') {
      return true
    }
    
    // 根据角色定义可访问的菜单
    const roleMenus = {
      'admin': ['*'], // 所有菜单
      'manager': ['dashboard', 'users', 'accounts', 'transactions', 'reports'],
      'teller': ['dashboard', 'accounts', 'transactions'],
      'user': ['dashboard', 'accounts', 'transactions']
    }
    
    const userRole = userData.value.role.name
    const menus = roleMenus[userRole] || []
    
    return menus.includes(menuKey) || menus.includes('*')
  }

  // 获取用户角色名称
  function getUserRoleName() {
    return userData.value?.role?.name || 'user'
  }

  // 获取用户权限列表
  function getUserPermissions() {
    const rolePermissions = {
      'admin': ['*'],
      'manager': ['user:read', 'user:write', 'account:read', 'account:write', 'transaction:read', 'transaction:write'],
      'teller': ['user:read', 'account:read', 'account:write', 'transaction:read', 'transaction:write'],
      'user': ['account:read', 'transaction:read']
    }
    
    const userRole = userData.value?.role?.name || 'user'
    return rolePermissions[userRole] || []
  }

  // 检查用户状态
  function isUserActive() {
    return userData.value?.status === 'active'
  }

  // 检查用户是否被锁定
  function isUserLocked() {
    return userData.value?.status === 'locked' || userData.value?.status === 'suspended'
  }

  return {
    token,
    userData,
    isLoggedIn,
    checkLoginStatus,
    validateToken,
    login,
    logout,
    updateUserInfo,
    hasPermission,
    hasRole,
    canAccessMenu,
    getUserRoleName,
    getUserPermissions,
    isUserActive,
    isUserLocked
  }
})