package com.xhkjedu.sstudy.service.question;

import com.xhkjedu.exception.MissingParametersException;
import com.xhkjedu.sstudy.mapper.question.*;
import com.xhkjedu.sstudy.mapper.subjectbook.SubjectBookMapper;
import com.xhkjedu.sstudy.model.question.TQuestion;
import com.xhkjedu.sstudy.model.question.TQuestionCollect;
import com.xhkjedu.sstudy.model.question.TQuestionDirector;
import com.xhkjedu.sstudy.model.question.TQuestionPoint;
import com.xhkjedu.sstudy.model.subjectbook.TSubjectBook;
import com.xhkjedu.sstudy.utils.StudyUtil;
import com.xhkjedu.sstudy.vo.question.QuestionCollectVo;
import com.xhkjedu.sstudy.vo.question.QuestionVo;
import com.xhkjedu.sstudy.vo.subjectbook.DirectorVo;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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 QuestionService
 * @description 
 * @date 2020/6/6 17:09
 **/
@Service
public class QuestionService {
    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private QuestionPointMapper questionPointMapper;
    @Resource
    private QuestionCollectMapper questionCollectMapper;
    @Resource
    private QuestionDirectorMapper questionDirectorMapper;
    @Resource
    private SubjectBookMapper subjectBookMapper;

    //更新单个试题状态
    public Integer updateState(String questionid, Integer qstate) {
        return questionMapper.updateState(questionid, qstate);
    }

    //修改
    public Integer update(TQuestion model) {
        model.setCreatetime(N_Utils.getSecondTimestamp());
        if (model.getQlevel() == 2) {
            List<TQuestion> questions = model.getQuestions();
            List<TQuestion> updateQuestions = new ArrayList<>();//要更新试题集合
            List<TQuestion> addQuestions = new ArrayList<>();//要添加试题集合
            for (TQuestion question : questions) {
                if (N_Utils.isEmpty(question.getQuestionid())) {
                    question.setQuestionid(StudyUtil.getId());
                    question.setQuestionpid(model.getQuestionid());
                    question.setCreatetime(N_Utils.getSecondTimestamp());
                    question.setQstate(1);
                    question.setHashear(0);
                    addQuestions.add(question);
                } else {
                    updateQuestions.add(question);
                }
            }
            if (N_Utils.isListNotEmpty(updateQuestions)) questionMapper.updateBatch(updateQuestions);
            if (N_Utils.isListNotEmpty(addQuestions)) questionMapper.saveBathQuestion(addQuestions);
        }
        return questionMapper.updateByPrimaryKeySelective(model);
    }

    //获取详情
    public QuestionVo findById(String questionid) {
        QuestionVo questionVo = questionMapper.findById(questionid);
        if(questionVo.getQlevel() == 2){
            //代表母题，需要获取子题
            List<Map> sonqlist = questionMapper.listSonQuestionsForDetail(questionVo.getQuestionid());
            questionVo.setSonqlist(sonqlist);
        }
        return questionVo;
    }

    //获取列表
    public List <Map<String, Object>> findAll(TQuestion question) {
        List<Map<String, Object>> list = questionMapper.findAll(question);
        Integer schoolid = question.getSchoolid();
        if(N_Utils.isEmptyInteger(schoolid)) return list;
        String shareqids = list.stream().filter(m -> schoolid.equals(m.get("schoolid")) && !m.get("belong").equals(10))
                               .map(m -> m.get("questionid").toString()).collect(Collectors.joining("','"));
        List<Map<String, String>> shareList = questionMapper.listShareNumByIds(shareqids);
        for (Map<String, Object> map : list) {
            setShareNum(shareList, map);
        }
        return list;
    }

    /**
     * 批量保存
     * @Param [addQuestion]
     * @Author ywx
     * @Date 2020/6/6 17:01
     * @return void
     **/
    public void batchSave(List<TQuestion> addQuestion) {
        questionMapper.insertList(addQuestion);
    }

