import { ref } from 'vue'
import { defineStore } from 'pinia'

// 用户状态管理
// 管理用户的认证信息、权限和个人信息
// 提供登录、登出和用户信息更新等功能

export const useUserStore = defineStore('user', () => {
  // 用户认证令牌
  const token = ref(localStorage.getItem('token'))
  // 用户信息
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  // 用户权限列表
  const permissions = ref(JSON.parse(localStorage.getItem('permissions') || '[]'))

  // 设置用户令牌
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
    localStorage.setItem('userInfo', JSON.stringify(info))
  }

  // 设置用户权限
  const setPermissions = (perms) => {
    permissions.value = perms
    localStorage.setItem('permissions', JSON.stringify(perms))
  }

  // 退出登录
  const logout = () => {
    token.value = null
    userInfo.value = {}
    permissions.value = []
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('permissions')
  }

  // 检查用户是否有特定权限
  const hasPermission = (perm) => {
    return permissions.value.includes(perm)
  }

  return {
    token,
    userInfo,
    permissions,
    setToken,
    setUserInfo,
    setPermissions,
    logout,
    hasPermission
  }
})