/**
 * 奖励管理服务
 */

export interface Reward {
  id?: number
  userId: number
  userName?: string
  activityId?: number
  activityName?: string
  rewardType: RewardType
  rewardAmount: number
  status: RewardStatus
  applyReason?: string
  applyTime?: string
  approveTime?: string
  grantTime?: string
  createdAt?: string
  updatedAt?: string
}

export type RewardType = 'COUPON' | 'POINTS' | 'CASH' | 'GIFT'

export type RewardStatus = 'PENDING' | 'APPROVED' | 'REJECTED' | 'GRANTED' | 'CANCELLED'

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

export interface RewardListQuery {
  page?: number
  size?: number
  status?: string
  rewardType?: string
  userId?: number
  activityId?: number
  startDate?: string
  endDate?: string
}

class RewardService {
  private baseUrl = '/api'

  /**
   * 获取奖励列表
   */
  async getRewards(params?: RewardListQuery): Promise<Reward[]> {
    const searchParams = new URLSearchParams()
    if (params?.page) searchParams.set('page', String(params.page))
    if (params?.size) searchParams.set('size', String(params.size))
    if (params?.status) searchParams.set('status', params.status)
    if (params?.rewardType) searchParams.set('rewardType', params.rewardType)

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

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

  /**
   * 申请奖励
   */
  async applyReward(data: {
    userId: number
    activityId: number
    rewardType: RewardType
    rewardAmount: number
    applyReason: string
  }): Promise<number> {
    const response = await fetch(`${this.baseUrl}/rewards/apply`, {
      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 approveReward(id: number, approved: boolean, comment?: string): Promise<void> {
    const response = await fetch(`${this.baseUrl}/rewards/${id}/approve`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ approved, comment })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '审批奖励失败')
    }
  }

  /**
   * 发放奖励
   */
  async grantReward(id: number): Promise<void> {
    const response = await fetch(`${this.baseUrl}/rewards/${id}/grant`, {
      method: 'POST',
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '发放奖励失败')
    }
  }

  /**
   * 批量发放奖励
   */
  async batchGrantRewards(ids: number[]): Promise<void> {
    const response = await fetch(`${this.baseUrl}/rewards/batch-grant`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ ids })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '批量发放失败')
    }
  }

  /**
   * 取消奖励
   */
  async cancelReward(id: number, reason: string): Promise<void> {
    const response = await fetch(`${this.baseUrl}/rewards/${id}/cancel`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ reason })
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '取消奖励失败')
    }
  }

  /**
   * 获取待审批奖励数量
   */
  async getPendingCount(): Promise<number> {
    const response = await fetch(`${this.baseUrl}/rewards/pending-count`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<number>
    if (result.code !== 200) {
      return 0
    }
    return result.data
  }

  /**
   * 导出奖励记录
   */
  async exportRewards(params?: RewardListQuery): Promise<Blob> {
    const searchParams = new URLSearchParams()
    if (params?.status) searchParams.set('status', params.status)
    if (params?.rewardType) searchParams.set('rewardType', params.rewardType)

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

  /**
   * 奖励对账
   */
  async reconcile(startDate: string, endDate: string): Promise<any> {
    const response = await fetch(`${this.baseUrl}/rewards/reconcile?startDate=${startDate}&endDate=${endDate}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '对账失败')
    }
    return result.data
  }
}

export const rewardService = new RewardService()
export default rewardService
