/**
 * 活动管理服务
 */
import { authFetch, baseUrl } from './authHelper'
import type { Activity } from '../types/activity'

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

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

export interface PagedResponse<T> {
  content: T[]
  number: number
  size: number
  totalElements: number
  totalPages: number
}

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

  /**
   * 获取活动列表
   */
  async getActivities(params?: ActivityListQuery): Promise<Activity[]> {
    const searchParams = new URLSearchParams()
    if (params?.page !== undefined) searchParams.set('page', String(params.page))
    if (params?.size !== undefined) searchParams.set('size', String(params.size))
    if (params?.status) searchParams.set('status', params.status)
    if (params?.keyword) searchParams.set('keyword', params.keyword)
    // 日期参数转换为 ISO 格式以兼容后端 OffsetDateTime
    if (params?.startDate) {
      // 尝试解析并转换为 ISO 格式
      const date = new Date(params.startDate)
      if (!isNaN(date.getTime())) {
        searchParams.set('startDate', date.toISOString())
      }
    }
    if (params?.endDate) {
      const date = new Date(params.endDate)
      if (!isNaN(date.getTime())) {
        searchParams.set('endDate', date.toISOString())
      }
    }

    const response = await authFetch(`${this.baseUrl}/activities?${searchParams}`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<PagedResponse<Activity> | Activity[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取活动列表失败')
    }
    // 兼容分页响应格式
    const data = result.data
    if (data && 'content' in data) {
      return data.content
    }
    // 兼容数组响应格式（演示模式）
    return Array.isArray(data) ? data : []
  }

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

  /**
   * 创建活动
   */
  async createActivity(data: Partial<Activity>): Promise<Activity> {
    const response = await authFetch(`${this.baseUrl}/activities`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<Activity>
    if (result.code !== 201 && result.code !== 200) {
      throw new Error(result.message || '创建活动失败')
    }
    return result.data
  }

  /**
   * 更新活动
   */
  async updateActivity(id: number, data: Partial<Activity>): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/activities/${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 deleteActivity(id: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/activities/${id}`, {
      method: 'DELETE',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '删除活动失败')
    }
  }

  /**
   * 归档活动
   */
  async archiveActivity(id: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/activities/${id}/archive`, {
      method: 'POST',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '归档活动失败')
    }
  }

  /**
   * 发布活动
   */
  async publishActivity(id: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/activities/${id}/publish`, {
      method: 'POST',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '发布活动失败')
    }
  }

  /**
   * 暂停活动
   */
  async pauseActivity(id: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/activities/${id}/pause`, {
      method: 'POST',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '暂停活动失败')
    }
  }

  /**
   * 恢复活动
   */
  async resumeActivity(id: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/activities/${id}/resume`, {
      method: 'POST',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '恢复活动失败')
    }
  }

  /**
   * 结束活动
   */
  async endActivity(id: number): Promise<void> {
    const response = await authFetch(`${this.baseUrl}/activities/${id}/end`, {
      method: 'POST',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '结束活动失败')
    }
  }

  /**
   * 获取活动参与者列表
   */
  async getParticipants(activityId: number, page: number = 0, size: number = 20, query?: string): Promise<{
    content: Array<{
      id: number
      inviterUserId: number
      inviteeUserId: number
      email: string
      status: string
      invitedAt: string
    }>
    totalElements: number
    totalPages: number
    currentPage: number
  }> {
    let url = `${this.baseUrl}/activities/admin/${activityId}/participants?page=${page}&size=${size}`
    if (query) {
      url += `&query=${encodeURIComponent(query)}`
    }
    const response = await authFetch(url, {
      method: 'GET',
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<{
      content: Array<{
        id: number
        inviterUserId: number
        inviteeUserId: number
        email: string
        status: string
        invitedAt: string
      }>
      totalElements: number
      totalPages: number
      currentPage: number
    }>
    if (result.code !== 200) {
      throw new Error(result.message || '获取活动参与者失败')
    }
    return result.data
  }

  /**
   * 批量发布活动
   */
  async batchPublish(activityIds: number[]): Promise<any> {
    const response = await authFetch(`${this.baseUrl}/activities/batch/publish`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify({ activityIds })
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '批量发布活动失败')
    }
    return result.data
  }

  /**
   * 批量暂停活动
   */
  async batchPause(activityIds: number[]): Promise<any> {
    const response = await authFetch(`${this.baseUrl}/activities/batch/pause`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify({ activityIds })
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '批量暂停活动失败')
    }
    return result.data
  }

  /**
   * 批量结束活动
   */
  async batchEnd(activityIds: number[]): Promise<any> {
    const response = await authFetch(`${this.baseUrl}/activities/batch/end`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: undefined,
      body: JSON.stringify({ activityIds })
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '批量结束活动失败')
    }
    return result.data
  }

  /**
   * 获取活动统计
   */
  async getActivityStats(id: number): Promise<any> {
    const response = await authFetch(`${this.baseUrl}/activities/${id}/stats`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '获取活动统计失败')
    }
    return result.data
  }

  /**
   * 获取活动图表数据
   */
  async getActivityGraph(id: number): Promise<any> {
    const response = await authFetch(`${this.baseUrl}/activities/${id}/graph`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<any>
    if (result.code !== 200) {
      throw new Error(result.message || '获取活动图表失败')
    }
    return result.data
  }

  /**
   * 获取活动排行榜
   */
  async getActivityLeaderboard(id: number, limit?: number): Promise<any[]> {
    // 后端使用topN参数，不是limit
    const params = limit ? `?topN=${limit}` : ''
    const response = await authFetch(`${this.baseUrl}/activities/${id}/leaderboard${params}`, {
      credentials: undefined
    })
    const result = await response.json() as ApiResponse<any[] | PagedResponse<any>>
    if (result.code !== 200) {
      throw new Error(result.message || '获取排行榜失败')
    }
    // 兼容分页响应
    const data = result.data as any
    if (data && 'content' in data) {
      return data.content || []
    }
    return Array.isArray(data) ? data : []
  }

  /**
   * 上传活动素材图片
   * @param activityId 活动ID
   * @param file 图片文件
   * @returns 返回上传后的URL和文件名
   */
  async uploadActivityImage(activityId: number, file: File): Promise<{ url: string; filename: string }> {
    const formData = new FormData()
    formData.append('file', file)

    const response = await authFetch(`${this.baseUrl}/activities/${activityId}/upload-image`, {
      method: 'POST',
      credentials: undefined,
      body: formData
    })
    const result = await response.json() as ApiResponse<{ url: string; filename: string }>
    if (result.code !== 200) {
      throw new Error(result.message || '图片上传失败')
    }
    return result.data
  }
}

export const activityService = new ActivityService()
export default activityService
