import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreateHomeworkScoreDto } from './dto/create-score.dto';

@Injectable()
export class HomeworkScoresService {
  constructor(private prisma: PrismaService) {}

  /**
   * 提交评分
   */
  async create(
    createDto: CreateHomeworkScoreDto,
    tenantId: number,
    reviewerId: number,
  ) {
    // 验证提交记录存在
    const submission = await this.prisma.homeworkSubmission.findFirst({
      where: {
        id: createDto.submissionId,
        tenantId,
        validState: 1,
      },
    });

    if (!submission) {
      throw new NotFoundException('提交记录不存在');
    }

    // 检查是否已经评过分
    const existingScore = await this.prisma.homeworkScore.findFirst({
      where: {
        submissionId: createDto.submissionId,
        reviewerId,
        validState: 1,
      },
    });

    if (existingScore) {
      throw new BadRequestException('您已经对该作品进行过评分');
    }

    // 计算总分
    const totalScore = createDto.dimensionScores.reduce(
      (sum, item) => sum + item.score,
      0,
    );

    // 创建评分记录
    const score = await this.prisma.homeworkScore.create({
      data: {
        tenantId,
        submissionId: createDto.submissionId,
        reviewerId,
        dimensionScores: JSON.stringify(createDto.dimensionScores),
        totalScore,
        comments: createDto.comments || null,
        scoreTime: new Date(),
        creator: reviewerId,
      },
    });

    // 更新提交记录的总分和状态
    await this.updateSubmissionScore(createDto.submissionId);

    return score;
  }

  /**
   * 更新提交记录的总分
   */
  private async updateSubmissionScore(submissionId: number) {
    // 获取该提交记录的所有有效评分
    const scores = await this.prisma.homeworkScore.findMany({
      where: {
        submissionId,
        validState: 1,
      },
    });

    if (scores.length === 0) {
      return;
    }

    // 计算平均分
    const totalScore =
      scores.reduce((sum, s) => sum + Number(s.totalScore), 0) / scores.length;

    // 更新提交记录
    await this.prisma.homeworkSubmission.update({
      where: { id: submissionId },
      data: {
        totalScore,
        status: 'reviewed',
      },
    });
  }

  /**
   * 标记作品违规
   */
  async markViolation(
    submissionId: number,
    tenantId: number,
    reviewerId: number,
    reason?: string,
  ) {
    const submission = await this.prisma.homeworkSubmission.findFirst({
      where: {
        id: submissionId,
        tenantId,
        validState: 1,
      },
    });

    if (!submission) {
      throw new NotFoundException('提交记录不存在');
    }

    return this.prisma.homeworkSubmission.update({
      where: { id: submissionId },
      data: {
        status: 'rejected',
        modifier: reviewerId,
      },
    });
  }

  /**
   * 重置评分（删除当前用户对该作品的评分）
   */
  async resetScore(submissionId: number, tenantId: number, reviewerId: number) {
    const score = await this.prisma.homeworkScore.findFirst({
      where: {
        submissionId,
        reviewerId,
        tenantId,
        validState: 1,
      },
    });

    if (!score) {
      throw new NotFoundException('评分记录不存在');
    }

    // 软删除评分记录
    await this.prisma.homeworkScore.update({
      where: { id: score.id },
      data: {
        validState: 2,
      },
    });

    // 重新计算提交记录的总分
    await this.updateSubmissionScore(submissionId);

    // 检查是否还有评分，没有则将状态改为pending
    const remainingScores = await this.prisma.homeworkScore.count({
      where: {
        submissionId,
        validState: 1,
      },
    });

    if (remainingScores === 0) {
      await this.prisma.homeworkSubmission.update({
        where: { id: submissionId },
        data: {
          status: 'pending',
          totalScore: null,
        },
      });
    }

    return { message: '评分已重置' };
  }
}