    /**
     * 添加
     * @Param [question]
     * @Author ywx
     * @Date 2020/6/8 17:38
     * @return java.lang.Integer
     **/
    @Transactional(rollbackFor = Exception.class)
    public String save(TQuestion question) {
        delQuestionATag(question);
        question.setCount(0);
        question.setQstate(1);
        Integer timestamp = N_Utils.getSecondTimestamp();
        question.setCreatetime(timestamp);
        String questionid = StudyUtil.getId();

        question.setQuestionid(questionid);
        if (N_Utils.isEmpty(question.getSubjectid())) {//科目为空根据教材id取科目
            TSubjectBook book = subjectBookMapper.selectByPrimaryKey(question.getLsbid());
            question.setSubjectid(book.getSubjectid());
        }

        if(question.getHashear() == null){
            question.setHashear(0);
        }
        if(question.getSnum() == null){
            question.setSnum(0);
        }
        List<TQuestion> saveques = new ArrayList<>();
        saveques.add(question);
        if(N_Utils.isListNotEmpty(question.getQuestions())){
            List<TQuestion> sonques = question.getQuestions();
            for(TQuestion sq : sonques){
                String sonquestionid = StudyUtil.getId();
                sq.setQuestionpid(questionid);
                sq.setQuestionid(sonquestionid);
                sq.setQlevel(3);
                sq.setSubjectid(question.getSubjectid());
                sq.setCount(0);
                sq.setQstate(1);
                sq.setBelong(question.getBelong());
                sq.setHashear(0);
                sq.setSnum(0);
                sq.setSubjectid(question.getSubjectid());
                sq.setCreateid(question.getCreateid());
                sq.setCreatetime(timestamp);
                sq.setSchoolid(question.getSchoolid());
                saveques.add(sq);
            }
        }
        questionMapper.saveBathQuestion(saveques);

        setQuestionPointDirector(question);
        questionPointMapper.batchSave(question.getQuestionPoints());//保存试题关联知识点信息
        batchSaveQuestionDirector(question.getDirectors());//保存试题关联章节信息
        return questionid;
    }

    /**
     * 修改
     * @Param [question]
     * @Author ywx
     * @Date 2020/6/9 8:33
     * @return void
     **/
    public void updateQuestion(TQuestion question) {
        N_Utils.validation(new Object[]{
                question.getQstem(),"试题题干",2,question.getQlevel(),"试题类型",1
                ,question.getScore(),"试题分值",1,question.getComplexity(),"试题难易度",1
                ,question.getQtypeid(),"试题题型id",2,question.getQuestionid(),"试题id",2
        });
        if (CollectionUtils.isEmpty(question.getQuestionPoints())){
            throw new MissingParametersException("试题关联知识点不能为空");
        }
        // 修改 试题_知识点关联信息
        questionPointMapper.deleteByQuestionId(question.getQuestionid());//删除试题关联知识点信息
        questionDirectorMapper.deleteByQuestionId(question.getQuestionid());//删除试题关联章节信息
        setQuestionPointDirector(question);
        questionPointMapper.batchSave(question.getQuestionPoints());//保存试题关联知识点信息
        batchSaveQuestionDirector(question.getDirectors());//保存试题关联章节信息
        delQuestionATag(question);
        update(question);
    }

