package com.ynfy.buss.exam.paperrulegroup.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.exam.dto.QuestionTypeCountDTO;
import com.ynfy.buss.exam.paper.enmus.JoinType;
import com.ynfy.buss.exam.paper.entity.Paper;
import com.ynfy.buss.exam.paper.service.IPaperService;
import com.ynfy.buss.exam.paperquestion.service.IPaperQuestionService;
import com.ynfy.buss.exam.paperquestionanswer.service.IPaperQuestionAnswerService;
import com.ynfy.buss.exam.paperruledetail.entity.PaperRuleDetail;
import com.ynfy.buss.exam.paperruledetail.service.IPaperRuleDetailService;
import com.ynfy.buss.exam.paperrulegroup.entity.PaperRuleGroup;
import com.ynfy.buss.exam.paperrulegroup.mapper.PaperRuleGroupMapper;
import com.ynfy.buss.exam.paperrulegroup.service.IPaperRuleGroupService;
import com.ynfy.buss.exam.question.enums.QuestionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Description: paper_rule_group
 * @Author: jeecg-boot
 * @Date: 2023-02-22
 * @Version: V1.0
 */
@Service
public class PaperRuleGroupServiceImpl extends ServiceImpl<PaperRuleGroupMapper, PaperRuleGroup> implements IPaperRuleGroupService {

    @Autowired
    private IPaperRuleDetailService paperRuleDetailService;

    @Autowired
    @Lazy
    private IPaperService paperService;

    @Autowired
    private IPaperQuestionService paperQuestionService;

    @Autowired
    private PaperRuleGroupMapper paperRuleGroupMapper;

    @Autowired
    private IPaperQuestionAnswerService paperQuestionAnswerService;


    /**
     * 保存试卷规则组
     */
    @Override
    public void saveAll(Paper paper, List<PaperRuleGroup> groupList) {
        //移除规则组
        remove(paper.getId());
        //移除规则明细
        paperRuleDetailService.remove(paper.getId());
        //移除试卷关联的试题
        paperQuestionService.remove(paper.getId());
        //删除多选题漏选分值
        paperQuestionAnswerService.remove(paper.getId());
        if (!CollectionUtils.isEmpty(groupList)) {
            if (paper.getJoinType().equals(JoinType.SJ.getCode())) {//随机组卷
                saveRandom(paper, groupList);
            } else if (paper.getJoinType().equals(JoinType.XT.getCode()) || paper.getJoinType().equals(JoinType.CT.getCode())) {//选题组卷或者抽题组卷
                saveSelect(paper, groupList);
            }
        }
    }


    /**
     * 选题组卷保存
     *
     * @param paper
     * @param groupList
     */
    public void saveSelect(Paper paper, List<PaperRuleGroup> groupList) {
        int sort = 1;
        for (PaperRuleGroup item : groupList) {
            item.setPaperId(paper.getId());
            item.setSort(sort);
            sort++;
        }
        //保存规则组
        saveBatch(groupList);
        paperQuestionService.saveAll(paper.getId(), groupList);

        //更新试卷
        paper.setHasSubjective(hasSubjective(groupList));
        paperService.saveOrUpdate(paper);
    }

    /**
     * 随机组卷保存
     *
     * @param paper
     * @param groupList
     */
    public void saveRandom(Paper paper, List<PaperRuleGroup> groupList) {
        int allQuestionNum = 0;
        int sort = 1;
        int totalScore = 0;
        for (PaperRuleGroup item : groupList) {
            item.setPaperId(paper.getId());
            Integer questionNum = item.getRuleList().stream().mapToInt(PaperRuleDetail::getNum).sum();
            item.setQuestionCount(questionNum);
            int groupTotalScore = questionNum * item.getPerScore();
            item.setTotalScore(groupTotalScore);
            totalScore += groupTotalScore;
            allQuestionNum += questionNum;
            item.setSort(sort);
            sort++;
        }
        //保存规则组
        saveBatch(groupList);
        //保存规则明细
        paperRuleDetailService.saveAll(paper.getId(), groupList);

        //更新试卷
        paper.setHasSubjective(hasSubjective(groupList));
        paper.setTotalScore(totalScore);
        paper.setQuestionCount(allQuestionNum);
        paperService.saveOrUpdate(paper);
    }


    /**
     * 试卷是否存在主观题
     *
     * @param groupList
     * @return
     */
    public boolean hasSubjective(List<PaperRuleGroup> groupList) {
        //主观题
        long subjectiveNum = groupList.stream().filter(o -> o.getQuestionType().equals(QuestionType.SIMPLE.getCode())).count();
        return subjectiveNum > 0 ? true : false;
    }


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

    /**
     * 根据试卷id查询规则组
     */
    @Override
    public List<PaperRuleGroup> listByPaperId(String paperId) {
        LambdaQueryWrapper<PaperRuleGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaperRuleGroup::getPaperId, paperId);
        queryWrapper.orderByAsc(PaperRuleGroup::getSort);
        return this.list(queryWrapper);
    }

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

    /**
     * 根据试卷id获取抽题规则组以及规则明细
     *
     * @param paperId
     * @return
     */
    @Override
    public List<PaperRuleGroup> listGroupAndDetail(String paperId) {
        return paperRuleGroupMapper.listGroupAndDetail(paperId);
    }


    /**
     * 根据试卷id获取每种题型数量
     *
     * @param paperId
     * @return
     */
    @Override
    public List<QuestionTypeCountDTO> sumQuestionCount(String paperId) {
        return paperRuleGroupMapper.sumQuestionCount(paperId);
    }
}
