/**
 * 表格数据转换工具
 * 将后端返回的ScreeningResult转换为双行表格展示格式
 */

import type { ScreeningResult, DoubleRowData } from '../types';

/**
 * 将筛选结果数组转换为双行表格数据
 * 每篇文献生成两行：第一行是DeepSeek结果，第二行是Qwen结果
 */
export function transformToDoubleRows(results: ScreeningResult[]): DoubleRowData[] {
  const rows: DoubleRowData[] = [];

  results.forEach((result, index) => {
    const hasConflict = result.conflictStatus === 'conflict';
    const literatureIndex = index + 1;

    // 第1行：DeepSeek结果
    rows.push({
      key: `${result.id}-ds`,
      literatureIndex,
      literatureId: result.literatureId,
      literatureTitle: result.literature.title,
      isFirstRow: true,
      modelName: 'DeepSeek-V3',
      P: result.dsPJudgment,
      I: result.dsIJudgment,
      C: result.dsCJudgment,
      O: null, // O维度没有单独判断
      S: result.dsSJudgment,
      conclusion: result.dsConclusion,
      confidence: result.dsConfidence,
      hasConflict,
      originalResult: result,
    });

    // 第2行：Qwen结果
    rows.push({
      key: `${result.id}-qw`,
      literatureIndex,
      literatureId: result.literatureId,
      literatureTitle: result.literature.title,
      isFirstRow: false,
      modelName: 'Qwen-Max',
      P: result.qwenPJudgment,
      I: result.qwenIJudgment,
      C: result.qwenCJudgment,
      O: null,
      S: result.qwenSJudgment,
      conclusion: result.qwenConclusion,
      confidence: result.qwenConfidence,
      hasConflict,
      originalResult: result,
    });
  });

  return rows;
}

/**
 * 判断是否有冲突（仅当两个模型的结论不一致时）
 */
export function hasConflict(result: ScreeningResult): boolean {
  return result.dsConclusion !== result.qwenConclusion;
}

/**
 * 获取最终决策
 * 优先使用人工复核结果，否则根据冲突情况自动决策
 */
export function getFinalDecision(result: ScreeningResult): string {
  // 如果有人工复核结果，优先使用
  if (result.finalDecision) {
    return result.finalDecision;
  }

  // 如果两个模型都同意，使用一致的结论
  if (result.dsConclusion === result.qwenConclusion) {
    return result.dsConclusion || 'pending';
  }

  // 如果有冲突，标记为待复核
  return 'pending';
}

/**
 * 计算进度百分比
 */
export function calculateProgress(
  processedItems: number,
  totalItems: number
): number {
  if (totalItems === 0) return 0;
  return Math.round((processedItems / totalItems) * 100);
}