    /**
     * 设置试题知识点、章节关联信息
     * @Param [question]
     * @Author ywx
     * @Date 2020/6/9 8:38
     * @return void
     **/
    public void setQuestionPointDirector(TQuestion question) {
        String questionid = question.getQuestionid();
        Integer createid = question.getCreateid();
        Integer schoolid = question.getSchoolid();
        List<TQuestionPoint> questionPoints = question.getQuestionPoints();
        for (TQuestionPoint qp : questionPoints) {
            qp.setQuestionid(questionid);
            qp.setCreateid(createid);
            qp.setCreatetime(N_Utils.getSecondTimestamp());
            qp.setSchoolid(schoolid);
            qp.setQpid(StudyUtil.getId());
        }
        question.setQuestionPoints(questionPoints);

        //章节
        List<TQuestionDirector> directors = question.getDirectors();
        if (N_Utils.isListEmpty(directors)) {//兼容以前添加单个章节模式
            directors = new ArrayList<>();
            TQuestionDirector qd = new TQuestionDirector();
            qd.setLsbid(question.getLsbid());
            qd.setDirectorid(question.getDirectorid());
            directors.add(qd);
        }
        for (TQuestionDirector qd : directors) {
            qd.setQuestionid(questionid);
            qd.setCreateid(createid);
            qd.setCreatetime(N_Utils.getSecondTimestamp());
            qd.setQdid(StudyUtil.getId());
        }
        question.setDirectors(directors);
    }

    /**
     * 批量保存试题章节关联信息
     * @Param [directors]
     * @Author ywx
     * @Date 2020/12/30 13:43
     * @return void
     **/
    public void batchSaveQuestionDirector(List<TQuestionDirector> directors){
        if (N_Utils.isListNotEmpty(directors)) {
            questionDirectorMapper.batchSave(directors);
        }
    }

    /**
     * @author ywx
     * @description 去除试题中的a标签
     * @date 2020/8/26 20:34
     **/
    private void delQuestionATag(TQuestion question) {
        question.setQstem(N_Utils.delATag(question.getQstem()));
        question.setQoption(N_Utils.delATag(question.getQoption()));
        question.setQanswer(N_Utils.delATag(question.getQanswer()));
        question.setQanalyze(N_Utils.delATag(question.getQanalyze()));
        if(question.getCtype() == 11 || question.getCtype() == 12){
            //说明改题有子题
            List<TQuestion>  sonques = question.getQuestions();//子题
            for(TQuestion sq : sonques){
                sq.setQstem(N_Utils.delATag(sq.getQstem()));
                sq.setQoption(N_Utils.delATag(sq.getQoption()));
                sq.setQanswer(N_Utils.delATag(sq.getQanswer()));
                sq.setQanalyze(N_Utils.delATag(sq.getQanalyze()));
            }
        }
    }

    /**
     * 章节、知识点选题
     * @Param [question]
     * @Author ywx
     * @Date 2020/6/9 15:00
     * @return java.util.List<Map>
     **/
    public List<Map<String, Object>> listForSelect(TQuestion question) {
        List<Map<String, Object>> list = questionMapper.listForSelect(question);
        String questionids = list.stream().filter(m -> m.get("qlevel").toString().equals("2")).map(
                m -> m.get("questionid").toString()).collect(Collectors.joining("','"));
        boolean rtn = false;
        List<Map<String, String>> sonList;
        if (N_Utils.isNotEmpty(questionids)) {
            sonList = questionMapper.listSonQuestionForSelect(questionids);
            rtn = true;
        } else {
            sonList = null;
        }

        Integer createid = question.getCreateid();
        String shareqids = list.stream().filter(m -> createid.equals(m.get("createid")) && !m.get("belong").equals(10))
                               .map(m -> m.get("questionid").toString()).collect(Collectors.joining("','"));
        List<Map<String, String>> shareList = questionMapper.listShareNumByIds(shareqids);
        for (Map<String, Object> map : list) {
            setShareNum(shareList, map);
            if (rtn) {
                setSonQList(sonList, map);
            }
        }
        return list;
    }

    /**
     * @Description 试题是否分享过
     * @Date 2023/9/1 14:28
     * @Author YWX
     * @Param [shareList, map]
     * @Return void
     **/
    private void setShareNum(List<Map<String, String>> shareList, Map<String, Object> map) {
        Object shareqid = map.get("questionid");
        Object sharenum = 0;
        if (N_Utils.isListNotEmpty(shareList)) {
            for (Map<String, String> s : shareList) {
                if (s.get("shareqid").equals(shareqid)) {
                    sharenum = s.get("sharenum");
                    break;
                }
            }
        }
        map.put("sharenum", sharenum);
    }

