package com.competition.modules.biz.homework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.competition.common.enums.ErrorCode;
import com.competition.common.exception.BusinessException;
import com.competition.modules.biz.homework.dto.CreateHomeworkScoreDto;
import com.competition.modules.biz.homework.entity.BizHomeworkScore;
import com.competition.modules.biz.homework.entity.BizHomeworkSubmission;
import com.competition.modules.biz.homework.mapper.HomeworkScoreMapper;
import com.competition.modules.biz.homework.service.IHomeworkScoreService;
import com.competition.modules.biz.homework.service.IHomeworkSubmissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class HomeworkScoreServiceImpl extends ServiceImpl<HomeworkScoreMapper, BizHomeworkScore> implements IHomeworkScoreService {

    private final HomeworkScoreMapper homeworkScoreMapper;
    @Lazy
    private final IHomeworkSubmissionService homeworkSubmissionService;

    @Override
    @Transactional
    public BizHomeworkScore create(CreateHomeworkScoreDto dto, Long reviewerId, Long tenantId) {
        log.info("创建作业评分，提交ID：{}，评审人：{}", dto.getSubmissionId(), reviewerId);

        // 验证提交存在
        BizHomeworkSubmission submission = homeworkSubmissionService.getById(dto.getSubmissionId());
        if (submission == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "作业提交不存在");
        }

        BizHomeworkScore entity = new BizHomeworkScore();
        entity.setTenantId(tenantId);
        entity.setSubmissionId(dto.getSubmissionId());
        entity.setReviewerId(reviewerId);
        entity.setDimensionScores(dto.getDimensionScores());
        entity.setTotalScore(dto.getTotalScore());
        entity.setComments(dto.getComments());
        entity.setScoreTime(LocalDateTime.now());

        save(entity);
        log.info("作业评分创建成功，ID：{}", entity.getId());

        // 更新提交的总分和状态
        submission.setTotalScore(dto.getTotalScore());
        submission.setStatus("reviewed");
        homeworkSubmissionService.updateById(submission);
        log.info("作业提交状态已更新为reviewed，提交ID：{}", submission.getId());

        return entity;
    }

    @Override
    public List<Map<String, Object>> findBySubmission(Long submissionId) {
        log.info("查询作业提交的评分记录，提交ID：{}", submissionId);

        LambdaQueryWrapper<BizHomeworkScore> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizHomeworkScore::getSubmissionId, submissionId);
        wrapper.eq(BizHomeworkScore::getValidState, 1);
        wrapper.orderByDesc(BizHomeworkScore::getScoreTime);

        List<BizHomeworkScore> list = homeworkScoreMapper.selectList(wrapper);
        return list.stream().map(this::entityToMap).collect(Collectors.toList());
    }

    // ====== 私有辅助方法 ======

    private Map<String, Object> entityToMap(BizHomeworkScore entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("id", entity.getId());
        map.put("tenantId", entity.getTenantId());
        map.put("submissionId", entity.getSubmissionId());
        map.put("reviewerId", entity.getReviewerId());
        map.put("dimensionScores", entity.getDimensionScores());
        map.put("totalScore", entity.getTotalScore());
        map.put("comments", entity.getComments());
        map.put("scoreTime", entity.getScoreTime());
        map.put("createTime", entity.getCreateTime());
        map.put("modifyTime", entity.getModifyTime());
        return map;
    }
}
