/**
 * 用户管理服务
 */

export interface User {
  id: number
  username: string
  email?: string
  phone?: string
  status: number
  roles?: string[]
  departmentId?: number
  createdAt?: string
}

export interface ApiResponse<T> {
  code: number
  data: T
  message?: string
}

class UserService {
  private baseUrl = '/api'

  async getUsers(params?: { page?: number; size?: number; keyword?: string }): Promise<User[]> {
    const searchParams = new URLSearchParams()
    if (params?.page) searchParams.set('page', String(params.page))
    if (params?.size) searchParams.set('size', String(params.size))
    if (params?.keyword) searchParams.set('keyword', params.keyword)

    const response = await fetch(`${this.baseUrl}/users?${searchParams}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<User[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取用户列表失败')
    }
    return result.data
  }

  async getUserById(id: number): Promise<User | null> {
    const response = await fetch(`${this.baseUrl}/users/${id}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<User>
    if (result.code !== 200) {
      return null
    }
    return result.data
  }

  async createUser(data: Partial<User>): Promise<number> {
    const response = await fetch(`${this.baseUrl}/users`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<number>
    if (result.code !== 200) {
      throw new Error(result.message || '创建用户失败')
    }
    return result.data
  }

  async updateUser(id: number, data: Partial<User>): Promise<void> {
    const response = await fetch(`${this.baseUrl}/users/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '更新用户失败')
    }
  }

  async deleteUser(id: number): Promise<void> {
    const response = await fetch(`${this.baseUrl}/users/${id}`, {
      method: 'DELETE',
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '删除用户失败')
    }
  }

  async freezeUser(id: number): Promise<void> {
    const response = await fetch(`${this.baseUrl}/users/${id}/freeze`, {
      method: 'POST',
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '冻结用户失败')
    }
  }

  async unfreezeUser(id: number): Promise<void> {
    const response = await fetch(`${this.baseUrl}/users/${id}/unfreeze`, {
      method: 'POST',
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '解冻用户失败')
    }
  }

  async assignRoles(userId: number, roleIds: number[]): Promise<void> {
    const response = await fetch(`${this.baseUrl}/users/${userId}/roles`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ roleIds })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '分配角色失败')
    }
  }
}

export const userService = new UserService()
export default userService