    /**
     * @Description 处理试题子题
     * @Date 2023/8/16 8:38
     * @Author YWX
     * @Param [sonList, map]
     * @Return void
     **/
    public void setSonQList(List<Map<String, String>> sonList, Map<String, Object> map) {
        if (map.get("qlevel").toString().equals("2")) {
            Object questionid = map.get("questionid");
            List<Map<String, String>> sonqlist = sonList.stream().filter(
                    s -> s.get("questionpid").equals(questionid)).collect(Collectors.toList());
            map.put("sonqlist", sonqlist);
        }
    }

    /**
     * 试题收藏
     * @Param [collect]
     * @Author ywx
     * @Date 2020/8/18 16:00
     * @return java.lang.Integer
     **/
    public Integer saveCollect(TQuestionCollect collect) {
        collect.setCreatetime(N_Utils.getSecondTimestamp());
        questionCollectMapper.insertUseGeneratedKeys(collect);
        return collect.getId();
    }

    /**
     * 试题取消收藏
     * @Param [collect]
     * @Author ywx
     * @Date 2020/8/18 16:01
     * @return void
     **/
    public void cancelCollect(TQuestionCollect collect) {
        questionCollectMapper.cancelCollect(collect);
    }

    /**
     * 获取试题是否收藏列表
     * @Param [questionids]
     * @Author ywx
     * @Date 2020/8/18 16:14
     * @return java.util.List<com.xhkjedu.vo.question.QuestionCollectVo>
     **/
    public List<QuestionCollectVo> listCollect(List<String> questionids, Integer userid) {
        List<String> questionIds = questionCollectMapper.listCollect(questionids, userid);
        List<QuestionCollectVo> list = new ArrayList<>();
        for (String questionid : questionids) {
            QuestionCollectVo qc = new QuestionCollectVo();
            qc.setQuestionid(questionid);
            int collected = 0;
            if (N_Utils.strInList(questionid, questionIds)){
                collected = 1;
            }
            qc.setCollected(collected);
            list.add(qc);
        }
        return list;
    }

    /**
     * @Description 保存编辑试题，编辑后保存为新试题默认为个人题库
     * @Param [question]
     * @Return java.lang.String
     * @Author wn
     * @Date 2022/7/19 16:02
     **/
    @Transactional(rollbackFor = Exception.class)
    public Map saveUpdateQuestion(TQuestion question){
        QuestionVo oldQuestion = questionMapper.findById(question.getQuestionid());//原试题详细信息
        delQuestionATag(question);//优化试题内容
        question.setSubjectid(oldQuestion.getSubjectid());

        List<TQuestion> saveQues = new ArrayList<>();//试题集合
        List<TQuestionPoint> saveQPoints = new ArrayList<>();//试题知识集合
        List<TQuestionDirector> saveQDirs = new ArrayList<>();//试题章节集合

        Map map = setSaveUpdateQuestion(question,saveQues,saveQPoints);
        setSaveUpdateQuesitonDirector(oldQuestion,question,saveQDirs);
        questionMapper.saveBathQuestion(saveQues);//保存试题
        if(N_Utils.isListNotEmpty(saveQPoints)){
            questionPointMapper.batchSave(saveQPoints);//保存试题关联知识点信息
        }
        if(N_Utils.isListNotEmpty(saveQDirs)){
            questionDirectorMapper.batchSave(saveQDirs);//保存试题关联章节
        }

        //删除试题栏中原题，加入新题
       /* userBasketMapper.deleteByQuestioniduid(question.getCreateid(),oldQuestion.getQuestionid());
        TUserBasket ub = new TUserBasket();
        ub.setUserid(question.getCreateid());
        ub.setSubjectid(question.getSubjectid());
        ub.setQtypeid(question.getQtypeid());
        ub.setQtypename(question.getQtypename());
        ub.setQuestionid(question.getQuestionid());
        ub.setCreatetime(question.getCreatetime());
        userBasketMapper.insertSelective(ub);//保存新试题进入试题栏*/

        return map;
    }

