package com.xhkjedu.sstudy.service.question;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.sstudy.mapper.question.QuestionDirectorMapper;
import com.xhkjedu.sstudy.mapper.question.QuestionMapper;
import com.xhkjedu.sstudy.mapper.question.QuestionPointMapper;
import com.xhkjedu.sstudy.mapper.question.ZQuestionUpdateMapper;
import com.xhkjedu.sstudy.model.question.TQuestion;
import com.xhkjedu.sstudy.model.question.TQuestionDirector;
import com.xhkjedu.sstudy.model.question.TQuestionPoint;
import com.xhkjedu.sstudy.model.subjectbook.TSubject;
import com.xhkjedu.sstudy.model.subjectbook.TSubjectQuestiontype;
import com.xhkjedu.sstudy.utils.StudyUtil;
import com.xhkjedu.sstudy.vo.question.QuestionVo;
import com.xhkjedu.sstudy.vo.subjectbook.DirectorVo;
import com.xhkjedu.sstudy.vo.subjectbook.PointVo;
import com.xhkjedu.utils.N_Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Description
 * @Author WN
 * Date 2022/8/16 16:50
 **/
@Service
public class ZQuestionUpdateService {
    @Resource
    private ZQuestionUpdateMapper zQuestionUpdateMapper;
    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private QuestionDirectorMapper questionDirectorMapper;
    @Resource
    private QuestionPointMapper questionPointMapper;

