package com.xhkjedu.sstudy.service.question;

import com.xhkjedu.sstudy.mapper.paper.PaperFileMapper;
import com.xhkjedu.sstudy.mapper.question.QuestionClassMapper;
import com.xhkjedu.sstudy.mapper.question.QuestionExplainMapper;
import com.xhkjedu.sstudy.mapper.question.QuestionMapper;
import com.xhkjedu.sstudy.mapper.question.QuestionStudentMapper;
import com.xhkjedu.sstudy.mapper.subjectbook.SubjectMapper;
import com.xhkjedu.sstudy.model.paper.TPaperFile;
import com.xhkjedu.sstudy.model.question.TQuestionExplain;
import com.xhkjedu.sstudy.model.question.TQuestionStudent;
import com.xhkjedu.sstudy.vo.question.QuestionClassVo;
import com.xhkjedu.sstudy.vo.question.QuestionStudentVo;
import com.xhkjedu.sstudy.vo.subjectbook.SubjectQuestiontypeVo;
import com.xhkjedu.utils.N_Utils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ywx
 * @classname QuestionStudentService
 * @description 
 * @date 2020/6/6 17:34
 **/
@Service
public class QuestionStudentService {
    @Resource
    private QuestionStudentMapper questionStudentMapper;

    @Resource
    private QuestionExplainMapper questionExplainMapper;

    @Resource
    private PaperFileMapper paperFileMapper;
    @Resource
    private QuestionClassMapper questionClassMapper;
    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private SubjectMapper subjectMapper;

    //添加
    public Integer save(TQuestionStudent model) {
        questionStudentMapper.insertUseGeneratedKeys(model);
        return model.getId();
    }

    //删除
    public Integer deleteById(Integer qsid) {
        return questionStudentMapper.deleteById(qsid);
    }

    /**
     * 更新错误次数
     * @Param [qsid]
     * @Author ywx
     * @Date 2020/6/11 15:00
     * @return java.lang.Integer
     **/
    public Integer updateErrorNum(Integer qsid) {
        Integer nowtime = N_Utils.getSecondTimestamp();
        return questionStudentMapper.updateErrorNum(qsid,nowtime);
    }

    //获取详情
    public TQuestionStudent findById(Integer id) {
        return questionStudentMapper.selectByPrimaryKey(id);
    }

    //获取列表
    public List <QuestionStudentVo> findAll(TQuestionStudent questionStudent) {
        List<QuestionStudentVo> list = questionStudentMapper.findAll(questionStudent);
        List<Integer> paperids = list.stream().filter(q -> q.getQctype() == 2).map(QuestionStudentVo::getPaperid).distinct().collect(Collectors.toList());
        Map<Integer, String> paperMap = new HashMap<>();
        if (N_Utils.isListNotEmpty(paperids)) {
            List<Map> papers = questionStudentMapper.getPaperNameById(paperids);
            for (Map paper : papers) {
                paperMap.put((Integer) paper.get("paperid"), paper.get("papername").toString());
            }
        }
        List<QuestionClassVo> questions = new ArrayList<>();//题库错题
        List<QuestionClassVo> scantrons = new ArrayList<>();//附件错题
        List<TQuestionExplain> explainAll = new ArrayList<>();//全部错题讲解
        listQuestionDetail(list, questions, scantrons, explainAll);//获取错题详情

        for (QuestionStudentVo q : list) {
            Integer qctype = q.getQctype();
            if (qctype == 1 || qctype == 3) {
                QuestionClassVo vo = questions.stream().filter(tq -> tq.getQuestionid().equals(q.getQuestionid())).findFirst().orElse(null);
                q.setCtype(vo.getCtype());
                q.setQstem(vo.getQstem());
                q.setQoption(vo.getQoption());
                q.setQtypename(vo.getQtypename());
                q.setHashear(vo.getHashear());
                q.setHearfile(vo.getHearfile());
            } else if (qctype == 2) {
                QuestionClassVo vo = scantrons.stream().filter(tq -> tq.getQuestionid().equals(q.getQuestionid())).findFirst().orElse(null);
                q.setCtype(vo.getCtype());
                q.setQtypename(vo.getQtypename());
                String papername = paperMap.get(q.getPaperid());
                q.setQstem(papername + "-第" + q.getQn() + "题");
            }
            List<TQuestionExplain> explains = explainAll.stream().filter(e -> e.getQctype() == qctype && e.getQuestionid().equals(q.getQuestionid())).collect(Collectors.toList());
            q.setExplains(explains);
        }
        return list;
    }

    //获取错题详情
    private void listQuestionDetail(List<QuestionStudentVo> list, List<QuestionClassVo> questions, List<QuestionClassVo> scantrons, List<TQuestionExplain> explainAll) {
        List<String> questionids = list.stream().filter(q -> q.getQctype() == 1 || q.getQctype() == 3)
                .map(QuestionStudentVo::getQuestionid).collect(Collectors.toList());
        List<String> sids = list.stream().filter(q -> q.getQctype() == 2).map(QuestionStudentVo::getQuestionid).collect(Collectors.toList());
        if (N_Utils.isListNotEmpty(questionids)) questions.addAll(questionClassMapper.getQuestionById(questionids));
        if (N_Utils.isListNotEmpty(sids)) scantrons.addAll(questionClassMapper.getScantronById(sids));
        if (N_Utils.isListNotEmpty(list)) {
            List<TQuestionExplain> explains = questionExplainMapper.listByQuestionIds(list);
            if (N_Utils.isListNotEmpty(explains)) explainAll.addAll(explains);
        }
    }