    //处理试题试题和知识
    private Map setSaveUpdateQuestion(TQuestion question,List<TQuestion> saveQues,List<TQuestionPoint> saveQPoints){
        Map map = new HashMap();
        List<Map> sonlist = new ArrayList<>();
        int timestamp = N_Utils.getSecondTimestamp();
        question.setCount(0);
        question.setQstate(1);
        question.setBelong(4);
        question.setCreatetime(timestamp);
        String questionid = StudyUtil.getId();
        question.setQuestionid(questionid);

        if(question.getHashear() == null){
            question.setHashear(0);
        }
        if(question.getSnum() == null){
            question.setSnum(0);
        }

        saveQues.add(question);
        map.put("questionid",questionid);

        //qlevel试题类型1单体2母题3子题
        if(question.getQlevel() == 2){//是母体并且包含子题
            List<TQuestion> sonques = question.getQuestions();
            for(TQuestion sq : sonques){
                String sqid = StudyUtil.getId();
                sq.setQuestionid(sqid);
                sq.setCount(0);
                sq.setQstate(1);
                sq.setBelong(4);
                sq.setHashear(0);
                sq.setQuestionpid(questionid);
                sq.setSubjectid(question.getSubjectid());
                sq.setCreateid(question.getCreateid());
                sq.setCreatetime(timestamp);
                sq.setSchoolid(question.getSchoolid());
                saveQues.add(sq);
                Map sonmap = new HashMap();
                sonmap.put("sorder",sq.getSorder());
                sonmap.put("quesitonid",sqid);
                sonlist.add(sonmap);
            }
        }

        //单题型母题关联知识点
        List<TQuestionPoint> points = question.getQuestionPoints();
        if(points!=null && points.size()>0){
            for(TQuestionPoint p : points){
                p.setQpid(StudyUtil.getId());
                p.setQuestionid(questionid);
                p.setCreateid(question.getCreateid());
                p.setCreatetime(timestamp);
                p.setSchoolid(question.getSchoolid());
                saveQPoints.add(p);
            }
        }

        map.put("sonlist",sonlist);
        return map;
    }

    //设置章节
    private void setSaveUpdateQuesitonDirector(QuestionVo qvo,TQuestion question,List<TQuestionDirector> saveQDirs){
        //原试题关联章节
        List<DirectorVo> dirs = qvo.getDirectors();
        if(dirs!=null && dirs.size()>0){
            for(DirectorVo d : dirs){
                TQuestionDirector qd = new TQuestionDirector();
                qd.setQdid(StudyUtil.getId());
                qd.setQuestionid(question.getQuestionid());
                qd.setLsbid(d.getLsbid());
                qd.setDirectorid(d.getDirectorid());
                qd.setCreateid(question.getCreateid());
                qd.setCreatetime(question.getCreatetime());

                saveQDirs.add(qd);
            }
        }
    }

    /*
     * @Description 获取试题关联知识点
     * @Date 2023/8/28 15:30:01
     * @Author WN
     * @Param [questionid]
     * @Return java.util.Map
     **/
    public List<Map> listPointsByQuestionid(String questionid) {
        return questionPointMapper.listPointsByQuestionid(questionid);
    }

