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

export interface User {
  id: number
  username: string
  email?: string
  phone?: string
  nickname?: string
  avatar?: string
  status: UserStatus
  roles?: string[]
  departmentId?: number
  departmentName?: string
  realNameVerified?: boolean
  createdAt?: string
  updatedAt?: string
}

export type UserStatus = 'ACTIVE' | 'FROZEN' | 'DISABLED'

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

export interface UserListQuery {
  page?: number
  size?: number
  keyword?: string
  status?: string
  departmentId?: number
  startDate?: string
  endDate?: string
}

class UserService {
  private baseUrl = '/api'

  /**
   * 获取用户列表
   */
  async getUsers(params?: UserListQuery): 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)
    if (params?.status) searchParams.set('status', params.status)

    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 || '分配角色失败')
    }
  }

  /**
   * 实名认证
   */
  async verifyRealName(userId: number, realNameInfo: any): Promise<void> {
    const response = await fetch(`${this.baseUrl}/users/${userId}/verify`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(realNameInfo)
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '实名认证失败')
    }
  }

  /**
   * 导出用户
   */
  async exportUsers(params?: UserListQuery): Promise<Blob> {
    const searchParams = new URLSearchParams()
    if (params?.keyword) searchParams.set('keyword', params.keyword)
    if (params?.status) searchParams.set('status', params.status)

    const response = await fetch(`${this.baseUrl}/users/export?${searchParams}`, {
      credentials: 'include'
    })
    if (!response.ok) {
      throw new Error('导出用户失败')
    }
    return response.blob()
  }
}

export const userService = new UserService()
export default userService
