/**
 * 用户管理服务
 */
import { authFetch, getAuthHeaders, baseUrl } from './authHelper'

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 = baseUrl || '/api/v1'

  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 authFetch(`${this.baseUrl}/users?${searchParams}`)
    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 authFetch(`${this.baseUrl}/users/${id}`)
    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 authFetch(`${this.baseUrl}/users`, {
      method: 'POST',
      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 authFetch(`${this.baseUrl}/users/${id}`, {
      method: 'PUT',
      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 authFetch(`${this.baseUrl}/users/${id}`, {
      method: 'DELETE'
    })
    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 authFetch(`${this.baseUrl}/users/${id}/freeze`, {
      method: 'POST'
    })
    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 authFetch(`${this.baseUrl}/users/${id}/unfreeze`, {
      method: 'POST'
    })
    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 authFetch(`${this.baseUrl}/users/${userId}/roles`, {
      method: 'POST',
      body: JSON.stringify({ roleIds })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '分配角色失败')
    }
  }

  async addToBlacklist(userId: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/users/${userId}/blacklist`, {
      method: 'POST'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '加入黑名单失败')
    }
  }

  async removeFromBlacklist(userId: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/users/${userId}/unblacklist`, {
      method: 'POST'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '取消黑名单失败')
    }
  }

  async addToWhitelist(userId: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/users/${userId}/whitelist`, {
      method: 'POST'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '加入白名单失败')
    }
  }

  async removeFromWhitelist(userId: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/users/${userId}/unwhitelist`, {
      method: 'POST'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '取消白名单失败')
    }
  }

  async adjustPoints(userId: number, amount: number, reason: string): Promise<number> {
    const response = await authFetch(`${this.baseUrl}/users/${userId}/points/adjust`, {
      method: 'POST',
      body: JSON.stringify({ amount, reason })
    })
    const result = await response.json() as ApiResponse<{ newPoints: number }>
    if (result.code !== 200) {
      throw new Error(result.message || '积分调整失败')
    }
    return result.data.newPoints
  }

  async getPoints(userId: number): Promise<number> {
    const response = await authFetch(`${this.baseUrl}/users/${userId}/points`)
    const result = await response.json() as ApiResponse<{ points: number }>
    if (result.code !== 200) {
      throw new Error(result.message || '获取积分失败')
    }
    return result.data.points
  }

  async getComplaints(userId: number): Promise<any[]> {
    const response = await authFetch(`${this.baseUrl}/users/${userId}/complaints`)
    const result = await response.json() as ApiResponse<any[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取投诉记录失败')
    }
    return result.data
  }

  async addComplaint(userId: number, data: { title: string; content: string; complainant?: string }): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/users/${userId}/complaints`, {
      method: 'POST',
      body: JSON.stringify(data)
    })
    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
