package com.qmth.distributed.print.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.distributed.print.business.bean.dto.open.PaperConfig;
import com.qmth.distributed.print.business.bean.params.analyze.GradeModuleKnowledgeDefineParam;
import com.qmth.distributed.print.business.bean.params.analyze.GradePaperDefineParam;
import com.qmth.distributed.print.business.bean.result.analyze.GradePaperDefineResult;
import com.qmth.distributed.print.business.entity.GradeModuleDefine;
import com.qmth.distributed.print.business.entity.GradePaper;
import com.qmth.teachcloud.common.enums.DimensionEnum;
import com.qmth.distributed.print.business.mapper.GradePaperMapper;
import com.qmth.distributed.print.business.service.GradeBatchPaperService;
import com.qmth.distributed.print.business.service.GradeModuleDefineService;
import com.qmth.distributed.print.business.service.GradePaperService;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.AssignEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 试卷基础信息表（赋分系数、试卷类型、满分、及格分等） 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2022-05-20
 */
@Service
public class GradePaperServiceImpl extends ServiceImpl<GradePaperMapper, GradePaper> implements GradePaperService {
    @Resource
    private GradeBatchPaperService gradeBatchPaperService;
    @Resource
    private GradeModuleDefineService gradeModuleDefineService;

    @Override
    public GradePaperDefineResult findGradePaperDefine(String paperNumber, String paperType, SysUser requestUser) {
        Long schoolId = requestUser.getSchoolId();
        GradePaper gradePaper = this.getOne(new QueryWrapper<GradePaper>()
                .lambda()
                .eq(GradePaper::getSchoolId, schoolId)
                .eq(GradePaper::getPaperNumber, paperNumber)
                .eq(GradePaper::getPaperType, paperType));


        List<GradeModuleDefine> gradeModuleDefineList = gradeModuleDefineService.list(new QueryWrapper<GradeModuleDefine>()
                .lambda()
                .eq(GradeModuleDefine::getSchoolId, schoolId)
                .eq(GradeModuleDefine::getPaperNumber, paperNumber)
                .eq(GradeModuleDefine::getPaperType, paperType));

        GradePaperDefineResult gradePaperDefineResult = new GradePaperDefineResult();
        if (Objects.isNull(gradePaper) && gradeModuleDefineList.isEmpty()){
            return null;
        }
        if (Objects.nonNull(gradePaper)) {
            gradePaperDefineResult.setTotalScore(gradePaper.getTotalScore());
            gradePaperDefineResult.setPassScore(gradePaper.getPassScore());
        }
        if (gradeModuleDefineList != null && gradeModuleDefineList.size() > 0) {
            // 知识维度
            List<GradeModuleDefine> gradeModuleKnowledgeDefineList = gradeModuleDefineList.stream()
                    .filter(e -> DimensionEnum.KNOWLEDGE.equals(e.getModuleType()))
                    .collect(Collectors.toList());
            if (gradeModuleKnowledgeDefineList.size() > 0) {
                gradePaperDefineResult.setKnowledgeInterpret(gradeModuleKnowledgeDefineList.get(0).getInterpret());
                List<GradeModuleKnowledgeDefineParam> gradeModuleKnowledgeDefineParamList = gradeModuleKnowledgeDefineList.stream().flatMap(e -> {
                    GradeModuleKnowledgeDefineParam cell = new GradeModuleKnowledgeDefineParam();
                    cell.setDefine(e.getDefine());
                    cell.setLevel(e.getLevel());
                    cell.setScope(e.getScope());
                    cell.setMax(e.getMax());
                    cell.setMin(e.getMin());
                    return Stream.of(cell);
                }).collect(Collectors.toList());
                gradePaperDefineResult.setGradeModuleKnowledgeDefineParamList(gradeModuleKnowledgeDefineParamList);
            }
            // 能力维度
            List<GradeModuleDefine> gradeModuleAbilityDefineList = gradeModuleDefineList.stream()
                    .filter(e -> DimensionEnum.ABILITY.equals(e.getModuleType()))
                    .collect(Collectors.toList());
            if (gradeModuleAbilityDefineList.size() > 0) {
                gradePaperDefineResult.setAbilityInterpret(gradeModuleAbilityDefineList.get(0).getInterpret());
            }
        }
        return gradePaperDefineResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveGradePaperDefine(GradePaperDefineParam gradePaperDefineParam, SysUser requestUser) {
        this.saveGradePaper(gradePaperDefineParam, requestUser);
        gradeModuleDefineService.saveGradeModuleDefineBatch(gradePaperDefineParam, requestUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long saveGradePaper(GradePaperDefineParam gradePaperDefineParam, SysUser requestUser) {
        String paperNumber = gradePaperDefineParam.getPaperNumber();
        String paperType = gradePaperDefineParam.getPaperType();
        String paperName = gradePaperDefineParam.getPaperName();
        Long schoolId = requestUser.getSchoolId();

        // 判断分析课程是否有操作权限
        gradeBatchPaperService.checkOperateAuth(schoolId, paperNumber, paperType);

        BigDecimal totalScore = gradePaperDefineParam.getTotalScore();
        BigDecimal passScore = gradePaperDefineParam.getPassScore();

        GradePaper gradePaper = new GradePaper();
        gradePaper.setSchoolId(schoolId);
        gradePaper.setPaperNumber(paperNumber);
        gradePaper.setPaperType(paperType);
        gradePaper.setPaperName(paperName);
        gradePaper.setCoefficient(BigDecimal.ZERO);
        gradePaper.setTotalScore(totalScore);
        gradePaper.setPassScore(passScore);
        gradePaper.setScoreType(AssignEnum.NO_NEED_ASSIGN_SCORE);

        // 删除原有的
        this.remove(new QueryWrapper<GradePaper>()
                .lambda()
                .eq(GradePaper::getSchoolId, schoolId)
                .eq(GradePaper::getPaperNumber, paperNumber)
                .eq(GradePaper::getPaperType, paperType));

        gradePaper.insertInfo(requestUser.getId());
        this.save(gradePaper);
        return gradePaper.getId();
    }

    @Override
    public PaperConfig findBySchoolIdAndPaperNumberAndPaperType(Long schoolId, String paperNumber, String paperType) {
        return this.baseMapper.findBySchoolIdAndPaperNumberAndPaperType(schoolId, paperNumber, paperType);
    }
}
