/**
 * 用户状态管理
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '@/utils/request'
import { API_ENDPOINTS } from '@/config/api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('admin_token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('admin_user') || 'null'))
  const permissions = ref([])
  
  // 登录
  const login = async (username, password) => {
    try {
      const response = await request.post(API_ENDPOINTS.LOGIN, {
        username,
        password
      })
      
      if (response.code === 200) {
        token.value = response.data.token
        userInfo.value = response.data.userInfo
        permissions.value = response.data.permissions || []
        
        // 保存到 localStorage
        localStorage.setItem('admin_token', response.data.token)
        localStorage.setItem('admin_user', JSON.stringify(response.data.userInfo))
        
        return true
      }
      return false
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }
  
  // 登出
  const logout = async () => {
    try {
      await request.post(API_ENDPOINTS.LOGOUT)
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      token.value = ''
      userInfo.value = null
      permissions.value = []
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_user')
    }
  }
  
  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await request.get(API_ENDPOINTS.GET_USER_INFO)
      if (response.code === 200) {
        userInfo.value = response.data.userInfo
        permissions.value = response.data.permissions || []
        localStorage.setItem('admin_user', JSON.stringify(response.data.userInfo))
        return true
      }
      return false
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return false
    }
  }
  
  // 检查权限
  const hasPermission = (permission) => {
    return permissions.value.includes(permission) || permissions.value.includes('*')
  }
  
  return {
    token,
    userInfo,
    permissions,
    login,
    logout,
    getUserInfo,
    hasPermission
  }
})

