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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynfy.buss.exam.paperquestion.entity.PaperQuestion;
import com.ynfy.buss.exam.paperquestion.mapper.PaperQuestionMapper;
import com.ynfy.buss.exam.paperquestion.service.IPaperQuestionService;
import com.ynfy.buss.exam.paperquestionanswer.service.IPaperQuestionAnswerService;
import com.ynfy.buss.exam.paperrulegroup.entity.PaperRuleGroup;
import com.ynfy.buss.exam.question.entity.Question;
import com.ynfy.buss.exam.question.enums.QuestionType;
import com.ynfy.buss.exam.userexamquestion.service.IUserExamQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * @Description: paper_question
 * @Author: jeecg-boot
 * @Date: 2023-02-23
 * @Version: V1.0
 */
@Service
public class PaperQuestionServiceImpl extends ServiceImpl<PaperQuestionMapper, PaperQuestion> implements IPaperQuestionService {

    @Autowired
    private IUserExamQuestionService userExamQuestionService;

    @Autowired
    private PaperQuestionMapper paperQuestionMapper;

    @Autowired
    private IPaperQuestionAnswerService paperQuestionAnswerService;

    /**
     * 删除已保存
     */
    @Override
    public void remove(String paperId) {
        QueryWrapper<PaperQuestion> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(PaperQuestion::getPaperId, paperId);
        this.remove(wrapper);
    }

    /**
     * 试卷试题排序并保存
     *
     * @param paperQuestions
     */
    @Override
    public List<PaperQuestion> sort(List<PaperQuestion> paperQuestions) {
        if (!CollectionUtils.isEmpty(paperQuestions)) {
            //按题型排序并编号
            paperQuestions = paperQuestions.stream().sorted(Comparator.comparing(PaperQuestion::getQuestionType)).collect(Collectors.toList());
            int sort = 1;
            for (PaperQuestion pq : paperQuestions) {
                pq.setSort(sort);
                sort++;
            }
        }
        return paperQuestions;
    }

    /**
     * 保存试卷试题和答案
     *
     * @param paperId
     * @param groupList
     */
    @Override
    public void saveAll(String paperId, List<PaperRuleGroup> groupList) {
        if (!CollectionUtils.isEmpty(groupList)) {
            groupList.forEach(g -> {
                List<PaperQuestion> paperQuestionList = new ArrayList<>();
                List<Question> questionList = g.getQuestionList();
                int sort = 1;
                if (!CollectionUtils.isEmpty(questionList)) {
                    if (QuestionType.COMBINATION.getCode().equals(g.getQuestionType())) {//组合题
                        for (Question q : questionList) {
                            double questionScore = q.getSubQuestionList().stream().filter(o ->
                                    !Objects.isNull(o.getScore())).mapToDouble(Question::getScore).sum();
                            PaperQuestion root = generatePaperQuestion(paperId, g, q, sort, questionScore);
                            paperQuestionList.add(root);
                            //子题目
                            q.getSubQuestionList().forEach(sub -> {
                                PaperQuestion paperSubQuestion = generatePaperQuestion(paperId, g, sub, sub.getSort(), sub.getScore());
                                paperSubQuestion.setParentQuestionId(q.getId());
                                //多选题漏选也给分，填空题按空给分设置（保存答案）
                                groupAnswerConfig(paperId, g, sub);

                                paperQuestionList.add(paperSubQuestion);
                            });
                        }
                    } else {//非组合题（单选，多选，判断，填空，简答）
                        for (Question q : questionList) {
                            groupAnswerConfig(paperId, g, q);
                            //生成试卷试题
                            paperQuestionList.add(generatePaperQuestion(paperId, g, q, sort, q.getScore()));
                            sort++;
                        }
                    }
                }
                saveBatch(paperQuestionList);
            });
        }
    }

    /**
     * 生成试卷试题
     *
     * @param paperId
     * @param g
     * @param q
     * @param sort
     * @return
     */
    public PaperQuestion generatePaperQuestion(String paperId, PaperRuleGroup g, Question q,
                                               Integer sort, Double questionScore) {
        PaperQuestion paperQuestion = new PaperQuestion();
        paperQuestion.setGroupId(g.getId());
        paperQuestion.setPaperId(paperId);
        paperQuestion.setQuestionId(q.getId());
        paperQuestion.setQuestionType(q.getType());
        paperQuestion.setChild(q.getChild());
        paperQuestion.setQuestionScore(questionScore);
        paperQuestion.setSort(sort);
        return paperQuestion;
    }

    /**
     * 多选题漏选也给分，填空题按空给分设置（保存答案）
     *
     * @param paperId
     * @param g
     * @param q
     */
    public void groupAnswerConfig(String paperId, PaperRuleGroup g, Question q) {
        //多选题漏选选项分值（漏选也给分）
        if (QuestionType.MULTI.getCode().equals(q.getType()) && !Objects.isNull(g.getCanMissOption()) && g.getCanMissOption()) {
            paperQuestionAnswerService.save(paperId, q, g.getQuestionType());
            //填空题按空给分
        } else if (QuestionType.BLANK.getCode().equals(q.getType()) && !Objects.isNull(g.getCanBlankOption()) && g.getCanBlankOption()) {
            paperQuestionAnswerService.save(paperId, q, g.getQuestionType());
        }
    }

    @Override
    public List<PaperQuestion> listByPaperId(String paperId) {
        return paperQuestionMapper.listByPaperId(paperId);
    }

    @Override
    public void removeByQuestionIds(String[] paperIds) {
        QueryWrapper<PaperQuestion> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(PaperQuestion::getPaperId, paperIds);
        this.remove(wrapper);
    }

    /**
     * 检查题目是否已经被试卷使用
     *
     * @param questionIds
     * @return
     */
    @Override
    public boolean checkIsUsedInPaper(String[] questionIds) {
        LambdaQueryWrapper<PaperQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(PaperQuestion::getQuestionId, questionIds);
        return this.count(wrapper) > 0 ? true : false;
    }


    /**
     * 检查题目是否已经被使用
     *
     * @param questionIds
     * @return
     */
    @Override
    public boolean checkIsUsed(String[] questionIds) {
        return checkIsUsedInPaper(questionIds) || userExamQuestionService.checkIsUsedInExam(questionIds);
    }

    @Override
    public List<PaperQuestion> listPaperSubQuestionByIds(String paperId, List<String> combinationIdList) {
        LambdaQueryWrapper<PaperQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaperQuestion::getPaperId, paperId)
                .in(PaperQuestion::getParentQuestionId, combinationIdList).eq(PaperQuestion::getChild, true);
        return list(wrapper);
    }
}
