/**
 * Phase 3: 批处理模式 - 结果展示主组件
 */

import React from 'react';
import { Button, Space, message } from 'antd';
import { DownloadOutlined, ReloadOutlined, RollbackOutlined } from '@ant-design/icons';
import { PresetTable } from './PresetTable';
import { CustomTable } from './CustomTable';
import type { BatchTask, BatchResult, BatchTemplate } from '../../api/batchApi';
import './BatchResults.css';

interface BatchResultsProps {
  task: BatchTask;
  results: BatchResult[];
  template: BatchTemplate | null;
  onRetryFailed: () => void;
  onReset: () => void;
}

export function BatchResults({
  task,
  results,
  template,
  onRetryFailed,
  onReset,
}: BatchResultsProps) {
  // 导出Excel
  const handleExportExcel = async () => {
    try {
      // 动态导入xlsx
      const XLSX = await import('xlsx');

      if (template) {
        // 预设模板：8列表格
        const exportData = results
          .filter(r => r.status === 'success')
          .map(r => ({
            '序号': r.index,
            '文献名称': r.document_name,
            '研究目的': r.data?.research_purpose || '',
            '研究设计': r.data?.research_design || '',
            '研究对象': r.data?.research_subjects || '',
            '样本量': r.data?.sample_size || '',
            '干预组': r.data?.intervention_group || '',
            '对照组': r.data?.control_group || '',
            '结果及数据': r.data?.results_data || '',
            '牛津评级': r.data?.oxford_level || '',
          }));

        const worksheet = XLSX.utils.json_to_sheet(exportData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '提取结果');

        // 添加任务信息Sheet
        const taskInfo = [
          { 项目: '任务名称', 值: task.name },
          { 项目: '模板类型', 值: template.name },
          { 项目: '执行时间', 值: task.started_at },
          { 项目: '完成时间', 值: task.completed_at || '-' },
          { 项目: '总文献数', 值: task.total_documents },
          { 项目: '成功数', 值: task.completed_count - task.failed_count },
          { 项目: '失败数', 值: task.failed_count },
          { 项目: '总用时', 值: task.duration_seconds ? `${task.duration_seconds}秒` : '-' },
        ];
        const taskSheet = XLSX.utils.json_to_sheet(taskInfo);
        XLSX.utils.book_append_sheet(workbook, taskSheet, '任务信息');

        const filename = `批处理结果_${template.name}_${new Date().toISOString().split('T')[0]}.xlsx`;
        XLSX.writeFile(workbook, filename);
      } else {
        // 自定义模板：3列表格
        const exportData = results
          .filter(r => r.status === 'success')
          .map(r => ({
            '序号': r.index,
            '文献名称': r.document_name,
            '提取结果': r.data?.extracted_text || '',
          }));

        const worksheet = XLSX.utils.json_to_sheet(exportData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '提取结果');

        // 添加任务信息Sheet
        const taskInfo = [
          { 项目: '任务名称', 值: task.name },
          { 项目: '模板类型', 值: '自定义模板' },
          { 项目: '执行时间', 值: task.started_at },
          { 项目: '完成时间', 值: task.completed_at || '-' },
          { 项目: '总文献数', 值: task.total_documents },
          { 项目: '成功数', 值: task.completed_count - task.failed_count },
          { 项目: '失败数', 值: task.failed_count },
          { 项目: '总用时', 值: task.duration_seconds ? `${task.duration_seconds}秒` : '-' },
        ];
        const taskSheet = XLSX.utils.json_to_sheet(taskInfo);
        XLSX.utils.book_append_sheet(workbook, taskSheet, '任务信息');

        const filename = `批处理结果_自定义任务_${new Date().toISOString().split('T')[0]}.xlsx`;
        XLSX.writeFile(workbook, filename);
      }

      message.success('Excel文件已导出');
    } catch (error: any) {
      message.error(`导出失败: ${error.message}`);
    }
  };

  return (
    <div className="batch-results">
      {/* 结果头部 */}
      <div className="results-header">
        <div className="results-title">
          <span className="title-icon">📊</span>
          <span>批处理结果</span>
        </div>
        <Space>
          {task.failed_count > 0 && (
            <Button
              icon={<ReloadOutlined />}
              onClick={onRetryFailed}
            >
              重试失败项 ({task.failed_count})
            </Button>
          )}
          <Button
            type="primary"
            icon={<DownloadOutlined />}
            onClick={handleExportExcel}
          >
            导出Excel
          </Button>
          <Button
            icon={<RollbackOutlined />}
            onClick={onReset}
          >
            新建任务
          </Button>
        </Space>
      </div>

      {/* 任务摘要 */}
      <div className="results-summary">
        <div className="summary-item">
          <span className="summary-label">任务名称：</span>
          <span className="summary-value">{task.name}</span>
        </div>
        <div className="summary-item">
          <span className="summary-label">模板类型：</span>
          <span className="summary-value">
            {template ? template.name : '自定义模板'}
          </span>
        </div>
        <div className="summary-item">
          <span className="summary-label">总文献数：</span>
          <span className="summary-value">{task.total_documents}</span>
        </div>
        <div className="summary-item">
          <span className="summary-label">成功：</span>
          <span className="summary-value success-text">
            {task.completed_count - task.failed_count}
          </span>
        </div>
        <div className="summary-item">
          <span className="summary-label">失败：</span>
          <span className="summary-value failed-text">
            {task.failed_count}
          </span>
        </div>
        {task.duration_seconds && (
          <div className="summary-item">
            <span className="summary-label">总用时：</span>
            <span className="summary-value">
              {Math.floor(task.duration_seconds / 60)}分{task.duration_seconds % 60}秒
            </span>
          </div>
        )}
      </div>

      {/* 结果表格 */}
      <div className="results-table">
        {template ? (
          <PresetTable results={results} />
        ) : (
          <CustomTable results={results} />
        )}
      </div>
    </div>
  );
}

