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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynfy.buss.exam.paperquestionanswer.entity.PaperQuestionAnswer;
import com.ynfy.buss.exam.paperquestionanswer.mapper.PaperQuestionAnswerMapper;
import com.ynfy.buss.exam.paperquestionanswer.service.IPaperQuestionAnswerService;
import com.ynfy.buss.exam.question.entity.Question;
import com.ynfy.buss.exam.questionanswer.entity.QuestionAnswer;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 试卷试题答案
 * @Author: jeecg-boot
 * @Date: 2023-04-05
 * @Version: V1.0
 */
@Service
public class PaperQuestionAnswerServiceImpl extends ServiceImpl<PaperQuestionAnswerMapper, PaperQuestionAnswer> implements IPaperQuestionAnswerService {

    @Override
    public List<PaperQuestionAnswer> listByPaperId(String paperId) {
        LambdaQueryWrapper<PaperQuestionAnswer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaperQuestionAnswer::getPaperId, paperId);
        return this.list(wrapper);
    }

    @Override
    public void remove(String paperId) {
        LambdaQueryWrapper<PaperQuestionAnswer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaperQuestionAnswer::getPaperId, paperId);
        this.remove(wrapper);
    }

    @Override
    public void save(String paperId, Question question) {
        List<QuestionAnswer> answerList = question.getAnswerList();
        if (!CollectionUtils.isEmpty(answerList)) {
            List<QuestionAnswer> pathScoreList = answerList.stream().filter(o ->
                    !Objects.isNull(o.getPathScore()) && o.getPathScore() > 0).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(pathScoreList)) {
                List<PaperQuestionAnswer> paperQuestionAnswerList = new ArrayList<>();
                pathScoreList.stream().forEach(ps -> {
                    PaperQuestionAnswer pqa = new PaperQuestionAnswer();
                    pqa.setPaperId(paperId);
                    pqa.setQuestionId(question.getId());
                    pqa.setAnswerId(ps.getId());
                    pqa.setPathScore(ps.getPathScore());
                    paperQuestionAnswerList.add(pqa);
                });
                if (!CollectionUtils.isEmpty(paperQuestionAnswerList)) {
                    saveBatch(paperQuestionAnswerList);
                }
            }
        }
    }
}
