/**
 * 风险管理服务
 */

import { authFetch, baseUrl } from './authHelper'

export interface RiskAlert {
  id: number
  type: RiskType
  level: RiskLevel
  title: string
  description: string
  userId?: number
  userName?: string
  activityId?: number
  activityName?: string
  data?: Record<string, any>
  status: AlertStatus
  handleResult?: string
  handledBy?: number
  handledAt?: string
  createdAt: string
  updatedAt?: string
}

export type RiskType = 'CHEAT' | 'ABNORMAL' | 'VIOLATION' | 'SYSTEM'

export type RiskLevel = 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'

export type AlertStatus = 'PENDING' | 'HANDLED' | 'IGNORED' | 'WHITELISTED'

export interface RiskRule {
  id: number
  name: string
  code: string
  description?: string
  riskType: RiskType
  condition: string
  action: RiskAction
  status: RuleStatus
  priority: number
  createdBy?: number
  createdAt?: string
  updatedAt?: string
}

export type RiskAction = 'BLOCK' | 'WARN' | 'LOG' | 'CAPTCHA'

export type RuleStatus = 'ENABLED' | 'DISABLED'

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

/**
 * 分页结果结构
 */
export interface PagedResult<T> {
  data: T[]
  total: number
  page: number
  size: number
}

class RiskService {
  private baseUrl = baseUrl || '/api/v1'

  /**
   * 获取风险告警列表
   */
  async getAlerts(params?: {
    page?: number
    size?: number
    type?: string
    level?: string
    status?: string
    startDate?: string
    endDate?: string
  }): Promise<RiskAlert[]> {
    const searchParams = new URLSearchParams()
    if (params?.page) searchParams.set('page', String(params.page))
    if (params?.size) searchParams.set('size', String(params.size))
    if (params?.type) searchParams.set('type', params.type)
    if (params?.level) searchParams.set('level', params.level)
    if (params?.status) searchParams.set('status', params.status)

    const response = await authFetch(`${this.baseUrl}/risks/alerts?${searchParams}`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<RiskAlert[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取风险告警失败')
    }
    return result.data
  }

  /**
   * 获取单个告警详情
   */
  async getAlertById(id: number): Promise<RiskAlert | null> {
    const response = await authFetch(`${this.baseUrl}/risks/alerts/${id}`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<RiskAlert>
    if (result.code !== 200) {
      return null
    }
    return result.data
  }

  /**
   * 处理风险告警
   */
  async handleAlert(id: number, data: {
    status: AlertStatus
    handleResult: string
  }): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/risks/alerts/${id}/handle`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '处理告警失败')
    }
  }

  /**
   * 批量处理告警
   */
  async batchHandleAlerts(ids: number[], data: {
    status: AlertStatus
    handleResult: string
  }): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/risks/alerts/batch-handle`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify({ ids, ...data })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '批量处理失败')
    }
  }

  /**
   * 获取风控规则列表
   */
  async getRules(params?: {
    page?: number
    size?: number
    riskType?: string
    status?: string
  }): Promise<PagedResult<RiskRule>> {
    const searchParams = new URLSearchParams()
    if (params?.page) searchParams.set('page', String(params.page))
    if (params?.size) searchParams.set('size', String(params.size))
    if (params?.riskType) searchParams.set('riskType', params.riskType)
    if (params?.status) searchParams.set('status', params.status)

    const response = await authFetch(`${this.baseUrl}/risks/rules?${searchParams}`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<PagedResult<RiskRule>>
    if (result.code !== 200) {
      throw new Error(result.message || '获取风控规则失败')
    }
    return result.data
  }

  /**
   * 创建风控规则
   */
  async createRule(data: Partial<RiskRule>): Promise<number> {
    const response = await authFetch(`${this.baseUrl}/risks/rules`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      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 updateRule(id: number, data: Partial<RiskRule>): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/risks/rules/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '更新规则失败')
    }
  }

  /**
   * 删除风控规则
   */
  async deleteRule(id: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/risks/rules/${id}`, {
      method: 'DELETE',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '删除规则失败')
    }
  }

  /**
   * 启用/禁用规则
   */
  async toggleRule(id: number, enabled: boolean): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/risks/rules/${id}/toggle`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify({ enabled })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '切换规则状态失败')
    }
  }

  /**
   * 获取待处理告警数量
   */
  async getPendingAlertCount(): Promise<number> {
    const response = await authFetch(`${this.baseUrl}/risks/alerts/pending-count`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<number>
    if (result.code !== 200) {
      return 0
    }
    return result.data
  }

  /**
   * 执行风险拦截
   */
  async blockAlert(id: number, comment?: string): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/risks/alerts/${id}/block`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify({ comment })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '执行拦截失败')
    }
  }

  /**
   * 解除风险拦截
   */
  async releaseAlert(id: number, comment?: string): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/risks/alerts/${id}/release`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify({ comment })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '解除拦截失败')
    }
  }

  /**
   * 导出风控规则（CSV格式）
   */
  async exportRules(): Promise<Blob> {
    const response = await authFetch(`${this.baseUrl}/risks/rules/export`, {
      credentials: undefined
    })
    if (!response.ok) {
      throw new Error('导出失败')
    }
    return response.blob()
  }

  /**
   * 审核风控告警
   */
  async auditAlert(id: number, data: {
    result: 'APPROVED' | 'REJECTED' | 'PENDING'
    comment?: string
  }): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/risks/${id}/audit`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '审核失败')
    }
  }
}

export const riskService = new RiskService()
export default riskService
