import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, logout, getCurrentUser } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || 'null'))
  const permissions = ref(JSON.parse(localStorage.getItem('permissions') || '[]'))
  
  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const username = computed(() => userInfo.value?.username || '')
  const nickname = computed(() => userInfo.value?.nickname || '')
  
  // 登录
  const loginAction = async (loginForm) => {
    try {
      const response = await login(loginForm)
      if (response.success) {
        const { token: newToken, user, permissions: userPermissions } = response.data
        
        // 保存到状态
        token.value = newToken
        userInfo.value = user
        permissions.value = userPermissions || []
        
        // 保存到本地存储
        localStorage.setItem('token', newToken)
        localStorage.setItem('userInfo', JSON.stringify(user))
        localStorage.setItem('permissions', JSON.stringify(userPermissions || []))
        
        ElMessage.success('登录成功')
        return true
      } else {
        ElMessage.error(response.message || '登录失败')
        return false
      }
    } catch (error) {
      console.error('登录错误:', error)
      ElMessage.error('登录失败，请检查网络连接')
      return false
    }
  }
  
  // 登出
  const logoutAction = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('登出错误:', error)
    } finally {
      // 清除状态
      token.value = ''
      userInfo.value = null
      permissions.value = []
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('permissions')
      
      ElMessage.success('已退出登录')
    }
  }
  
  // 获取当前用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await getCurrentUser()
      if (response.success) {
        userInfo.value = response.data
        localStorage.setItem('userInfo', JSON.stringify(response.data))
      }
    } catch (error) {
      console.error('获取用户信息错误:', error)
    }
  }
  
  // 检查权限
  const hasPermission = (permission) => {
    return permissions.value.includes(permission)
  }
  
  // 检查角色
  const hasRole = (role) => {
    return userInfo.value?.roles?.includes(role) || false
  }
  
  return {
    // 状态
    token,
    userInfo,
    permissions,
    
    // 计算属性
    isAuthenticated,
    username,
    nickname,
    
    // 方法
    loginAction,
    logoutAction,
    fetchUserInfo,
    hasPermission,
    hasRole
  }
})