    /**
     * @Description 分享伙伴校
     * @Date 2023/8/29 9:26
     * @Author YWX
     * @Param [question]
     * @Return com.xhkjedu.vo.ResultVo
     **/
    @Transactional(rollbackFor = Exception.class)
    public ResultVo shareGroupSchool(TQuestion question) {
        List<Map> schools = question.getSchools();
        if (N_Utils.isListEmpty(schools)) return new ResultVo(1, "伙伴校不能为空");
        String shareqid = question.getQuestionid();
        Integer createid = question.getCreateid();
        int timestamp = N_Utils.getSecondTimestamp();
        TQuestion q = questionMapper.getQuestionAndDirectorPointById(shareqid);
        List<TQuestion> list = new ArrayList<>();
        if (q.getQlevel().equals(2)) {
            list = questionMapper.listSonQuestionsForShare(shareqid);
        }
        List<TQuestionPoint> questionPoints = q.getQuestionPoints();
        List<TQuestionDirector> questionDirectors = q.getDirectors();
        List<Integer> schoolids = q.getSchools().stream().map(s -> (Integer) s.get("schoolid")).collect(Collectors.toList());
        List<TQuestion> questions = new ArrayList<>();//未分享过的学校试题集合
        List<TQuestionPoint> points = new ArrayList<>();//未分享过的学校试题知识点集合
        List<TQuestionDirector> directors = new ArrayList<>();//未分享过的学校试题章节集合
        List<Integer> schoolIds = new ArrayList<>();//已分享过的学校集合
        for (Map<String, Integer> school : schools) {
            Integer schoolid = school.get("schoolid");
            if (N_Utils.numInList(schoolid, schoolids)) {//已分享过的学校需更新试题时间
                schoolIds.add(schoolid);
                continue;
            }
            //试题
            TQuestion tq = new TQuestion();
            BeanUtils.copyProperties(q, tq);
            String questionid = StudyUtil.getId();
            tq.setQuestionid(questionid);
            tq.setCount(0);
            tq.setCreateid(createid);
            tq.setCreatetime(timestamp);
            tq.setBelong(10);
            tq.setSchoolid(schoolid);
            tq.setShareqid(shareqid);
            questions.add(tq);
            for (TQuestion s : list) {
                TQuestion sq = new TQuestion();
                BeanUtils.copyProperties(s, sq);
                sq.setQuestionid(StudyUtil.getId());
                sq.setQuestionpid(questionid);
                sq.setCount(0);
                sq.setCreateid(createid);
                sq.setCreatetime(timestamp);
                sq.setBelong(10);
                sq.setSchoolid(schoolid);
                sq.setShareqid(shareqid);
                questions.add(sq);
            }

            //试题关联知识点
            for (TQuestionPoint p : questionPoints) {
                TQuestionPoint qp = new TQuestionPoint();
                BeanUtils.copyProperties(p, qp);
                qp.setQpid(StudyUtil.getId());
                qp.setQuestionid(questionid);
                qp.setCreateid(createid);
                qp.setCreatetime(timestamp);
                points.add(qp);
            }

            //试题关联章节
            for (TQuestionDirector d : questionDirectors) {
                TQuestionDirector qd = new TQuestionDirector();
                BeanUtils.copyProperties(d, qd);
                qd.setQdid(StudyUtil.getId());
                qd.setQuestionid(questionid);
                qd.setCreateid(createid);
                qd.setCreatetime(timestamp);
                directors.add(qd);
            }
        }

        if (N_Utils.isListNotEmpty(questions)) questionMapper.saveBathQuestion(questions);
        if (N_Utils.isListNotEmpty(points)) questionPointMapper.batchSave(points);
        if (N_Utils.isListNotEmpty(directors)) questionDirectorMapper.batchSave(directors);
        if (N_Utils.isListNotEmpty(schoolIds)) questionMapper.batchUpdateTime(schoolIds, shareqid, timestamp);
        return new ResultVo(0, "分享成功");
    }

    /**
     * @Description 获取分享的伙伴校
     * @Date 2023/8/29 11:22
     * @Author YWX
     * @Param [questionid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map<String, Object>> listSharePartnerSchool(String questionid) {
        return questionMapper.listSharePartnerSchool(questionid);
    }

    /*
     * @Description 根据试题ids获取对应知识点集合
     * @Date 2023/8/31 15:13:28
     * @Author WN
     * @Param [questionids]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map> listQuestionPoints(List<String> questionids) {
        return questionPointMapper.listQuestionPoints(questionids);
    }
}
