package com.qxgmat.service.inline;

import com.github.pagehelper.Page;
import com.nuliji.tools.AbstractService;
import com.nuliji.tools.Transform;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.exception.SystemException;
import com.nuliji.tools.mybatis.Example;
import com.qxgmat.data.dao.SentenceQuestionMapper;
import com.qxgmat.data.dao.entity.Manager;
import com.qxgmat.data.dao.entity.Question;
import com.qxgmat.data.dao.entity.SentenceQuestion;
import com.qxgmat.data.dao.entity.UserQuestion;
import com.qxgmat.data.inline.PaperStat;
import com.qxgmat.data.relation.SentenceQuestionRelationMapper;
import com.qxgmat.data.relation.entity.SentenceQuestionRelation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SentenceQuestionService extends AbstractService {
    private static final Logger logger = LoggerFactory.getLogger(SentenceQuestionService.class);

    @Resource
    private SentenceQuestionMapper sentenceQuestionMapper;

    @Resource
    private QuestionService questionService;

    @Resource
    private SentenceQuestionRelationMapper sentenceQuestionRelationMapper;

    /**
     * 根据题目编号id列表获取关联题目
     * @param ids
     * @return
     */
    public List<SentenceQuestionRelation> listWithRelationByIds(Number[] ids){
        List<SentenceQuestion> p = select(sentenceQuestionMapper, ids);
        return relation(p);
    }

    /**
     * 根据题目编号id列表获取关联题目
     * @param ids
     * @return
     */
    public Map<Number, SentenceQuestionRelation> mapWithRelationByIds(Number[] ids){
        List<SentenceQuestion> p = select(sentenceQuestionMapper, ids);
        List<SentenceQuestionRelation> list = relation(p);
        Map<Number, SentenceQuestionRelation> map = new HashMap<>();
        for(SentenceQuestionRelation relation : list){
            map.put(relation.getId(), relation);
        }
        return map;
    }

    /**
     * 累加做题记录到sentenceQuestion
     * @param question
     */
    public void accumulation(UserQuestion question){
        sentenceQuestionRelationMapper.accumulation(question.getQuestionNoId(), 1, question.getTime(), question.getIsCorrect());
    }

    /**
     * 根据题目获取总试卷统计信息
     * @param questionNoList
     * @return
     */
    public PaperStat statPaper(List<SentenceQuestion> questionNoList){
        PaperStat stat = new PaperStat();
        Integer totalTime = 0;
        Integer totalNumber = 0;
        Integer totalCorrect = 0;
        for(SentenceQuestion questionNo : questionNoList){
            totalTime += questionNo.getTotalTime();
            totalNumber += questionNo.getTotalNumber();
            totalCorrect += questionNo.getTotalCorrect();
        }
        stat.setTotalCorrect(totalCorrect);
        stat.setTotalNumber(totalNumber);
        stat.setTotalTime(totalTime);
        return stat;
    }

    /**
     * 根据试卷分组获取统计信息
     * @param questionNoIdsMap
     * @return
     */
    public Map<Integer, PaperStat> statPaperMap(Map<Integer, Integer[]> questionNoIdsMap){
        Map<Integer, PaperStat> relationMap = new HashMap<>();
        List<Integer> ids = new ArrayList<>();
        for(Integer[] questionNoIds : questionNoIdsMap.values()){
            ids.addAll(Arrays.stream(questionNoIds).collect(Collectors.toList()));
        }
        List<SentenceQuestion> questionNoList = select(ids);
        Map questionNoMap = Transform.getMap(questionNoList, SentenceQuestion.class, "id");
        List<SentenceQuestion> l = new ArrayList<>();
        for(Integer k: questionNoIdsMap.keySet()){
            l.clear();
            for (Integer questionNoId : questionNoIdsMap.get(k)){
                l.add((SentenceQuestion)questionNoMap.get(questionNoId));
            }
            relationMap.put(k, statPaper(l));
        }

        return relationMap;
    }

    /**
     * 根据长难句题目关系，获取完整题目：列表
     * @param p
     * @return
     */
    public List<SentenceQuestionRelation> relation(List<SentenceQuestion> p){
        List<SentenceQuestionRelation> relationList = Transform.convert(p, SentenceQuestionRelation.class);

        Collection questionIds = Transform.getIds(p, SentenceQuestion.class, "questionId");
        List<Question> questions = questionService.select(questionIds);
        Transform.combine(relationList, questions, SentenceQuestionRelation.class, "questionId", "question", Question.class, "id");
        return relationList;
    }

    /**
     * 根据长难句题目关系，获取完整题目：单个
     * @param p
     * @return
     */
    public SentenceQuestionRelation relation(SentenceQuestion p){
        SentenceQuestionRelation relation = Transform.convert(p, SentenceQuestionRelation.class);

        Question question = questionService.get(p.getQuestionId());
        relation.setQuestion(question);
        return relation;
    }

    /**
     * 根据序号查询
     * @param no
     * @return
     */
    public SentenceQuestion getByNo(Integer no){
        Example example = new Example(SentenceQuestion.class);
        example.and(
                example.createCriteria()
                        .andEqualTo("no", no)
        );
        return one(sentenceQuestionMapper, example);
    }

    public SentenceQuestion add(SentenceQuestion question){
        int result = insert(sentenceQuestionMapper, question);
        question = one(sentenceQuestionMapper, question.getId());
        if(question == null){
            throw new SystemException("题目添加失败");
        }
        return question;
    }

    public SentenceQuestion edit(SentenceQuestion question){
        SentenceQuestion in = one(sentenceQuestionMapper, question.getId());
        if(in == null){
            throw new ParameterException("题目不存在");
        }
        int result = update(sentenceQuestionMapper, question);
        return question;
    }

    public boolean delete(Number id){
        SentenceQuestion in = one(sentenceQuestionMapper, id);
        if(in == null){
            throw new ParameterException("题目不存在");
        }
        int result = delete(sentenceQuestionMapper, id);
        return result > 0;
    }

    public SentenceQuestion get(Number id){
        SentenceQuestion in = one(sentenceQuestionMapper, id);

        if(in == null){
            throw new ParameterException("题目不存在");
        }
        return in;
    }

    public Page<SentenceQuestion> select(int page, int pageSize){
        return select(sentenceQuestionMapper, page, pageSize);
    }

    public List<SentenceQuestion> select(Collection ids){
        return select(sentenceQuestionMapper, ids);
    }

}
