/**
 * 审计日志服务
 */

export interface AuditLog {
  id: number
  userId: number
  userName?: string
  action: string
  module: string
  resource?: string
  method?: string
  requestUri?: string
  requestMethod?: string
  requestParams?: string
  requestBody?: string
  responseStatus?: number
  responseBody?: string
  ipAddress?: string
  userAgent?: string
  duration?: number
  errorMessage?: string
  createdAt: string
}

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

class AuditService {
  private baseUrl = '/api'

  /**
   * 获取审计日志列表
   */
  async getLogs(params?: {
    page?: number
    size?: number
    userId?: number
    action?: string
    module?: string
    startDate?: string
    endDate?: string
    keyword?: string
  }): Promise<AuditLog[]> {
    const searchParams = new URLSearchParams()
    if (params?.page) searchParams.set('page', String(params.page))
    if (params?.size) searchParams.set('size', String(params.size))
    if (params?.userId) searchParams.set('userId', String(params.userId))
    if (params?.action) searchParams.set('action', params.action)
    if (params?.module) searchParams.set('module', params.module)
    if (params?.keyword) searchParams.set('keyword', params.keyword)

    const response = await fetch(`${this.baseUrl}/audit/logs?${searchParams}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<AuditLog[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取审计日志失败')
    }
    return result.data
  }

  /**
   * 获取单个日志详情
   */
  async getLogById(id: number): Promise<AuditLog | null> {
    const response = await fetch(`${this.baseUrl}/audit/logs/${id}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<AuditLog>
    if (result.code !== 200) {
      return null
    }
    return result.data
  }

  /**
   * 获取操作类型列表
   */
  async getActionTypes(): Promise<string[]> {
    const response = await fetch(`${this.baseUrl}/audit/actions`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<string[]>
    if (result.code !== 200) {
      return []
    }
    return result.data
  }

  /**
   * 获取模块列表
   */
  async getModules(): Promise<string[]> {
    const response = await fetch(`${this.baseUrl}/audit/modules`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<string[]>
    if (result.code !== 200) {
      return []
    }
    return result.data
  }

  /**
   * 导出审计日志
   */
  async exportLogs(params?: {
    userId?: number
    action?: string
    module?: string
    startDate?: string
    endDate?: string
    keyword?: string
  }): Promise<Blob> {
    const searchParams = new URLSearchParams()
    if (params?.userId) searchParams.set('userId', String(params.userId))
    if (params?.action) searchParams.set('action', params.action)
    if (params?.module) searchParams.set('module', params.module)
    if (params?.keyword) searchParams.set('keyword', params.keyword)

    const response = await fetch(`${this.baseUrl}/audit/logs/export?${searchParams}`, {
      credentials: 'include'
    })
    if (!response.ok) {
      throw new Error('导出审计日志失败')
    }
    return response.blob()
  }

  /**
   * 获取审计统计
   */
  async getStats(params?: {
    startDate?: string
    endDate?: string
  }): Promise<{
    totalCount: number
    actionCounts: Record<string, number>
    userCounts: Record<string, number>
    dailyCounts: Record<string, number>
  }> {
    const searchParams = new URLSearchParams()
    if (params?.startDate) searchParams.set('startDate', params.startDate)
    if (params?.endDate) searchParams.set('endDate', params.endDate)

    const response = await fetch(`${this.baseUrl}/audit/stats?${searchParams}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '获取审计统计失败')
    }
    return result.data
  }
}

export const auditService = new AuditService()
export default auditService
