package com.ynfy.buss.exam.examreview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynfy.buss.exam.exam.enums.PaperState;
import com.ynfy.buss.exam.examreview.dto.ExamPreviewDTO;
import com.ynfy.buss.exam.examreview.dto.PreviewSubmitDTO;
import com.ynfy.buss.exam.examreview.entity.ExamReview;
import com.ynfy.buss.exam.examreview.mapper.ExamReviewMapper;
import com.ynfy.buss.exam.examreview.service.IExamReviewService;
import com.ynfy.buss.exam.question.enums.QuestionType;
import com.ynfy.buss.exam.userexam.entity.UserExam;
import com.ynfy.buss.exam.userexam.service.IUserExamService;
import com.ynfy.buss.exam.userexamquestion.entity.UserExamQuestion;
import com.ynfy.buss.exam.userexamquestion.service.IUserExamQuestionService;
import com.ynfy.buss.exam.userexamresult.service.IUserExamResultService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 阅卷表
 * @Author: jeecg-boot
 * @Date: 2023-04-08
 * @Version: V1.0
 */
@Service
public class ExamReviewServiceImpl extends ServiceImpl<ExamReviewMapper, ExamReview> implements IExamReviewService {

    @Autowired
    private ExamReviewMapper examReviewMapper;

    @Autowired
    private IUserExamService userExamService;

    @Autowired
    private IUserExamQuestionService userExamQuestionService;

    @Autowired
    private IUserExamResultService userExamResultService;


    /**
     * 统计需阅卷的考试
     *
     * @return
     */
    @Override
    public List<ExamReview> calcReview() {
        return examReviewMapper.calcReview();
    }

    @Override
    public boolean removeByExamIds(List<String> examIds) {
        LambdaQueryWrapper<ExamReview> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ExamReview::getId, examIds);
        return remove(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(List<ExamReview> examReviews) {
        if (!CollectionUtils.isEmpty(examReviews)) {
            List<String> examIds = examReviews.stream().map(ExamReview::getId).collect(Collectors.toList());
            removeByExamIds(examIds);
            saveBatch(examReviews);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitPreview(PreviewSubmitDTO dto) {
        if (StringUtils.isEmpty(dto.getUserExamId())) {
            throw new JeecgBootException("考试ID不能为空");
        }
        UserExam userExam = userExamService.listUserExam(dto.getUserExamId());
        if (Objects.isNull(userExam)) {
            throw new JeecgBootException("考试记录不存在");
        }
        if (PaperState.FINISHED.equals(userExam.getState())) {
            throw new JeecgBootException("该试卷已经阅卷，不允许重复阅卷");
        }
        List<UserExamQuestion> userExamQuestionList = userExam.getUserExamQuestionList();
        if (CollectionUtils.isEmpty(userExamQuestionList)) {
            throw new JeecgBootException("考题查询失败");
        }

        //获取主观题
        List<UserExamQuestion> subjectiveList = userExamQuestionList.stream().filter(o -> o.getQuestionType()
                .equals(QuestionType.SIMPLE.getCode())).collect(Collectors.toList());
        Map<Integer, UserExamQuestion> subjectiveMap = subjectiveList.stream().collect(Collectors
                .toMap(UserExamQuestion::getQuestionIndex, a -> a, (k1, k2) -> k1));
        List<ExamPreviewDTO> examPreviews = dto.getExamPreviews();

        if (!CollectionUtils.isEmpty(examPreviews)) {
            int subjectiveScore = 0;
            for (ExamPreviewDTO o : examPreviews) {
                UserExamQuestion userExamQuestion = subjectiveMap.get(o.getIndex());
                userExamQuestion.setActualScore(o.getActualScore());
                userExamQuestion.setIsRight(o.getIsRight());
                subjectiveScore += o.getActualScore();
            }
            //更新评分
            userExamQuestionService.updateBatchById(userExamQuestionList);

            //用户得分，主观题得分，更新阅卷人，阅卷时间,考试状态
            userExam.setSubjectiveScore(subjectiveScore);//主观题得分
            userExam.setUserScore(userExam.getUserScore() + subjectiveScore);//用户最终得分
            userExam.setPreviewTime(new Date());
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            userExam.setPreviewUser(user.getRealname());
            userExam.setState(PaperState.FINISHED);
            int pass = userExam.getUserScore() >= userExam.getQualifyScore() ? 1 : 0;
            userExam.setPassed(pass);
            userExamService.updateById(userExam);

            //考试完成后加入成绩
            userExamResultService.joinResult(userExam.getUserId(), userExam.getExamId(), userExam.getUserScore(), pass);
        }
    }


    @Override
    public IPage<ExamReview> selectPageList(IPage<ExamReview> page, ExamReview examReview, LoginUser user) {
        return examReviewMapper.selectPageList(page, examReview, user);
    }

}
