package cn.reghao.tnb.content.app.exam.service;

import cn.reghao.jutil.jdk.web.db.Page;
import cn.reghao.jutil.jdk.web.db.PageList;
import cn.reghao.tnb.auth.api.dto.AccountInfo;
import cn.reghao.tnb.auth.api.iface.AccountQuery;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.app.exam.db.mapper.*;
import cn.reghao.tnb.content.app.exam.model.constant.QuestionType;
import cn.reghao.tnb.content.app.exam.model.dto.UserResult;
import cn.reghao.tnb.content.app.exam.model.po.*;
import cn.reghao.tnb.content.app.exam.model.query.ExamQuery;
import cn.reghao.tnb.content.app.exam.model.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author reghao
 * @date 2024-08-29 09:55:20
 */
@Service
public class MarkService {
    @DubboReference(check = false, retries = 0)
    private AccountQuery accountQuery;

    private final PaperResultMapper paperResultMapper;
    private final PaperAnswerMapper paperAnswerMapper;

    public MarkService(PaperResultMapper paperResultMapper, PaperAnswerMapper paperAnswerMapper) {
        this.paperResultMapper = paperResultMapper;
        this.paperAnswerMapper = paperAnswerMapper;
    }

    public PageList<ExamMark> getExamReviewList(ExamQuery examQuery) {
        int total = paperResultMapper.countByCriteria(examQuery);
        Page page = examQuery.getPage();
        List<ExamResults> list = paperResultMapper.findExamResultsByPage(page, examQuery);
        List<ExamMark> list1 = list.stream()
                .map(examResults -> {
                    long userId = examResults.getStudent();
                    String student = ""+userId;
                    AccountInfo accountInfo = accountQuery.getAccountInfo(userId);
                    if (accountInfo != null) {
                        student = accountInfo.getScreenName();
                    }
                    return new ExamMark(examResults, student, userId);
                })
                .collect(Collectors.toList());
        return PageList.pageList(page, total, list1);
    }

    @Transactional(rollbackFor = Exception.class)
    public void markExamResult(UserResult userResult) {
        int paperId = userResult.getPaperId();
        long loginUser = UserContext.getUserId();
        PaperResult paperResult = getPaperResult(paperId, loginUser);
        if (paperResult == null) {
            return;
        }

        int totalSubjectiveScore = 0;
        int resultId = paperResult.getId();
        for (QuestionAnswer questionAnswer : userResult.getSubmitUserAnswers()) {
            long questionId = questionAnswer.getQuestionId();
            int questionType = questionAnswer.getQuestionType();
            if (questionType <= QuestionType.QUESTION3.getCode()) {
                continue;
            }

            String review = "";
            int submitScore = questionAnswer.getSubmitScore();
            paperAnswerMapper.updatePaperAnswer(resultId, questionId, review, submitScore);
            totalSubjectiveScore += submitScore;
        }

        paperResultMapper.updateSetResultMarked(resultId, totalSubjectiveScore);
    }

    private PaperResult getPaperResult(int paperId, long userId) {
        ExamQuery examQuery = new ExamQuery.Builder()
                .loginUser(userId)
                .paperId(paperId)
                .build();
        Page page = examQuery.getPage();
        List<PaperResult> list = paperResultMapper.findPaperResultByPage(page, examQuery);
        return list.isEmpty() ? null : list.get(0);
    }
}
