/**
 * @description 成就相关API
 * @author yslg
 * @since 2025-10-24
 */

import { api } from '@/apis/index';
import type { Achievement, UserAchievement, UserAchievementProgress, AchievementVO, AchievementEvent, ResultDomain, PageParam } from '@/types';

/**
 * 成就API服务
 */
export const achievementApi = {
  // ==================== 成就定义管理（管理员）====================

  /**
   * 创建成就
   * @param achievement 成就信息
   * @returns Promise<ResultDomain<Achievement>>
   */
  async createAchievement(achievement: Achievement): Promise<ResultDomain<Achievement>> {
    const response = await api.post<Achievement>('/achievements/achievement', achievement);
    return response.data;
  },

  /**
   * 更新成就
   * @param achievement 成就信息
   * @returns Promise<ResultDomain<Achievement>>
   */
  async updateAchievement(achievement: Achievement): Promise<ResultDomain<Achievement>> {
    const response = await api.put<Achievement>('/achievements/achievement', achievement);
    return response.data;
  },

  /**
   * 删除成就
   * @param achievement 成就信息（包含achievementID）
   * @returns Promise<ResultDomain<Boolean>>
   */
  async deleteAchievement(achievement: Achievement): Promise<ResultDomain<Boolean>> {
    const response = await api.delete<boolean>('/achievements/achievement', achievement);
    return response.data;
  },

  /**
   * 获取所有成就列表
   * @param filter 过滤条件（type: 成就类型, level: 成就等级）
   * @returns Promise<ResultDomain<Achievement>>
   */
  async getAllAchievements(filter?: Partial<Achievement>): Promise<ResultDomain<Achievement>> {
    const response = await api.post<Achievement>('/achievements/list', filter || {});
    return response.data;
  },

  /**
   * 分页查询成就
   * @param filter 过滤条件
   * @param pageParam 分页参数
   * @returns Promise<ResultDomain<Achievement>>
   */
  async getAchievementPage(filter?: Partial<Achievement>, pageParam?: PageParam): Promise<ResultDomain<Achievement>> {
    const response = await api.post<Achievement>('/achievements/page', { filter, pageParam });
    return response.data;
  },

  /**
   * 获取成就详情
   * @param achievementID 成就ID
   * @returns Promise<ResultDomain<Achievement>>
   */
  async getAchievementDetail(achievementID: string): Promise<ResultDomain<Achievement>> {
    const response = await api.get<Achievement>(`/achievements/detail/${achievementID}`);
    return response.data;
  },

  // ==================== 用户成就查询 ====================

  /**
   * 获取用户已获得的成就
   * @param userID 用户ID
   * @param type 成就类型（可选）
   * @returns Promise<ResultDomain<UserAchievement>>
   */
  async getUserAchievements(userID: string, type?: number): Promise<ResultDomain<UserAchievement>> {
    const params: Record<string, any> = {};
    if (type !== undefined) {
      params.type = type;
    }
    const response = await api.get<UserAchievement>(`/achievements/user/${userID}`, params);
    return response.data;
  },

  /**
   * 获取当前用户的成就列表（含进度信息）
   * 返回所有成就，包括：
   * - 已获得的成就：显示获得时间
   * - 未获得的成就：显示当前进度
   * @param type 成就类型（可选）
   * @returns Promise<ResultDomain<AchievementVO>>
   */
  async getMyAchievements(type?: number): Promise<ResultDomain<AchievementVO>> {
    const params: Record<string, any> = {};
    if (type !== undefined) {
      params.type = type;
    }
    const response = await api.get<AchievementVO>('/achievements/my', params);
    return response.data;
  },

  /**
   * 检查用户是否已获得成就
   * @param userID 用户ID
   * @param achievementID 成就ID
   * @returns Promise<ResultDomain<boolean>>
   */
  async hasAchievement(userID: string, achievementID: string): Promise<ResultDomain<boolean>> {
    const response = await api.get<boolean>(`/achievements/check/${userID}/${achievementID}`);
    return response.data;
  },

  // ==================== 成就授予（管理员）====================

  /**
   * 手动授予用户成就
   * @param userID 用户ID
   * @param achievementID 成就ID
   * @returns Promise<ResultDomain<UserAchievement>>
   */
  async grantAchievement(userID: string, achievementID: string): Promise<ResultDomain<UserAchievement>> {
    const response = await api.post<UserAchievement>('/achievements/grant', null, { 
      params: { userID, achievementID } 
    });
    return response.data;
  },

  /**
   * 撤销用户成就
   * @param userID 用户ID
   * @param achievementID 成就ID
   * @returns Promise<ResultDomain<Boolean>>
   */
  async revokeAchievement(userID: string, achievementID: string): Promise<ResultDomain<Boolean>> {
    const response = await api.delete<boolean>('/achievements/revoke', null, { 
      params: { userID, achievementID } 
    });
    return response.data;
  },

  // ==================== 成就进度查询 ====================

  /**
   * 获取用户成就进度
   * @param userID 用户ID
   * @param achievementID 成就ID（可选，为空则获取所有进度）
   * @returns Promise<ResultDomain<UserAchievementProgress>>
   */
  async getUserAchievementProgress(userID: string, achievementID?: string): Promise<ResultDomain<UserAchievementProgress>> {
    const params: Record<string, any> = {};
    if (achievementID) {
      params.achievementID = achievementID;
    }
    const response = await api.get<UserAchievementProgress>(`/achievements/progress/${userID}`, params);
    return response.data;
  },

  // ==================== 成就检测 ====================

  /**
   * 处理成就事件（内部接口，由其他服务调用）
   * @param event 成就事件
   * @returns Promise<ResultDomain<UserAchievement>>
   */
  async processAchievementEvent(event: AchievementEvent): Promise<ResultDomain<UserAchievement>> {
    const response = await api.post<UserAchievement>('/achievements/event/process', event);
    return response.data;
  },

  /**
   * 检查用户是否满足成就条件
   * @param userID 用户ID
   * @param achievementID 成就ID
   * @returns Promise<ResultDomain<boolean>>
   */
  async checkAchievementCondition(userID: string, achievementID: string): Promise<ResultDomain<boolean>> {
    const response = await api.get<boolean>(`/achievements/condition/check/${userID}/${achievementID}`);
    return response.data;
  },

  /**
   * 批量检查用户可获得的成就
   * @param userID 用户ID
   * @returns Promise<ResultDomain<Achievement>>
   */
  async checkAvailableAchievements(userID: string): Promise<ResultDomain<Achievement>> {
    const response = await api.get<Achievement>(`/achievements/available/${userID}`);
    return response.data;
  },

  // ==================== 成就统计 ====================

  /**
   * 获取用户成就统计
   * @param userID 用户ID
   * @returns Promise<ResultDomain<Record<string, any>>>
   */
  async getUserAchievementStatistics(userID: string): Promise<ResultDomain<Record<string, any>>> {
    const response = await api.get<Record<string, any>>(`/achievements/statistics/${userID}`);
    return response.data;
  },

  /**
   * 获取成就排行榜
   * @param limit 排行榜条数（默认10条）
   * @returns Promise<ResultDomain<Record<string, any>>>
   */
  async getAchievementRanking(limit = 10): Promise<ResultDomain<Record<string, any>>> {
    const response = await api.get<Record<string, any>>('/achievements/ranking', { limit });
    return response.data;
  },

  /**
   * 获取最近获得成就的用户
   * @param pageParam 分页参数
   * @param filter 过滤条件
   * @param limit 查询条数（默认10条）
   * @returns Promise<ResultDomain<UserAchievement>>
   */
  async getRecentAchievers(pageParam: PageParam, filter?:Achievement ): Promise<ResultDomain<UserAchievement>> {
    const response = await api.post<UserAchievement>(`/achievements/recent`, {pageParam, filter });
    return response.data;
  }
};
