/**
 * ASL 文献控制器
 */

import { FastifyRequest, FastifyReply } from 'fastify';
import { ImportLiteratureDto, LiteratureDto } from '../types/index.js';
import { prisma } from '../../../config/database.js';
import { logger } from '../../../common/logging/index.js';
import * as XLSX from 'xlsx';

/**
 * 导入文献（从Excel或JSON）
 */
export async function importLiteratures(
  request: FastifyRequest<{ Body: ImportLiteratureDto }>,
  reply: FastifyReply
) {
  try {
    const userId = (request as any).userId || 'asl-test-user-001';
    const { projectId, literatures } = request.body;

    // 验证项目归属
    const project = await prisma.aslScreeningProject.findFirst({
      where: { id: projectId, userId },
    });

    if (!project) {
      return reply.status(404).send({
        error: 'Project not found',
      });
    }

    // 批量创建文献
    const created = await prisma.aslLiterature.createMany({
      data: literatures.map((lit) => ({
        projectId,
        pmid: lit.pmid,
        title: lit.title,
        abstract: lit.abstract,
        authors: lit.authors,
        journal: lit.journal,
        publicationYear: lit.publicationYear,
        doi: lit.doi,
      })),
      skipDuplicates: true, // 跳过重复的PMID
    });

    logger.info('Literatures imported', {
      projectId,
      count: created.count,
    });

    return reply.status(201).send({
      success: true,
      data: {
        importedCount: created.count,
      },
    });
  } catch (error) {
    logger.error('Failed to import literatures', { error });
    return reply.status(500).send({
      error: 'Failed to import literatures',
    });
  }
}

/**
 * 从Excel文件导入文献
 */
export async function importLiteraturesFromExcel(
  request: FastifyRequest,
  reply: FastifyReply
) {
  try {
    const userId = (request as any).userId || 'asl-test-user-001';
    
    // 获取上传的文件
    const data = await request.file();
    if (!data) {
      return reply.status(400).send({
        error: 'No file uploaded',
      });
    }

    const projectId = (request.body as any).projectId;
    if (!projectId) {
      return reply.status(400).send({
        error: 'projectId is required',
      });
    }

    // 验证项目归属
    const project = await prisma.aslScreeningProject.findFirst({
      where: { id: projectId, userId },
    });

    if (!project) {
      return reply.status(404).send({
        error: 'Project not found',
      });
    }

    // 解析Excel（内存中）
    const buffer = await data.toBuffer();
    const workbook = XLSX.read(buffer, { type: 'buffer' });
    const sheetName = workbook.SheetNames[0];
    const sheet = workbook.Sheets[sheetName];
    const jsonData = XLSX.utils.sheet_to_json<any>(sheet);

    // 映射字段（支持中英文列名）
    const literatures: LiteratureDto[] = jsonData.map((row) => ({
      pmid: row.PMID || row.pmid || row['PMID编号'],
      title: row.Title || row.title || row['标题'],
      abstract: row.Abstract || row.abstract || row['摘要'],
      authors: row.Authors || row.authors || row['作者'],
      journal: row.Journal || row.journal || row['期刊'],
      publicationYear: row.Year || row.year || row['年份'],
      doi: row.DOI || row.doi,
    }));

    // 批量创建
    const created = await prisma.aslLiterature.createMany({
      data: literatures.map((lit) => ({
        projectId,
        ...lit,
      })),
      skipDuplicates: true,
    });

    logger.info('Literatures imported from Excel', {
      projectId,
      count: created.count,
    });

    return reply.status(201).send({
      success: true,
      data: {
        importedCount: created.count,
        totalRows: jsonData.length,
      },
    });
  } catch (error) {
    logger.error('Failed to import literatures from Excel', { error });
    return reply.status(500).send({
      error: 'Failed to import literatures from Excel',
    });
  }
}

/**
 * 获取项目的所有文献
 */
export async function getLiteratures(
  request: FastifyRequest<{
    Params: { projectId: string };
    Querystring: { page?: number; limit?: number };
  }>,
  reply: FastifyReply
) {
  try {
    const userId = (request as any).userId || 'asl-test-user-001';
    const { projectId } = request.params;
    const { page = 1, limit = 50 } = request.query;

    // 验证项目归属
    const project = await prisma.aslScreeningProject.findFirst({
      where: { id: projectId, userId },
    });

    if (!project) {
      return reply.status(404).send({
        error: 'Project not found',
      });
    }

    const [literatures, total] = await Promise.all([
      prisma.aslLiterature.findMany({
        where: { projectId },
        skip: (page - 1) * limit,
        take: limit,
        orderBy: { createdAt: 'desc' },
        include: {
          screeningResults: {
            select: {
              conflictStatus: true,
              finalDecision: true,
            },
          },
        },
      }),
      prisma.aslLiterature.count({
        where: { projectId },
      }),
    ]);

    return reply.send({
      success: true,
      data: {
        literatures,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
        },
      },
    });
  } catch (error) {
    logger.error('Failed to get literatures', { error });
    return reply.status(500).send({
      error: 'Failed to get literatures',
    });
  }
}

/**
 * 删除文献
 */
export async function deleteLiterature(
  request: FastifyRequest<{ Params: { literatureId: string } }>,
  reply: FastifyReply
) {
  try {
    const userId = (request as any).userId || 'asl-test-user-001';
    const { literatureId } = request.params;

    // 验证文献归属
    const literature = await prisma.aslLiterature.findFirst({
      where: {
        id: literatureId,
        project: { userId },
      },
    });

    if (!literature) {
      return reply.status(404).send({
        error: 'Literature not found',
      });
    }

    await prisma.aslLiterature.delete({
      where: { id: literatureId },
    });

    logger.info('Literature deleted', { literatureId });

    return reply.send({
      success: true,
      message: 'Literature deleted successfully',
    });
  } catch (error) {
    logger.error('Failed to delete literature', { error });
    return reply.status(500).send({
      error: 'Failed to delete literature',
    });
  }
}

