import type { Answer, CumulativeResult } from '@/client/mobile/components/Exam/types';

/**
 * 计算累计结果（按用户ID分组计算累计收益）
 * @param answers 答题数据数组
 * @returns 累计结果数组
 */
export function calculateCumulativeResults(answers: Answer[]): CumulativeResult[] {
  const userResults = new Map<string, CumulativeResult>();

  // 按日期排序
  const sortedDates = [...new Set(answers.map(a => a.date))].sort((a: string, b: string) => 
    new Date(a).getTime() - new Date(b).getTime()
  );
  
  sortedDates.forEach(date => {
    const dateAnswers = answers.filter(answer => answer.date === date);
    dateAnswers.forEach((answer: Answer) => {
      const userId = answer.userId?.toString();
      if (!userId) return;
      
      // 直接使用服务端计算好的收益数据
      const profitAmount = answer.profitAmount || 0;
      const profitPercent = answer.profitPercent || 0;

      if (!userResults.has(userId)) {
        userResults.set(userId, {
          userId: parseInt(userId),
          username: answer.username,
          totalProfitAmount: 0,
          totalProfitPercent: 0
        });
      }

      const currentResult = userResults.get(userId)!;
      currentResult.totalProfitAmount += profitAmount;
      currentResult.totalProfitPercent += profitPercent;
      userResults.set(userId, currentResult);
    });
  });

  return Array.from(userResults.values());
}