package cn.com.qmth.examcloud.core.questions.service.impl;

import cn.com.qmth.examcloud.commons.exception.StatusException;
import cn.com.qmth.examcloud.core.questions.api.bean.PaperK12Bean;
import cn.com.qmth.examcloud.core.questions.base.CommonUtils;
import cn.com.qmth.examcloud.core.questions.base.Model;
import cn.com.qmth.examcloud.core.questions.base.enums.PaperType;
import cn.com.qmth.examcloud.core.questions.dao.*;
import cn.com.qmth.examcloud.core.questions.dao.entity.*;
import cn.com.qmth.examcloud.core.questions.service.ExtractConfigService;
import cn.com.qmth.examcloud.core.questions.service.PaperProviderService;
import cn.com.qmth.examcloud.question.commons.core.paper.DefaultPaper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author weiwenhai
 * @date 2018.10.8
 * @company qmth
 * @description paperProviderServiceImpl
 * @code 014
 */
@Service("paperProviderServiceImpl")
public class PaperProviderServiceImpl implements PaperProviderService {

    private static final Logger LOG = LoggerFactory.getLogger(PaperProviderServiceImpl.class);

    @Autowired
    private QuesRepo quesRepo;

    @Autowired
    PaperRepo paperRepo;

    @Autowired
    PaperDetailRepo paperDetailRepo;

    @Autowired
    PaperDetailUnitRepo paperDetailUnitRepo;

    @Autowired
    ExtractConfigProviderServiceImpl extractConfigProviderServiceImpl;

    @Autowired
    ExtractConfigService extractConfigService;

    @Autowired
    ExtractConfigRepo extractConfigRepo;

    @Override
    public String genPaper(Set<String> questionIds, Map<String, PaperK12Bean> map, String paperName, String orgId, String userName) {
        if (questionIds == null || questionIds.size() < 1) {
            throw new StatusException("Q-014038", "questionIds is null");
        }
        if (map == null || map.size() < 1) {
            throw new StatusException("Q-014041", "map is null");
        }
        //查询所有试题集合
        List<Question> questions = quesRepo.findByIdIn(questionIds);
        if (CollectionUtils.isEmpty(questions)) {
            LOG.error("根据试题id的集合没有查询到试题结合");
            throw new StatusException("Q-014041", "根据试题id的集合没有查询到试题结合");
        }
        //构建试卷对象
        Paper paper = initPaper(paperName, orgId, userName);
        //构建大题对象，未设置
        PaperDetail paperDetail = initPaperDetail(paper);
        //构建包装试题对象
        List<PaperDetailUnit> paperDetailUnits = buildUnits(paper, paperDetail, questions, map);
        paper = paperRepo.save(paper);
        paperDetailRepo.save(paperDetail);
        quesRepo.saveAll(questions);
        paperDetailUnitRepo.saveAll(paperDetailUnits);
        return paper.getId();
    }

    /**
     * 构建大题对象
     *
     * @param paper
     * @return
     */
    private PaperDetail initPaperDetail(Paper paper) {
        PaperDetail paperDetail = new PaperDetail();
        paperDetail.setPaper(paper);
        paperDetail.setName("默认大题");
        paperDetail.setNumber(1);
        paperDetail.setCreator(paper.getCreator());
        return paperDetail;
    }

    /**
     * 构建试卷对象
     *
     * @param paperName
     * @return
     */
    private Paper initPaper(String paperName, String orgId, String userName) {
        Paper paper = new Paper();
        //初始化默认课程
        Course course = new Course();
        course.setId("k12");
        course.setId("k12");
        course.setName("k12");
        course.setOrgId(orgId);
        course.setCreateTime(CommonUtils.getCurDateTime());
        course.setEnable("true");
        paper.setCourse(course);
        paper.setName(paperName);
        paper.setTitle(paperName);
        paper.setPaperType(PaperType.GENERATE);
        paper.setOrgId(orgId);
        paper.setCreator(userName);
        paper.setCreateTime(CommonUtils.getCurDateTime());
        return paper;
    }