    /**
     * 获取学生错题信息
     *
     * @return com.xhkjedu.model.question.TQuestionStudent
     * @Param [questionid, studentid]
     * @Author ywx
     * @Date 2020/6/10 16:23
     **/
    public TQuestionStudent getQuestionStudent(TQuestionStudent qs) {
        return questionStudentMapper.getQuestionStudent(qs);
    }

    /**
     * 作答
     * @Param [qsid, corrected]
     * @Author ywx
     * @Date 2020/6/11 15:03
     * @return void
     **/
    public void submitQuestion(Integer qsid, Integer corrected) {
        if (corrected == 1){//作答正确，移除错题库
            deleteById(qsid);
        } else {//作答错误，更新错误次数
            updateErrorNum(qsid);
        }
    }

    //////////////////////////////////////////////学生WEB端//////////////////////////////////////////////
    /**
     * 未做提交或者自动批改未得满分，入错题库
     * @Param [questionid, studentid, subjectid]
     * @Author ywx
     * @Date 2020/6/10 16:26
     * @return java.lang.Boolean
     **/
    public Boolean updateQuestionStudent(TQuestionStudent qs){
        if (N_Utils.isEmpty(qs.getQuestionid())){//试题id为空不入错题库
            return true;
        }
        qs.setScorerate(N_Utils.getDoubleDivideAndMulitiply(qs.getStuscore(),qs.getQscore()));
        qs.setHandletime(N_Utils.getSecondTimestamp());
        TQuestionStudent questionStudent = getQuestionStudent(qs);
        if (questionStudent == null){
            qs.setErrornum(1);
            qs.setDelstate(0);
            try {
                Integer result = save(qs);
                return result > 0 ? true : false;
            } catch (DuplicateKeyException e) {
                return true;
            }
        }else {
            qs.setQsid(questionStudent.getQsid());
            Integer result = questionStudentMapper.updateQuestion(qs);
            return result > 0 ? true : false;
        }
    }

    /**
     * 已批阅未得满分的试题
     * @Param [paperid, classid, qctype]
     * @Author ywx
     * @Date 2020/10/12 15:10
     * @return java.util.List<com.xhkjedu.model.question.TQuestionStudent>
     **/
    public List<TQuestionStudent> listQuestions(Long paperid, Integer classid, Integer qctype) {
        return questionStudentMapper.listQuestions(paperid, classid, qctype);
    }

    /**
     * 题型列表
     * @Param [qs]
     * @Author ywx
     * @Date 2020/10/21 16:15
     * @return java.util.List<com.xhkjedu.vo.subjectbook.SubjectQuestiontypeVo>
     **/
    public List<SubjectQuestiontypeVo> listQtype(TQuestionStudent qs) {
        List<SubjectQuestiontypeVo> list = questionStudentMapper.listQtype(qs);
        String subjectid = qs.getSubjectid();
        String  subjectname = subjectMapper.getSubjectnameById(subjectid);
        if(subjectname.contains("英语")){
            //如果是英语题获取英语题对应试题包含听力题的题型
            Integer hearnum = questionMapper.getQuestionHasHearNum(subjectid);
            if(hearnum!=null && hearnum >0){
                SubjectQuestiontypeVo qt = new SubjectQuestiontypeVo();
                qt.setQtypename("听力题");
                qt.setQtypeid("tlt");
                list.add(0,qt);
            }
        }
        return list;
    }

    //获取列表
    public List <QuestionStudentVo> findAllStuWeb(TQuestionStudent question) {
        List<QuestionStudentVo> list = questionStudentMapper.listForWeb(question);
        List<QuestionClassVo> questions = new ArrayList<>();//题库错题
        List<QuestionClassVo> scantrons = new ArrayList<>();//附件错题
        List<TQuestionExplain> explainAll = new ArrayList<>();//全部错题讲解
        listQuestionDetail(list, questions, scantrons, explainAll);//获取错题详情
        for (QuestionStudentVo q : list) {
            Integer qctype = q.getQctype();
            if (qctype == 1 || qctype == 3) {
                QuestionClassVo vo = questions.stream().filter(tq -> tq.getQuestionid().equals(q.getQuestionid())).findFirst().orElse(null);
                q.setCtype(vo.getCtype());
                q.setQstem(vo.getQstem());
                q.setQoption(vo.getQoption());
                q.setQtypename(vo.getQtypename());
                q.setHashear(vo.getHashear());
                q.setHearfile(vo.getHearfile());
            } else if (qctype == 2) {
                QuestionClassVo vo = scantrons.stream().filter(tq -> tq.getQuestionid().equals(q.getQuestionid())).findFirst().orElse(null);
                q.setCtype(vo.getCtype());
                q.setQtypename(vo.getQtypename());
            }
            List<TQuestionExplain> explains = explainAll.stream().filter(e -> e.getQctype() == qctype && e.getQuestionid().equals(q.getQuestionid())).collect(Collectors.toList());
            q.setExplains(explains);
        }
        return list;
    }

    /**
     * 试题详情
     * @Param [questionid, qctype, studentid]
     * @Author ywx
     * @Date 2020/9/5 10:12
     * @return com.xhkjedu.vo.question.QuestionStudentVo
     **/
    public QuestionStudentVo detailStuWeb(String questionid, Integer qctype, Integer studentid) {
        QuestionStudentVo question = null;
        if (qctype == 1 || qctype == 3) {
            question = questionStudentMapper.detail(questionid, studentid, qctype);
            if (N_Utils.isComplexQuestion(question.getCtype())) {
                List<Map> sonqlist = questionMapper.listSonQuestionsForDetail(questionid);
                question.setSonqlist(sonqlist);
            }
        } else {
            question = questionStudentMapper.sdetail(questionid, studentid);
            if (question != null) {
                List<TPaperFile> files = paperFileMapper.listObjsByPaperid(question.getPaperid());
                question.setFiles(files);
            }
        }
        return question;
    }

}
