/**
 * 稿件审查功能 - API封装
 */

import request from './request';
import axios from 'axios';

// ==================== 类型定义 ====================

/**
 * 稿约规范性评估 - 单项
 */
export interface EditorialItem {
  criterion: string;
  status: 'pass' | 'warning' | 'fail';
  score: number;
  issues: string[];
  suggestions: string[];
}

/**
 * 稿约规范性评估结果
 */
export interface EditorialReview {
  overall_score: number;
  summary: string;
  items: EditorialItem[];
}

/**
 * 方法学评估 - 问题项
 */
export interface MethodologyIssue {
  type: string;
  severity: 'major' | 'minor';
  description: string;
  location: string;
  suggestion: string;
}

/**
 * 方法学评估 - 部分
 */
export interface MethodologyPart {
  part: string;
  score: number;
  issues: MethodologyIssue[];
}

/**
 * 方法学评估结果
 */
export interface MethodologyReview {
  overall_score: number;
  summary: string;
  parts: MethodologyPart[];
}

/**
 * 审查任务状态
 */
export type ReviewTaskStatus = 
  | 'pending'           // 等待处理
  | 'extracting'        // 提取文档文本
  | 'reviewing_editorial'  // 稿约规范性评估
  | 'reviewing_methodology'  // 方法学评估
  | 'completed'         // 完成
  | 'failed';           // 失败

/**
 * 审查任务
 */
export interface ReviewTask {
  id: string;
  fileName: string;
  fileSize: number;
  status: ReviewTaskStatus;
  wordCount?: number;
  overallScore?: number;
  modelUsed?: string;
  createdAt: string;
  startedAt?: string;
  completedAt?: string;
  durationSeconds?: number;
  errorMessage?: string;
}

/**
 * 完整审查报告
 */
export interface ReviewReport {
  taskId: string;
  fileName: string;
  wordCount?: number;
  modelUsed?: string;
  overallScore?: number;
  editorialReview?: EditorialReview;
  methodologyReview?: MethodologyReview;
  completedAt?: string;
  durationSeconds?: number;
}

/**
 * 任务列表项（简化版）
 */
export interface ReviewTaskListItem {
  id: string;
  fileName: string;
  fileSize: number;
  status: ReviewTaskStatus;
  overallScore?: number;
  modelUsed?: string;
  createdAt: string;
  completedAt?: string;
  durationSeconds?: number;
  wordCount?: number;
}

/**
 * 任务列表响应
 */
export interface ReviewTaskListResponse {
  tasks: ReviewTaskListItem[];
  pagination: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
  };
}

/**
 * 上传参数
 */
export interface UploadManuscriptParams {
  file: File;
  modelType?: 'deepseek-v3' | 'qwen3-72b' | 'qwen-long';
}

// ==================== API函数 ====================

/**
 * 上传稿件并开始审查
 */
export async function uploadManuscript(params: UploadManuscriptParams): Promise<{
  taskId: string;
  fileName: string;
  status: ReviewTaskStatus;
  createdAt: string;
}> {
  const formData = new FormData();
  formData.append('file', params.file);
  formData.append('modelType', params.modelType || 'deepseek-v3');

  // 使用axios直接调用，因为FormData需要特殊处理
  const response = await axios.post('/api/v1/review/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    timeout: 30000,
  });

  return response.data.data;
}

/**
 * 获取任务状态
 */
export async function getTaskStatus(taskId: string): Promise<ReviewTask> {
  const response = await request.get(`/review/tasks/${taskId}`);
  return response.data;
}

/**
 * 获取审查报告（完整）
 */
export async function getTaskReport(taskId: string): Promise<ReviewReport> {
  const response = await request.get(`/review/tasks/${taskId}/report`);
  return response.data;
}

/**
 * 获取任务列表
 */
export async function getTaskList(page: number = 1, limit: number = 20): Promise<ReviewTaskListResponse> {
  const response = await request.get('/review/tasks', {
    params: { page, limit },
  });
  
  return {
    tasks: response.data,
    pagination: response.pagination,
  };
}

/**
 * 删除任务
 */
export async function deleteTask(taskId: string): Promise<void> {
  await request.delete(`/review/tasks/${taskId}`);
}

/**
 * 轮询任务状态直到完成
 * @param taskId 任务ID
 * @param onProgress 进度回调
 * @param maxAttempts 最大尝试次数（默认60次，即5分钟）
 * @returns 完成的任务
 */
export async function pollTaskUntilComplete(
  taskId: string,
  onProgress?: (task: ReviewTask) => void,
  maxAttempts: number = 60,
): Promise<ReviewTask> {
  let attempts = 0;

  while (attempts < maxAttempts) {
    const task = await getTaskStatus(taskId);

    if (onProgress) {
      onProgress(task);
    }

    if (task.status === 'completed' || task.status === 'failed') {
      return task;
    }

    // 等待5秒后再次查询
    await new Promise(resolve => setTimeout(resolve, 5000));
    attempts++;
  }

  throw new Error('任务执行超时（超过5分钟）');
}

/**
 * 获取任务状态的中文描述
 */
export function getStatusText(status: ReviewTaskStatus): string {
  const statusMap: Record<ReviewTaskStatus, string> = {
    pending: '等待处理',
    extracting: '提取文档文本',
    reviewing_editorial: '稿约规范性评估',
    reviewing_methodology: '方法学评估',
    completed: '评估完成',
    failed: '评估失败',
  };
  return statusMap[status] || status;
}

/**
 * 获取任务状态的颜色
 */
export function getStatusColor(status: ReviewTaskStatus): string {
  const colorMap: Record<ReviewTaskStatus, string> = {
    pending: 'default',
    extracting: 'processing',
    reviewing_editorial: 'processing',
    reviewing_methodology: 'processing',
    completed: 'success',
    failed: 'error',
  };
  return colorMap[status] || 'default';
}

/**
 * 格式化文件大小
 */
export function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}

/**
 * 格式化时长
 */
export function formatDuration(seconds: number): string {
  if (seconds < 60) return `${seconds}秒`;
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}分${remainingSeconds}秒`;
}

/**
 * 获取评分等级
 */
export function getScoreLevel(score: number): {
  level: 'excellent' | 'good' | 'fair' | 'poor';
  text: string;
  color: string;
} {
  if (score >= 90) {
    return { level: 'excellent', text: '优秀', color: '#52c41a' };
  } else if (score >= 80) {
    return { level: 'good', text: '良好', color: '#1890ff' };
  } else if (score >= 60) {
    return { level: 'fair', text: '及格', color: '#faad14' };
  } else {
    return { level: 'poor', text: '不及格', color: '#f5222d' };
  }
}

// 默认导出
export default {
  uploadManuscript,
  getTaskStatus,
  getTaskReport,
  getTaskList,
  deleteTask,
  pollTaskUntilComplete,
  getStatusText,
  getStatusColor,
  formatFileSize,
  formatDuration,
  getScoreLevel,
};































