package com.lesingle.creation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lesingle.creation.common.enums.ValidStateEnum;
import com.lesingle.creation.dto.homework.*;
import com.lesingle.creation.entity.Homework;
import com.lesingle.creation.entity.HomeworkReviewDimension;
import com.lesingle.creation.entity.HomeworkReviewRule;
import com.lesingle.creation.entity.HomeworkSubmission;
import com.lesingle.creation.common.exception.BusinessException;
import com.lesingle.creation.mapper.HomeworkMapper;
import com.lesingle.creation.mapper.HomeworkReviewDimensionMapper;
import com.lesingle.creation.mapper.HomeworkReviewRuleMapper;
import com.lesingle.creation.mapper.HomeworkSubmissionMapper;
import com.lesingle.creation.service.HomeworkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.creation.vo.homework.HomeworkDetailVO;
import com.lesingle.creation.vo.homework.HomeworkListVO;
import com.lesingle.creation.vo.homework.ReviewDimensionVO;
import com.lesingle.creation.vo.homework.ReviewRuleVO;
import com.lesingle.creation.vo.homework.SubmissionVO;
import com.lesingle.creation.vo.school.ClassTreeNodeVO;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 作业服务实现类
 */
@Slf4j
@Service
public class HomeworkServiceImpl extends ServiceImpl<HomeworkMapper, Homework>
        implements HomeworkService {

    private final HomeworkSubmissionMapper homeworkSubmissionMapper;
    private final HomeworkReviewRuleMapper homeworkReviewRuleMapper;
    private final HomeworkReviewDimensionMapper homeworkReviewDimensionMapper;

    public HomeworkServiceImpl(HomeworkSubmissionMapper homeworkSubmissionMapper,
                               HomeworkReviewRuleMapper homeworkReviewRuleMapper,
                               HomeworkReviewDimensionMapper homeworkReviewDimensionMapper) {
        this.homeworkSubmissionMapper = homeworkSubmissionMapper;
        this.homeworkReviewRuleMapper = homeworkReviewRuleMapper;
        this.homeworkReviewDimensionMapper = homeworkReviewDimensionMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HomeworkDetailVO create(CreateHomeworkDTO dto, Long tenantId, Long creatorId) {
        // 验证时间顺序
        if (dto.getSubmitStartTime().isAfter(dto.getSubmitEndTime())) {
            throw new BusinessException("提交开始时间不能晚于结束时间");
        }

        // 检查作业名称是否已存在
        Homework existing = this.getOne(new LambdaQueryWrapper<Homework>()
                .eq(Homework::getTenantId, tenantId)
                .eq(Homework::getName, dto.getName())
                .eq(Homework::getDeleted, 0));
        if (existing != null) {
            throw new BusinessException("作业名称已存在");
        }

        // 创建作业
        Homework homework = new Homework();
        homework.setTenantId(tenantId);
        homework.setName(dto.getName());
        homework.setContent(dto.getContent());
        homework.setStatus("unpublished");
        homework.setSubmitStartTime(dto.getSubmitStartTime());
        homework.setSubmitEndTime(dto.getSubmitEndTime());
        homework.setAttachments(dto.getAttachments());
        homework.setPublishScope(dto.getPublishScope());
        homework.setReviewRuleId(dto.getReviewRuleId());
        homework.setValidState(ValidStateEnum.VALID.getCode());

        this.save(homework);
        log.info("创建作业成功，ID={}, 名称={}", homework.getId(), dto.getName());

        return convertToDetailVO(homework);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HomeworkDetailVO update(Long id, UpdateHomeworkDTO dto, Long tenantId) {
        Homework homework = this.getById(id);
        if (homework == null || !homework.getTenantId().equals(tenantId)) {
            throw new BusinessException("作业不存在");
        }

        // 已发布的作业不能修改
        if ("published".equals(homework.getStatus())) {
            throw new BusinessException("已发布的作业不能修改");
        }

        homework.setName(dto.getName());
        homework.setContent(dto.getContent());
        if (dto.getSubmitStartTime() != null) {
            homework.setSubmitStartTime(dto.getSubmitStartTime());
        }
        if (dto.getSubmitEndTime() != null) {
            homework.setSubmitEndTime(dto.getSubmitEndTime());
        }
        homework.setAttachments(dto.getAttachments());
        homework.setPublishScope(dto.getPublishScope());
        if (dto.getReviewRuleId() != null) {
            homework.setReviewRuleId(dto.getReviewRuleId());
        }

        this.updateById(homework);
        log.info("更新作业成功，ID={}", id);

        return convertToDetailVO(homework);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HomeworkDetailVO publish(Long id, Long tenantId) {
        Homework homework = this.getById(id);
        if (homework == null || !homework.getTenantId().equals(tenantId)) {
            throw new BusinessException("作业不存在");
        }

        homework.setStatus("published");
        homework.setPublishTime(LocalDateTime.now());
        this.updateById(homework);
        log.info("发布作业成功，ID={}", id);

        return convertToDetailVO(homework);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id, Long tenantId) {
        Homework homework = this.getById(id);
        if (homework == null || !homework.getTenantId().equals(tenantId)) {
            throw new BusinessException("作业不存在");
        }

        this.removeById(id);
        log.info("删除作业成功，ID={}", id);
    }

    @Override
    public HomeworkDetailVO getDetail(Long id, Long tenantId) {
        Homework homework = this.getById(id);
        if (homework == null || !homework.getTenantId().equals(tenantId)) {
            throw new BusinessException("作业不存在");
        }

        return convertToDetailVO(homework);
    }

    @Override
    public Page<HomeworkListVO> pageQuery(HomeworkQueryDTO queryDTO, Long tenantId) {
        Page<Homework> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        LambdaQueryWrapper<Homework> wrapper = new LambdaQueryWrapper<Homework>()
                .eq(Homework::getTenantId, tenantId)
                .eq(Homework::getDeleted, 0)
                .like(queryDTO.getNameKeyword() != null, Homework::getName, queryDTO.getNameKeyword())
                .eq(queryDTO.getStatus() != null, Homework::getStatus, queryDTO.getStatus())
                .eq(queryDTO.getValidState() != null, Homework::getValidState, queryDTO.getValidState())
                .orderByDesc(Homework::getCreateTime);

        Page<Homework> resultPage = this.page(page, wrapper);

        // 转换为 VO
        List<HomeworkListVO> voList = resultPage.getRecords().stream()
                .map(this::convertToListVO)
                .collect(Collectors.toList());

        Page<HomeworkListVO> voPage = new Page<>(
                resultPage.getCurrent(),
                resultPage.getSize(),
                resultPage.getTotal()
        );
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SubmissionVO submit(SubmitHomeworkDTO dto, Long tenantId, Long studentId) {
        Homework homework = this.getById(dto.getHomeworkId());
        if (homework == null || !homework.getTenantId().equals(tenantId)) {
            throw new BusinessException("作业不存在");
        }

        // 检查是否已提交
        HomeworkSubmission existing = homeworkSubmissionMapper.selectOne(new LambdaQueryWrapper<HomeworkSubmission>()
                .eq(HomeworkSubmission::getHomeworkId, dto.getHomeworkId())
                .eq(HomeworkSubmission::getStudentId, studentId)
                .eq(HomeworkSubmission::getDeleted, 0));
        if (existing != null) {
            throw new BusinessException("您已经提交过该作业");
        }

        // 检查提交时间
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(homework.getSubmitStartTime())) {
            throw new BusinessException("还未到提交开始时间");
        }
        if (now.isAfter(homework.getSubmitEndTime())) {
            throw new BusinessException("已错过提交截止时间");
        }

        HomeworkSubmission submission = new HomeworkSubmission();
        submission.setTenantId(tenantId);
        submission.setHomeworkId(dto.getHomeworkId());
        submission.setStudentId(studentId);
        submission.setContent(dto.getContent());
        submission.setAttachments(dto.getAttachments());
        submission.setStatus("submitted");
        submission.setSubmitTime(LocalDateTime.now());

        homeworkSubmissionMapper.insert(submission);
        log.info("提交作业成功，ID={}, 学生 ID={}", submission.getId(), studentId);

        return convertToSubmissionVO(submission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SubmissionVO review(ReviewHomeworkDTO dto, Long tenantId, Long reviewerId) {
        HomeworkSubmission submission = homeworkSubmissionMapper.selectById(dto.getSubmissionId());
        if (submission == null || !submission.getTenantId().equals(tenantId)) {
            throw new BusinessException("提交记录不存在");
        }

        submission.setReviewerId(reviewerId);
        submission.setReviewComment(dto.getComment());
        submission.setReviewScore(dto.getScore());
        submission.setReviewTime(LocalDateTime.now());
        submission.setStatus("reviewing");

        homeworkSubmissionMapper.updateById(submission);
        log.info("批改作业成功，提交 ID={}, 分数={}", dto.getSubmissionId(), dto.getScore());

        return convertToSubmissionVO(submission);
    }

    @Override
    public List<SubmissionVO> getSubmissions(Long homeworkId, Long tenantId) {
        List<HomeworkSubmission> submissions = homeworkSubmissionMapper.selectList(
                new LambdaQueryWrapper<HomeworkSubmission>()
                        .eq(HomeworkSubmission::getHomeworkId, homeworkId)
                        .eq(HomeworkSubmission::getTenantId, tenantId)
                        .eq(HomeworkSubmission::getDeleted, 0)
                        .orderByDesc(HomeworkSubmission::getSubmitTime)
        );

        return submissions.stream()
                .map(this::convertToSubmissionVO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReviewRuleVO createReviewRule(String ruleName, String ruleType,
                                         java.math.BigDecimal totalScore, String description, Long tenantId) {
        HomeworkReviewRule rule = new HomeworkReviewRule();
        rule.setTenantId(tenantId);
        rule.setRuleName(ruleName);
        rule.setRuleType(ruleType);
        rule.setTotalScore(totalScore);
        rule.setDescription(description);

        homeworkReviewRuleMapper.insert(rule);
        log.info("创建评审规则成功，ID={}", rule.getId());

        return convertToReviewRuleVO(rule);
    }

    @Override
    public List<ReviewRuleVO> getReviewRules(Long tenantId) {
        List<HomeworkReviewRule> rules = homeworkReviewRuleMapper.selectList(
                new LambdaQueryWrapper<HomeworkReviewRule>()
                        .eq(HomeworkReviewRule::getTenantId, tenantId)
                        .eq(HomeworkReviewRule::getDeleted, 0)
                        .orderByDesc(HomeworkReviewRule::getCreateTime)
        );

        return rules.stream()
                .map(this::convertToReviewRuleVO)
                .collect(Collectors.toList());
    }

    // ========== 转换方法 ==========

    private HomeworkDetailVO convertToDetailVO(Homework homework) {
        HomeworkDetailVO vo = new HomeworkDetailVO();
        vo.setId(homework.getId());
        vo.setName(homework.getName());
        vo.setContent(homework.getContent());
        vo.setStatus(homework.getStatus());
        vo.setPublishTime(homework.getPublishTime());
        vo.setSubmitStartTime(homework.getSubmitStartTime());
        vo.setSubmitEndTime(homework.getSubmitEndTime());
        vo.setAttachments(homework.getAttachments());
        vo.setPublishScope(homework.getPublishScope());
        vo.setReviewRuleId(homework.getReviewRuleId());
        vo.setCreateTime(homework.getCreateTime());

        // 统计提交人数和批改人数
        Long submissionCount = homeworkSubmissionMapper.selectCount(
                new LambdaQueryWrapper<HomeworkSubmission>()
                        .eq(HomeworkSubmission::getHomeworkId, homework.getId())
                        .eq(HomeworkSubmission::getDeleted, 0)
        );
        Long reviewedCount = homeworkSubmissionMapper.selectCount(
                new LambdaQueryWrapper<HomeworkSubmission>()
                        .eq(HomeworkSubmission::getHomeworkId, homework.getId())
                        .eq(HomeworkSubmission::getStatus, "reviewing")
                        .eq(HomeworkSubmission::getDeleted, 0)
        );
        vo.setSubmissionCount(submissionCount.intValue());
        vo.setReviewedCount(reviewedCount.intValue());

        return vo;
    }

    private HomeworkListVO convertToListVO(Homework homework) {
        HomeworkListVO vo = new HomeworkListVO();
        vo.setId(homework.getId());
        vo.setName(homework.getName());
        vo.setStatus(homework.getStatus());
        vo.setPublishTime(homework.getPublishTime());
        vo.setSubmitStartTime(homework.getSubmitStartTime());
        vo.setSubmitEndTime(homework.getSubmitEndTime());
        vo.setCreateTime(homework.getCreateTime());

        // 统计提交人数和批改人数
        Long submissionCount = homeworkSubmissionMapper.selectCount(
                new LambdaQueryWrapper<HomeworkSubmission>()
                        .eq(HomeworkSubmission::getHomeworkId, homework.getId())
                        .eq(HomeworkSubmission::getDeleted, 0)
        );
        Long reviewedCount = homeworkSubmissionMapper.selectCount(
                new LambdaQueryWrapper<HomeworkSubmission>()
                        .eq(HomeworkSubmission::getHomeworkId, homework.getId())
                        .eq(HomeworkSubmission::getStatus, "reviewing")
                        .eq(HomeworkSubmission::getDeleted, 0)
        );
        vo.setSubmissionCount(submissionCount.intValue());
        vo.setReviewedCount(reviewedCount.intValue());

        return vo;
    }

    private SubmissionVO convertToSubmissionVO(HomeworkSubmission submission) {
        SubmissionVO vo = new SubmissionVO();
        vo.setId(submission.getId());
        vo.setHomeworkId(submission.getHomeworkId());
        vo.setStudentId(submission.getStudentId());
        vo.setStudentName(submission.getStudentName());
        vo.setContent(submission.getContent());
        vo.setAttachments(submission.getAttachments());
        vo.setStatus(submission.getStatus());
        vo.setSubmitTime(submission.getSubmitTime());
        vo.setReviewTime(submission.getReviewTime());
        vo.setReviewerId(submission.getReviewerId());
        vo.setReviewComment(submission.getReviewComment());
        vo.setReviewScore(submission.getReviewScore());
        return vo;
    }

    private ReviewRuleVO convertToReviewRuleVO(HomeworkReviewRule rule) {
        ReviewRuleVO vo = new ReviewRuleVO();
        vo.setId(rule.getId());
        vo.setRuleName(rule.getRuleName());
        vo.setRuleType(rule.getRuleType());
        vo.setTotalScore(rule.getTotalScore());
        vo.setDescription(rule.getDescription());

        // 查询关联的维度列表
        List<HomeworkReviewDimension> dimensions = homeworkReviewDimensionMapper.selectByRuleId(rule.getId());
        if (dimensions != null && !dimensions.isEmpty()) {
            vo.setDimensions(dimensions.stream().map(this::convertToReviewDimensionVO).collect(Collectors.toList()));
        }

        return vo;
    }

    private ReviewDimensionVO convertToReviewDimensionVO(HomeworkReviewDimension dimension) {
        ReviewDimensionVO vo = new ReviewDimensionVO();
        vo.setId(dimension.getId());
        vo.setName(dimension.getName());
        vo.setMaxScore(dimension.getMaxScore());
        vo.setDescription(dimension.getDescription());
        vo.setSortOrder(dimension.getSortOrder());
        return vo;
    }

    // ========== 新增方法实现 ==========

    @Override
    public List<ReviewRuleVO> getReviewRulesForSelect(Long tenantId) {
        // 获取所有有效的评审规则，用于下拉选择
        List<HomeworkReviewRule> rules = homeworkReviewRuleMapper.selectList(
                new LambdaQueryWrapper<HomeworkReviewRule>()
                        .eq(HomeworkReviewRule::getTenantId, tenantId)
                        .eq(HomeworkReviewRule::getDeleted, 0)
                        .orderByDesc(HomeworkReviewRule::getCreateTime)
        );
        return rules.stream()
                .map(this::convertToReviewRuleVO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReviewRuleVO updateReviewRule(Long id, UpdateReviewRuleDTO dto, Long tenantId) {
        HomeworkReviewRule rule = homeworkReviewRuleMapper.selectById(id);
        if (rule == null || !rule.getTenantId().equals(tenantId)) {
            throw new BusinessException("评审规则不存在");
        }

        if (dto.getRuleName() != null) {
            rule.setRuleName(dto.getRuleName());
        }
        if (dto.getDescription() != null) {
            rule.setDescription(dto.getDescription());
        }
        // 注意：维度列表需要单独处理
        if (dto.getDimensions() != null && !dto.getDimensions().isEmpty()) {
            // 删除原有维度
            homeworkReviewDimensionMapper.deleteByRuleId(id);
            // 插入新维度
            int sortOrder = 0;
            for (ReviewDimensionDTO dim : dto.getDimensions()) {
                HomeworkReviewDimension dimension = new HomeworkReviewDimension();
                dimension.setRuleId(id);
                dimension.setTenantId(tenantId);
                dimension.setName(dim.getName());
                dimension.setMaxScore(dim.getMaxScore());
                dimension.setDescription(dim.getDescription());
                dimension.setSortOrder(sortOrder++);
                homeworkReviewDimensionMapper.insert(dimension);
            }
        }

        homeworkReviewRuleMapper.updateById(rule);
        log.info("更新评审规则成功，ID={}", id);

        return convertToReviewRuleVO(rule);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteReviewRule(Long id, Long tenantId) {
        HomeworkReviewRule rule = homeworkReviewRuleMapper.selectById(id);
        if (rule == null || !rule.getTenantId().equals(tenantId)) {
            throw new BusinessException("评审规则不存在");
        }

        // 删除关联的维度
        homeworkReviewDimensionMapper.deleteByRuleId(id);
        // 逻辑删除规则
        rule.setDeleted(1);
        homeworkReviewRuleMapper.updateById(rule);
        log.info("删除评审规则成功，ID={}", id);
    }

    @Override
    public Page<HomeworkListVO> getMyHomeworks(HomeworkQueryDTO queryDTO, Long userId, Long tenantId) {
        Page<Homework> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        // TODO: 需要根据用户 ID 查询关联的班级/年级，进而查询作业
        // 这里简化处理：查询所有已发布的作业
        LambdaQueryWrapper<Homework> wrapper = new LambdaQueryWrapper<Homework>()
                .eq(Homework::getTenantId, tenantId)
                .eq(Homework::getDeleted, 0)
                .eq(Homework::getStatus, "published")
                .like(queryDTO.getNameKeyword() != null, Homework::getName, queryDTO.getNameKeyword())
                .orderByDesc(Homework::getCreateTime);

        Page<Homework> resultPage = this.page(page, wrapper);

        List<HomeworkListVO> voList = resultPage.getRecords().stream()
                .map(this::convertToListVO)
                .collect(Collectors.toList());

        Page<HomeworkListVO> voPage = new Page<>(
                resultPage.getCurrent(),
                resultPage.getSize(),
                resultPage.getTotal()
        );
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HomeworkDetailVO unpublish(Long id, Long tenantId) {
        Homework homework = this.getById(id);
        if (homework == null || !homework.getTenantId().equals(tenantId)) {
            throw new BusinessException("作业不存在");
        }

        homework.setStatus("unpublished");
        this.updateById(homework);
        log.info("撤销发布作业成功，ID={}", id);

        return convertToDetailVO(homework);
    }

    @Override
    public Page<SubmissionVO> getSubmissionsList(SubmissionQueryDTO queryDTO, Long tenantId) {
        Page<HomeworkSubmission> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        LambdaQueryWrapper<HomeworkSubmission> wrapper = new LambdaQueryWrapper<HomeworkSubmission>()
                .eq(HomeworkSubmission::getTenantId, tenantId)
                .eq(HomeworkSubmission::getDeleted, 0)
                .eq(queryDTO.getHomeworkId() != null, HomeworkSubmission::getHomeworkId, queryDTO.getHomeworkId())
                .like(queryDTO.getStudentName() != null, HomeworkSubmission::getStudentName, queryDTO.getStudentName())
                .eq(queryDTO.getStatus() != null, HomeworkSubmission::getStatus, queryDTO.getStatus())
                .orderByDesc(HomeworkSubmission::getSubmitTime);

        Page<HomeworkSubmission> resultPage = homeworkSubmissionMapper.selectPage(page, wrapper);

        List<SubmissionVO> voList = resultPage.getRecords().stream()
                .map(this::convertToSubmissionVO)
                .collect(Collectors.toList());

        Page<SubmissionVO> voPage = new Page<>(
                resultPage.getCurrent(),
                resultPage.getSize(),
                resultPage.getTotal()
        );
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public SubmissionVO getSubmissionDetail(Long id, Long tenantId) {
        HomeworkSubmission submission = homeworkSubmissionMapper.selectById(id);
        if (submission == null || !submission.getTenantId().equals(tenantId)) {
            throw new BusinessException("提交记录不存在");
        }

        return convertToSubmissionVO(submission);
    }

    @Override
    public List<com.lesingle.creation.vo.school.ClassTreeNodeVO> getClassTree(Long tenantId) {
        // TODO: 需要实现班级树查询逻辑
        // 这里返回空列表，后续需要根据实际的班级/年级表实现
        log.warn("getClassTree 方法暂未实现，tenantId={}", tenantId);
        return List.of();
    }

    @Override
    public SubmissionVO getMySubmission(Long homeworkId, Long userId, Long tenantId) {
        HomeworkSubmission submission = homeworkSubmissionMapper.selectOne(
                new LambdaQueryWrapper<HomeworkSubmission>()
                        .eq(HomeworkSubmission::getTenantId, tenantId)
                        .eq(HomeworkSubmission::getHomeworkId, homeworkId)
                        .eq(HomeworkSubmission::getStudentId, userId)
                        .eq(HomeworkSubmission::getDeleted, 0)
        );

        if (submission == null) {
            return null;
        }

        return convertToSubmissionVO(submission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SubmissionVO createScore(CreateScoreDTO dto, Long tenantId, Long reviewerId) {
        HomeworkSubmission submission = homeworkSubmissionMapper.selectById(dto.getSubmissionId());
        if (submission == null || !submission.getTenantId().equals(tenantId)) {
            throw new BusinessException("提交记录不存在");
        }

        // TODO: 保存维度评分到 homework_dimension_scores 表
        // 这里先更新总分和评语
        if (dto.getDimensionScores() != null && !dto.getDimensionScores().isEmpty()) {
            java.math.BigDecimal totalScore = dto.getDimensionScores().stream()
                    .map(com.lesingle.creation.dto.homework.DimensionScoreDTO::getScore)
                    .reduce(java.math.BigDecimal.ZERO, java.math.BigDecimal::add);
            submission.setReviewScore(totalScore);
        }
        submission.setReviewComment(dto.getComments());
        submission.setReviewerId(reviewerId);
        submission.setStatus("reviewing");
        submission.setReviewTime(LocalDateTime.now());

        homeworkSubmissionMapper.updateById(submission);
        log.info("创建评分成功，提交 ID={}, 评审人 ID={}", dto.getSubmissionId(), reviewerId);

        return convertToSubmissionVO(submission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void markViolation(Long submissionId, String reason, Long tenantId) {
        HomeworkSubmission submission = homeworkSubmissionMapper.selectById(submissionId);
        if (submission == null || !submission.getTenantId().equals(tenantId)) {
            throw new BusinessException("提交记录不存在");
        }

        submission.setStatus("violation");
        submission.setReviewComment("违规：" + reason);
        homeworkSubmissionMapper.updateById(submission);
        log.info("标记违规成功，提交 ID={}, 原因={}", submissionId, reason);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetScore(Long submissionId, Long tenantId) {
        HomeworkSubmission submission = homeworkSubmissionMapper.selectById(submissionId);
        if (submission == null || !submission.getTenantId().equals(tenantId)) {
            throw new BusinessException("提交记录不存在");
        }

        submission.setReviewScore(null);
        submission.setReviewComment(null);
        submission.setReviewerId(null);
        submission.setStatus("submitted");
        homeworkSubmissionMapper.updateById(submission);
        log.info("重置评分成功，提交 ID={}", submissionId);
    }
}