    /**
     * @Description 处理万幸填空阅读理解
     * @Param []
     * @Return void
     * @Author wn
     * @Date 2022/8/17 8:52
     **/
    @Transactional(rollbackFor = Exception.class)
    public void saveQuestions() throws Exception {
        // 需要处理试题的科目
        List<TSubject> subjects = zQuestionUpdateMapper.listSubjects();

        if (N_Utils.isListEmpty(subjects)) {
            throw new Exception("无需要处理试题");
        }
        for (TSubject s : subjects) {
            List<TSubjectQuestiontype> qtypelist = zQuestionUpdateMapper.listSubjectQtype(s.getLevel(), s.getSubjectid());
            Map<String, TSubjectQuestiontype> tmap = new TreeMap();
            if (N_Utils.isListEmpty(qtypelist)) {
                throw new Exception(s.getSubjectname() + "未设置题型");
            }
            for (TSubjectQuestiontype t : qtypelist) {
                String key = t.getCtype() + "_"+t.getQtypename();
                if(!tmap.containsKey(key)){
                    tmap.put(key, t);
                }
            }

            List<QuestionVo> list = zQuestionUpdateMapper.listQuestions(s.getLevel(), s.getSubjectid());

            List<TQuestion> questions = new ArrayList<>();
            List<TQuestionDirector> directors = new ArrayList<>();
            List<TQuestionPoint> points = new ArrayList<>();
            List<String> questionids = new ArrayList<>();
            int timestamp = N_Utils.getSecondTimestamp();
            for (int k = 0; k < list.size(); k++) {
//            System.out.println("第几题："+(k+1));
                QuestionVo qvo = list.get(k);
                TQuestion q = new TQuestion();
                String qid = StudyUtil.getId();

                // 处理子题
                String qoption = qvo.getQoption();
                String qanswer = qvo.getQanswer();
                List<Map> optionlist = JSON.parseArray(qoption, Map.class);
                List<String> answerlist = JSON.parseArray(qanswer, String.class);

                q.setQuestionid(qid);
                q.setQstem(qvo.getQstem());
                q.setQstemtxt(qvo.getQstemtxt());
                q.setQanalyze(qvo.getQanalyze());
                q.setScore(qvo.getScore());
                q.setComplexity(qvo.getComplexity());
                q.setSubjectid(qvo.getSubjectid());
                q.setCount(qvo.getCount());
                q.setQlevel(2);
                q.setSnum(optionlist.size());
                q.setSorder(0);
                q.setQstate(1);
                q.setHashear(0);
                q.setSource(qvo.getSource());
                q.setYear(qvo.getYear());
                q.setRegion(qvo.getRegion());
                q.setSchoolname(qvo.getSchoolname());
                q.setCreateid(qvo.getCreateid());
                q.setCreatetime(timestamp);
                q.setBelong(qvo.getBelong());
                q.setSchoolid(qvo.getSchoolid());
                TSubjectQuestiontype st = null;
                if (qvo.getCtype() == 7 || qvo.getCtype() == 8) {
                    String sckey = "16_"+qvo.getQtypename();
                    st = tmap.get(sckey);
                    q.setCtype(16);

                }
                if (qvo.getCtype() == 10) {
                    String sckey = "17_"+qvo.getQtypename();
                    st = tmap.get(sckey);
                    q.setCtype(17);
                }

                if(st == null){
                    throw new Exception("未设置题型："+ s.getSubjectname() + ":"+qvo.getQuestionid());
                }

                q.setQtypeid(st.getQtypeid());
                q.setQtypename(st.getQtypename());
                questions.add(q);// 母题

                List<PointVo> pointVoList = qvo.getPoints();
                for (PointVo pointVo : pointVoList) {
                    TQuestionPoint tp = new TQuestionPoint();
                    tp.setQpid(StudyUtil.getId());
                    tp.setQuestionid(qid);
                    tp.setPointid(pointVo.getPointid());
                    tp.setCreateid(qvo.getCreateid());
                    tp.setCreatetime(timestamp);
                    points.add(tp);
                }
                List<DirectorVo> directorVoList = qvo.getDirectors();
                for (DirectorVo d : directorVoList) {
                    TQuestionDirector td = new TQuestionDirector();
                    td.setQdid(StudyUtil.getId());
                    td.setQuestionid(qid);
                    td.setLsbid(d.getLsbid());
                    td.setDirectorid(d.getDirectorid());
                    td.setCreateid(qvo.getCreateid());
                    td.setCreatetime(timestamp);
                    directors.add(td);
                }
                
                String key1 = "1_单选题";
                String key2 = "1_选择题";
                TSubjectQuestiontype sonqtype = null;
                if(tmap.containsKey(key1)){
                    sonqtype = tmap.get(key1);
                }else if(tmap.containsKey(key2)){
                    sonqtype = tmap.get(key2);
                }

                if (sonqtype == null) {
                    throw new Exception("科目下无单选题题型：" + s.getSubjectname() + ";试题id：" + qvo.getQuestionid());
                }

                for (int i = 0; i < optionlist.size(); i++) {
                    Map map = optionlist.get(i);
                    String sqstem = map.get("sqstem").toString();
                    String sqoptions = map.get("sqoptions").toString();
                    String sanswer = answerlist.get(i);
                    List<String> sanswerlist = new ArrayList<>();
                    sanswerlist.add(sanswer);
                    Double sscore = getDivide(qvo.getScore(), optionlist.size());

                    TQuestion sq = new TQuestion();
                    sq.setQuestionid(StudyUtil.getId());
                    sq.setQuestionpid(qid);
                    sq.setQstem(sqstem);
                    sq.setQstemtxt(sqstem);
                    sq.setQoption(sqoptions);
                    sq.setQanswer(JSON.toJSONString(sanswerlist));
                    sq.setScore(sscore);
                    sq.setComplexity(qvo.getComplexity());
                    sq.setSubjectid(qvo.getSubjectid());
                    sq.setCount(0);
                    sq.setQlevel(3);
                    sq.setSnum(0);
                    sq.setSorder(i + 1);
                    sq.setQstate(1);
                    sq.setHashear(0);
                    sq.setSource(qvo.getSource());
                    sq.setYear(qvo.getYear());
                    sq.setRegion(qvo.getRegion());
                    sq.setSchoolname(qvo.getSchoolname());
                    sq.setCreateid(qvo.getCreateid());
                    sq.setCreatetime(timestamp);
                    sq.setBelong(qvo.getBelong());
                    sq.setSchoolid(qvo.getSchoolid());

                    sq.setCtype(1);
                    sq.setQtypeid(sonqtype.getQtypeid());
                    sq.setQtypename(sonqtype.getQtypename());

                    questions.add(sq);
                }
                questionids.add(qvo.getQuestionid());
            }

            questionMapper.saveBathQuestion(questions);
            questionDirectorMapper.batchSave(directors);
            questionPointMapper.batchSave(points);
            zQuestionUpdateMapper.updateBatchQuestionState(questionids);
        }

    }

    private Double getDivide(Double score, Integer num) {
        BigDecimal score1 = new BigDecimal(score);
        BigDecimal num1 = new BigDecimal(num);
        BigDecimal divide = score1.divide(num1, 1, BigDecimal.ROUND_FLOOR);
        return divide.doubleValue();
    }
}
