package com.qxgmat.service.inline;

import com.github.pagehelper.Page;
import com.nuliji.tools.AbstractService;
import com.nuliji.tools.PageResult;
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.constants.enums.status.DirectionStatus;
import com.qxgmat.data.dao.TextbookQuestionMapper;
import com.qxgmat.data.dao.entity.Question;
import com.qxgmat.data.dao.entity.TextbookQuestion;
import com.qxgmat.data.dao.entity.UserQuestion;
import com.qxgmat.data.inline.PaperStat;
import com.qxgmat.data.relation.TextbookQuestionRelationMapper;
import com.qxgmat.data.relation.entity.TextbookQuestionRelation;
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 TextbookQuestionService extends AbstractService {
    private static final Logger logger = LoggerFactory.getLogger(TextbookQuestionService.class);

    @Resource
    private TextbookQuestionMapper textbookQuestionMapper;

    @Resource
    private QuestionService questionService;

    @Resource
    private TextbookQuestionRelationMapper textbookQuestionRelationMapper;

    /**
     * 管理后台查询列表
     * @param page
     * @param pageSize
     * @param questionType
     * @param paperId
     * @param questionNoId
     * @param order
     * @param direction
     * @return
     */
    public Page<TextbookQuestion> listAdmin(int page, int pageSize, String questionType, Number paperId, Integer questionNoId, String order, DirectionStatus direction){
        if(order.isEmpty()) order = "id";
        if (direction == null){
            direction = DirectionStatus.DESC;
        }
        String finalOrder = order;
        DirectionStatus finalDirection = direction;

        Page<TextbookQuestion> p = page(() -> {
            textbookQuestionRelationMapper.listAdmin(questionType, paperId, questionNoId, finalOrder, finalDirection.key);
        }, page, pageSize);

        Collection ids = Transform.getIds(p, TextbookQuestion.class, "id");

        // 获取详细数据
        List<TextbookQuestion> list = select(ids);
        Transform.replace(p, list, TextbookQuestion.class, "id");

        return p;
    }

    /**
     * 根据题目id获取题目列表
     * @param page
     * @param size
     * @param no
     * @return
     */
    public PageResult<TextbookQuestionRelation> searchNo(int page, int size, String no){
        Example example = new Example(TextbookQuestion.class);
        example.and(
                example.createCriteria()
                        .andLike("title", no)
        );
        example.orderBy("id").asc();
        Page<TextbookQuestion> p = page(()->select(textbookQuestionMapper, example), page, size);
        return new PageResult<>(relation(p), p.getTotal());
    }

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

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

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

    /**
     * 根据题目获取总试卷统计信息
     * @param questionNoList
     * @return
     */
    public PaperStat statPaper(List<TextbookQuestion> questionNoList){
        PaperStat stat = new PaperStat();
        Integer totalTime = 0;
        Integer totalNumber = 0;
        Integer totalCorrect = 0;
        for(TextbookQuestion 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<TextbookQuestion> questionNoList = select(ids);
        Map questionNoMap = Transform.getMap(questionNoList, TextbookQuestion.class, "id");
        List<TextbookQuestion> l = new ArrayList<>();
        for(Integer k: questionNoIdsMap.keySet()){
            l.clear();
            for (Integer questionNoId : questionNoIdsMap.get(k)){
                l.add((TextbookQuestion)questionNoMap.get(questionNoId));
            }
            relationMap.put(k, statPaper(l));
        }

        return relationMap;
    }

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

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

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

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

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

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

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

    public TextbookQuestion get(Number id){
        TextbookQuestion in = one(textbookQuestionMapper, id);

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

    public Page<TextbookQuestion> select(int page, int pageSize){
        return select(textbookQuestionMapper, page, pageSize);
    }

    public List<TextbookQuestion> select(Collection ids){
        return select(textbookQuestionMapper, ids);
    }

}