    /**
     * 构建题包装器
     *
     * @param questions
     * @param map
     * @return
     */
    private List<PaperDetailUnit> buildUnits(Paper paper, PaperDetail paperDetail, List<Question> questions, Map<String, PaperK12Bean> map) {
        List<PaperDetailUnit> paperDetailUnits = new ArrayList<>();
        int j = 0;
        double score = 0;
        double sum = 0;
        for (int i = 0; i < questions.size(); i++) {
            PaperDetailUnit paperDetailUnit = new PaperDetailUnit();
            paperDetailUnit.setNumber(i + 1);
            paperDetailUnit.setQuestion(questions.get(i));
            paperDetailUnit.setPaperDetail(paperDetail);
            paperDetailUnit.setQuestionType(questions.get(i).getQuestionType());
            paperDetailUnit.setCreator(paper.getCreator());
            paperDetailUnit.setPaper(paper);
            paperDetailUnit.setPaperType(PaperType.GENERATE);
            if (StringUtils.isBlank(map.get(questions.get(i).getId()).getScore() + "")) {
                throw new StatusException("Q-014157", questions.get(i).getId() + "分数未设置");
            }
            paperDetailUnit.setScore(map.get(questions.get(i).getId()).getScore());
            if (!StringUtils.isBlank(map.get(questions.get(i).getId()).getTimeLimit() + "")) {
                paperDetailUnit.setTimeLimit(map.get(questions.get(i).getId()).getTimeLimit());
            }
            j++;
            score = map.get(questions.get(i).getId()).getScore() + score;
            sum = paperDetailUnit.getScore() * paperDetailUnit.getQuestion().getDifficultyDegree() / 10 + sum;
            paperDetailUnits.add(paperDetailUnit);
        }
        paperDetail.setUnitCount(j);
        paperDetail.setScore(score);

        BigDecimal b;
        if (score != 0d) {
            b = BigDecimal.valueOf(sum / score);
        } else {
            b = BigDecimal.valueOf(0d);
        }

        Double difficulty = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        paper.setTotalScore(score);
        paper.setDifficultyDegree(difficulty);
        return paperDetailUnits;
    }

    @Override
    public DefaultPaper findPaper(String paperId) {
        Paper basePaper = Model.of(paperRepo.findById(paperId));
        if (basePaper == null) {
            throw new StatusException("Q-014180", "basePaper is null");
        }
        DefaultPaper defaultPaper = extractConfigProviderServiceImpl.buildDefaultByBasePaper(basePaper, null, null, null);
        return defaultPaper;
    }

    @Override
    public String examPaper(String orgId, String paperId, Long examId) {
        ExtractConfig extractConfig = new ExtractConfig();
        extractConfig.setExamId(examId);
        extractConfig.setCourseCode("K12");
        extractConfig.setOrgId(orgId);
        ExtractConfig tempConfig = extractConfigService.findConfig(extractConfig);
        if (tempConfig != null) {
            extractConfigRepo.delete(tempConfig);
        }
        //查询试卷对象
        Paper paper = Model.of(paperRepo.findById(paperId));
        if (paper == null) {
            throw new StatusException("Q-014200", "paper is null");
        }
        //初始化默认课程
        Course course = new Course();
        course.setId("k12");
        course.setCode("k12");
        course.setName("k12");
        course.setLevel("ALL");
        course.setOrgId(orgId);
        course.setCreateTime(CommonUtils.getCurDateTime());
        course.setEnable("true");
        extractConfig.setCourse(course);
        extractConfig.setIfFinish((short) 0);
        ExamPaper examPaper = new ExamPaper();
        examPaper.setId(null);
        examPaper.setGroupCode("K");
        examPaper.setWeight(100);
        examPaper.setPaper(paper);
        List<ExamPaper> examPaperList = new ArrayList<>();
        examPaperList.add(examPaper);
        extractConfig.setExamPaperList(examPaperList);
        extractConfig.setScrambling_the_option_order((short) 0);
        extractConfig.setScrambling_the_question_order((short) 0);
        extractConfig = extractConfigRepo.save(extractConfig);
        return extractConfig.getId();
    }

    @Override
    public DefaultPaper findExamPaper(String orgId, Long examId) {
        ExtractConfig extractConfig = new ExtractConfig();
        extractConfig.setExamId(examId);
        extractConfig.setCourseCode("K12");
        extractConfig.setOrgId(orgId);
        ExtractConfig tempConfig = extractConfigService.findConfig(extractConfig);
        if (tempConfig == null) {
            return null;
        }
        List<ExamPaper> list = tempConfig.getExamPaperList();
        if (list == null || list.size() < 1) {
            throw new StatusException("Q-014252", "该场考试关联试卷集合为空");
        }
        String paperId = list.get(0).getPaper().getId();
        if (StringUtils.isBlank(paperId)) {
            throw new StatusException("Q-014256", "该场考试关联的试卷id为空");
        }
        DefaultPaper defaultPaper = findPaper(paperId);
        return defaultPaper;
    }

}
