/**
 * 用户状态管理
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo } from '@/types'
import { login as loginApi, logout as logoutApi } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(getToken() || '')
  const userInfo = ref<UserInfo | null>(null)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userName = computed(() => userInfo.value?.realName || '')
  const userAvatar = computed(() => userInfo.value?.avatar || '')
  const permissions = computed(() => userInfo.value?.permissions || [])
  const roles = computed(() => userInfo.value?.roles || [])

  /**
   * 登录
   */
  const login = async (username: string, password: string, captcha: string, captchaKey: string) => {
    const data = await loginApi({
      username,
      password,
      captcha,
      captcha_key: captchaKey
    })

    token.value = data.access_token
    userInfo.value = data.user
    setToken(data.access_token)

    return data
  }

  /**
   * 登出
   */
  const logout = async () => {
    try {
      await logoutApi()
    } finally {
      token.value = ''
      userInfo.value = null
      removeToken()
    }
  }

  /**
   * 设置用户信息
   */
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
  }

  /**
   * 检查权限
   */
  const hasPermission = (permission: string) => {
    if (userInfo.value?.isAdmin) {
      return true
    }
    return permissions.value.includes(permission)
  }

  /**
   * 检查角色
   */
  const hasRole = (roleCode: string) => {
    if (userInfo.value?.isAdmin) {
      return true
    }
    return roles.value.some(role => role.roleCode === roleCode)
  }

  return {
    // 状态
    token,
    userInfo,
    // 计算属性
    isLoggedIn,
    userName,
    userAvatar,
    permissions,
    roles,
    // 方法
    login,
    logout,
    setUserInfo,
    hasPermission,
    hasRole
  }
})
