package com.ruoyi.ie.service.impl;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ie.domain.KnowledgeTree;
import com.ruoyi.ie.domain.Questions;
import com.ruoyi.ie.mapper.KnowledgeTreeMapper;
import com.ruoyi.ie.mapper.QuestionsMapper;
import com.ruoyi.ie.service.IQuestionsService;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 试题Service业务层处理
 *
 * @author mingxue
 * @date 2021-06-19
 */
@Service
public class QuestionsServiceImpl implements IQuestionsService
{
    @Autowired
    private QuestionsMapper questionsMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private KnowledgeTreeMapper knowledgeTreeMapper;
    /**
     * 查询试题
     *
     * @param id 试题ID
     * @return 试题
     */
    @Override
    public Questions selectQuestionsById(Long id)
    {
        Questions questions= questionsMapper.selectQuestionsById(id);
        if(StringUtils.isNotNull(questions)){
            List<Questions> list= Arrays.asList(questions);
            list = this.changeQuestionList(list);
            return list.get(0);
        }
        return questions;
    }

    @Override
    public List<Questions> selectQuestionsByZtPaperId(Map map) {
        return questionsMapper.selectQuestionsByZtPaperId(map);
    }

    @Override
    public Questions getQuestionInfo(Long id)
    {
        return questionsMapper.selectQuestionsById(id);
    }

    /**
     * 查询试题列表
     *
     * @param questions 试题
     * @return 试题
     */
    @Override
    public List<Questions> selectQuestionsList(Questions questions)
    {
        return questionsMapper.selectQuestionsList(questions);
    }

    @Override
    public List<Questions> selectQuestionsFilter(Questions questions) {
        return questionsMapper.selectQuestionsFilter(questions);
    }

    /**
     * 新增试题
     *
     * @param questions 试题
     * @return 结果
     */
    @Override
    public int insertQuestions(Questions questions)
    {
        return questionsMapper.insertQuestions(questions);
    }

    /**
     * 修改试题
     *
     * @param questions 试题
     * @return 结果
     */
    @Override
    public int updateQuestions(Questions questions)
    {
        return questionsMapper.updateQuestions(questions);
    }

    /**
     * 批量删除试题
     *
     * @param ids 需要删除的试题ID
     * @return 结果
     */
    @Override
    public int deleteQuestionsByIds(Long[] ids)
    {
        return questionsMapper.deleteQuestionsByIds(ids);
    }

    /**
     * 删除试题信息
     *
     * @param id 试题ID
     * @return 结果
     */
    @Override
    public int deleteQuestionsById(Long id)
    {
        return questionsMapper.deleteQuestionsById(id);
    }

    @Override
    public int updateBatchQtpyeByIds(Long[] ids,String qtpye) {
        return questionsMapper.updateBatchQtpyeByIds(ids,qtpye);
    }

    @Override
    public int getQuestionsCountByChapterIds(List<Long> chapterIds) {
        return questionsMapper.getQuestionsCountByChapterIds(chapterIds);
    }

    @Override
    public int getQuestionsCountByChapterId(Long chapterId) {
        List<Long> chapterIds =Arrays.asList(chapterId);
        return questionsMapper.getQuestionsCountByChapterIds(chapterIds);
    }


    @Override
    public List<Questions> getPaperQuestionList(Questions body) {
        List<Questions> list = questionsMapper.getPaperQuestionList(body);
        list = this.changeQuestionList(list);
        return list;
    }

    @Override
    public List<Questions> getPaperQuestionListByKnowledge(Questions body) {
        List<Questions> list = questionsMapper.getPaperQuestionListByKnowledge(body);
        list = this.changeQuestionList(list);
        return list;
    }


    public List<Questions> getPaperQuestionListByPaperId(Long paperId) {
        List<Questions> list = questionsMapper.getPaperQuestionListByPaperId(paperId);
        list = this.changeQuestionList(list);
        return list;
    }

    @Override
    public String correctImageUrl(String content) {
        if (StringUtils.isNotBlank(content)) {
            String value = configService.selectConfigByKey("file_pre");
            if(StringUtils.isBlank(value)) {
                value = "https://file.mingxuejinbang.com/tikubao/";
            }
            if(StringUtils.isBlank(value)) {
                value = "https://file.mingxue100.com/tikubao/";
            }

            return content.replaceAll("src=\"/", "src=\"" + value).replaceAll("src=\'/", "src=\'" + value);
        }
        return content;
    }

    public List<Questions> fillSubquestions(List<Questions> questionsList) {
        Map<Integer, Questions> questionsMap = Maps.newHashMap();
        for (Questions q : questionsList) {
            if (null != q.getIsSubType()) {
                q.setTitle0(null);
                q.setTitle1(null);
                q.setTitle(null);
                questionsMap.put(q.getIsSubType(), q);
            }
        }
        String value = configService.selectConfigByKey("file_pre");
        if(StringUtils.isBlank(value)) {
            value = "https://file.mingxuejinbang.com/tikubao/";//2.0
        }
        if(StringUtils.isBlank(value)) {
            value = "https://file.mingxue100.com/tikubao/";//1.0
        }
        Map<Integer, List<Questions>> map = Maps.newHashMap();
        if(questionsMap.size() > 0) {
            // 根据题目id集合获取题目
            List<Questions> subquestionList = questionsMapper.selectQuestionsByPids(questionsMap.keySet().toArray(new Integer[]{}));
            if(CollectionUtils.isNotEmpty(subquestionList)) {
                for(Questions subquestions : subquestionList ) {
                    Questions parent = questionsMap.get(subquestions.getIsSubType());
                    if (null != parent && null == parent.getTitle()) {
                        parent.setTitle(subquestions.getTitle0());
                    }
                    subquestions.setTitle0(null);
                    subquestions.setTitle1(null);
                    List<Questions> list = map.get(subquestions.getIsSubType());
                    if(null == list) {
                        list = new ArrayList<>();
                        map.put(subquestions.getIsSubType(), list);
                    }
                    if(StringUtils.isNotEmpty(subquestions.getTitle())){
                        subquestions.setTitle(subquestions.getTitle().replaceAll("src=\"/", "src=\""+value));
                    }
                    if(StringUtils.isNotBlank(subquestions.getAnswer1())) {
                        subquestions.setAnswer1(subquestions.getAnswer1().replaceAll("src=\"/", "src=\""+value));
                    }
                    if(StringUtils.isNotBlank(subquestions.getAnswer2())) {
                        subquestions.setAnswer2(subquestions.getAnswer2().replaceAll("src=\"/", "src=\""+value));
                    }
                    if(StringUtils.isNotBlank(subquestions.getParse())) {
                        subquestions.setParse(subquestions.getParse().replaceAll("src=\"/", "src=\""+value));
                    }
                    list.add(subquestions);
                }
            }
            if (map.size() > 0) {
                for (Integer isSubType : questionsMap.keySet()) {
                    Questions parent = questionsMap.get(isSubType);
                    List<Questions> subQuesList = map.get(isSubType);
                    parent.setScore(subQuesList.stream().mapToLong(t -> t.getScore()).sum());
                    parent.setSubquestions(subQuesList);
                }
            }
        }
        return questionsList;
    }

    @Override
    public List<Questions> changeQuestionList(List<Questions> list, boolean keepTitleNotChange) {

        if(CollectionUtils.isNotEmpty(list)) {
            String value = configService.selectConfigByKey("file_pre");
            if(StringUtils.isBlank(value)) {
                value = "https://file.mingxuejinbang.com/tikubao/";
            }
            if(StringUtils.isBlank(value)) {
                value = "https://file.mingxue100.com/tikubao/";
            }
            List<Long> questionIds = new ArrayList<>();
            for(Questions questions: list) {
                questions.setTitle(questions.getTitle().replaceAll("src=\"/", "src=\""+value));
                questions.setTitle(questions.getTitle().replaceAll("src=\'/", "src=\'"+value));
                if (StringUtils.isNotBlank(questions.getOptionA())) {
                    questions.setOptionA(questions.getOptionA().replaceAll("src=\"/", "src=\"" + value));
                    questions.setOptionA(questions.getOptionA().replaceAll("src=\'/", "src=\'" + value));
                }
                if (StringUtils.isNotBlank(questions.getOptionB())) {
                    questions.setOptionB(questions.getOptionB().replaceAll("src=\"/", "src=\"" + value));
                    questions.setOptionB(questions.getOptionB().replaceAll("src=\'/", "src=\'" + value));
                }
                if (StringUtils.isNotBlank(questions.getOptionC())) {
                    questions.setOptionC(questions.getOptionC().replaceAll("src=\"/", "src=\"" + value));
                    questions.setOptionC(questions.getOptionC().replaceAll("src=\'/", "src=\'" + value));
                }
                if (StringUtils.isNotBlank(questions.getOptionD())) {
                    questions.setOptionD(questions.getOptionD().replaceAll("src=\"/", "src=\"" + value));
                    questions.setOptionD(questions.getOptionD().replaceAll("src=\'/", "src=\'" + value));
                }
                if (StringUtils.isNotBlank(questions.getOptionE())) {
                    questions.setOptionE(questions.getOptionE().replaceAll("src=\"/", "src=\"" + value));
                    questions.setOptionE(questions.getOptionE().replaceAll("src=\'/", "src=\'" + value));
                }
                if(StringUtils.isNotBlank(questions.getAnswer1())) {
                    questions.setAnswer1(questions.getAnswer1().replaceAll("src=\"/", "src=\""+value));
                    questions.setAnswer1(questions.getAnswer1().replaceAll("src=\'/", "src=\'"+value));
                }
                if(StringUtils.isNotBlank(questions.getAnswer2())) {
                    questions.setAnswer2(questions.getAnswer2().replaceAll("src=\"/", "src=\""+value));
                    questions.setAnswer2(questions.getAnswer2().replaceAll("src=\'/", "src=\'"+value));
                }
                if(StringUtils.isNotBlank(questions.getParse())) {
                    questions.setParse(questions.getParse().replaceAll("src=\"/", "src=\""+value));
                    questions.setParse(questions.getParse().replaceAll("src=\'/", "src=\'"+value));
                }
                if(null!=questions.getIsSub()&&questions.getIsSub()==1){
                    questionIds.add(questions.getId());
                }
            }
            fillSubquestions(list);
        }

        return list;
    }

    @Override
    public List<Questions> changeQuestionList(List<Questions> list) {
        return changeQuestionList(list, false);
    }

    @Override
    public List<Questions> getQuestionsByQTypeAndNum(List<Questions> params) {
        List<Questions> data = new ArrayList<>();
        for(Questions q : params) {
            List<Questions> res = questionsMapper.getPaperQuestionList(q);
            if (CollectionUtils.isNotEmpty(res)) {
                data.addAll(res);
            }
        }
        fillQuestionInfo(data);
        return data;
    }

    @Override
    public List<Questions> selectIdsByIdGreaterThan(Long id) {
        return questionsMapper.selectIdsByIdGreaterThan(id);
    }

    @Override
    public List<Questions> selectIdsByIdGreaterThan2(Long id) {
        return questionsMapper.selectIdsByIdGreaterThan2(id);
    }

    @Override
    public List<Questions> getPaperQuestionListBySubject(Questions body) {
        List<Questions> list = questionsMapper.getPaperQuestionListBySubject(body);
        list = this.changeQuestionList(list);
        return list;
    }



    /**
     *
     * @param chapterTree 传入的
     * @param oldids 用来收集最底层的id
     */
//    private void getChapterTreeIds(ChapterTree chapterTree, List<Long> oldids) {
//        // 找出章节的所有末节点
//        ChapterTree query = new ChapterTree();
//        query.setPid(chapterTree.getId());
//        // key: pid, value: children ids
//
//        List<ChapterTree> children = chapterTreeMapper.selectChapterTreeList(query);
//
//        if (CollectionUtils.isEmpty(children)) {
//            // 如果没有子，说明自己就是末节点
//            oldids.add(chapterTree.getId());
//        } else {
//
//            Map<Long, List<Long>> map = new LinkedHashMap<>();
//            while (CollectionUtils.isNotEmpty(children)) {
//                groupChildrenIds(children, map);
//                List<Long> pids = children.stream().map(ChapterTree::getId).collect(Collectors.toList());
//                query = new ChapterTree();
//                query.setPids(pids);
//                children = chapterTreeMapper.selectChapterTreeList(query);
//            }
//            for (Long pid : map.keySet()) {
//                if (pid == 0L) {
//                    continue;
//                }
//                List<Long> childrenIds = map.get(pid);
//                if (CollectionUtils.isEmpty(childrenIds)) {
//                    oldids.add(pid);
//                }
//            }
//
//
//
////            for (ChapterTree child : children) {
////                getChapterTreeIds(child, oldids);
////            }
//        }
//    }

//    private void groupChildrenIds(List<ChapterTree> children, Map<Long, List<Long>> map) {
//        // 放parent
//        for (ChapterTree c : children) {
//            List<Long> childrenIds = map.get(c.getPid());
//            if (childrenIds == null) {
//                childrenIds = new ArrayList<>();
//                map.put(c.getPid(), childrenIds);
//            }
//            childrenIds.add(c.getId());
//        }
//        // 放自己
//        for (ChapterTree c : children) {
//            map.put(c.getId(), new ArrayList<>());
//        }
//    }

    @Override
    public List<Questions> selectByKnowledgeTree(Questions query, Integer pageNum, Integer pageSize) {
        if (query.getKnowledgeId() != null) {
            // 所有末节点的集合
            List<KnowledgeTree> oldids = new ArrayList<>();
            KnowledgeTree knowledgeTree = knowledgeTreeMapper.selectKnowledgeTreeById(query.getKnowledgeId());
            getKnowledgeTreeOldids(knowledgeTree, oldids);
            query.setKnowledgeIds(oldids.stream().map(KnowledgeTree::getId).collect(Collectors.toList()));
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Questions> questions = questionsMapper.selectByKnowledgeTreeOldids(query);
        return questions;
    }

    public void getKnowledgeTreeOldids(KnowledgeTree knowledgeTree, List<KnowledgeTree> oldids) {
        // 找出章节的所有末节点
        KnowledgeTree query = new KnowledgeTree();
        query.setPids(Lists.newArrayList(knowledgeTree.getId()));
        List<KnowledgeTree> midList = knowledgeTreeMapper.selectKnowledgeTreeList(query);
        if (CollectionUtils.isEmpty(midList)) {
            // 如果没有子，说明自己就是末节点
            oldids.add(knowledgeTree);
        } else {
            Map<Long, KnowledgeTree> midMap = Maps.newLinkedHashMap();
            for (KnowledgeTree mid : midList) {
                midMap.put(mid.getId(), mid);
            }
            query.setPids(Lists.newArrayList(midMap.keySet()));
            List<KnowledgeTree> children = knowledgeTreeMapper.selectKnowledgeTreeList(query);
            children.stream().forEach(t -> midMap.remove(t.getPid()));
            oldids.addAll(midMap.values());
            oldids.addAll(children);
        }
    }

//    private ChapterTree getTopChapter(Long subjectId, Integer editionId, Integer gradeId, Long chapterId) {
//        ChapterTree t = chapterTreeMapper.selectChapterTreeById(chapterId);
//        int cnt = 0;
//        while (t != null && t.getPid() != 0) {
//            t = chapterTreeMapper.selectChapterTreeById(t.getPid());
//            if (cnt++ > 100) {
//                break;
//            }
//        }
//        return t;
//    }





    @Override
    public List<Questions> getQuestionsByKnowledgeForParactice(Integer subjectId, Long knowledgeId) {
        Questions questions = new Questions();
        KnowledgeTree knowledgeTree = knowledgeTreeMapper.selectKnowledgeTreeById(knowledgeId);
        List<KnowledgeTree> ids = new ArrayList<>();
        getKnowledgeTreeOldids(knowledgeTree, ids);
        questions.setKnowledgeIds(ids.stream().map(KnowledgeTree::getId).collect(Collectors.toList()));
        PageHelper.startPage(1, 10);
        return questionsMapper.getQuestionsByKnowledgeForParactice(questions);
    }

    @Override
    public List<Questions> selectCollectedList(Questions questions) {
        return questionsMapper.selectCollectedList(questions);
    }

    @Override
    public List<Questions> selectWrongQuestions(Questions questions) {
        return questionsMapper.selectWrongQuestions(questions);
    }

    @Override
    public void fillCollectInfo(Long userId, List<Questions> questions) {
        if (CollectionUtils.isEmpty(questions)) {
            return;
        }
//        for (Questions q : questions) {
//            System.out.println(q);
//        }
        List<Long> ids = questions.stream().map(Questions::getId).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("ids", ids);
        List<Questions> collectInfos = questionsMapper.selectCollectInfo(map);
        Set<Long> collected = collectInfos.stream().map(Questions::getId).collect(Collectors.toSet());
        questions.forEach(e -> {
            e.setCollect(collected.contains(e.getId()));
        });
    }

    @Override
    public List<Questions> selectByKnowledgeIds(Questions questions) {
        return questionsMapper.selectByKnowledgeIds(questions);
    }

    @Override
    public void fillQuestionInfo(List<Questions> list) {
        String value = configService.selectConfigByKey("file_pre");
        if(StringUtils.isBlank(value)) {
            value = "https://file.mingxuejinbang.com/tikubao/";
        }
        if(StringUtils.isBlank(value)) {
            value = "https://file.mingxue100.com/tikubao/";
        }
        List<Questions> res = list;
        List<Long> questionIds = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(res)) {
            for(Questions questions: res) {
                questions.setTitle(questions.getTitle().replaceAll("src=\"/", "src=\""+value));
                questions.setTitle(questions.getTitle().replaceAll("src=\'/", "src=\'"+value));
                if(StringUtils.isNotBlank(questions.getAnswer1())) {
                    questions.setAnswer1(questions.getAnswer1().replaceAll("src=\"/", "src=\""+value));
                    questions.setAnswer1(questions.getAnswer1().replaceAll("src=\'/", "src=\'"+value));
                }
                if(StringUtils.isNotBlank(questions.getAnswer2())) {
                    questions.setAnswer2(questions.getAnswer2().replaceAll("src=\"/", "src=\""+value));
                    questions.setAnswer2(questions.getAnswer2().replaceAll("src=\'/", "src=\'"+value));
                }
                if(StringUtils.isNotBlank(questions.getParse())) {
                    questions.setParse(questions.getParse().replaceAll("src=\"/", "src=\""+value));
                    questions.setParse(questions.getParse().replaceAll("src=\'/", "src=\'"+value));
                }
                if(null!=questions.getIsSub()&&questions.getIsSub()==1){
                    questionIds.add(questions.getId());
                }
            }
        }

    }

    @Override
    public List<Questions> selectByIds(Long[] ids) {
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        return questionsMapper.selectByIds(map);
    }

    public static void main(String[] args) throws Exception {
        String title = "已知集合A={x|x<sup>2</sup>-x-6＞0}，<img src=\"http://www.com/tikuimages/2/2020/700/xuekubao3/cddd8b1e-e81f-11ea-876c-b42e9921e93e_xkb185.png\" encode=\"encode\" data-latex=\"B%3D%5C%7By%7Cy%3Dx-%20%5Cfrac%20%7B8%7D%7Bx%7D%EF%BC%8Cx%EF%BC%9E4%5C%7D\" w=\"156px\" h=\"33px\" />，则A∩B=（　　）";
        String value = "https://file.mingxue100.com/tikubao/";
        title = title.replaceAll("src=\"/", "src=\""+value);
        System.out.println("title1: " + title);

        title = title.replaceAll("src=\'/", "src=\'"+value);
        System.out.println("title2: " + title);



    }

    @Override
    public void replaceImage(List<Questions> list,Boolean isHttp) {
        if(CollectionUtils.isNotEmpty(list)) {
            String value = configService.selectConfigByKey("file_pre");
            if(StringUtils.isBlank(value)) {
                value = "https://file.mingxuejinbang.com/tikubao/";
            }
            if(StringUtils.isBlank(value)) {
                value = "https://file.mingxue100.com/tikubao/";
            }

            if(isHttp){
                value = value.replace("https://","http://");
            }
            List<Long> questionIds = new ArrayList<>();
            for(Questions questions: list) {
                questions.setTitle(questions.getTitle().replaceAll("src=\"/", "src=\""+value));
                questions.setTitle(questions.getTitle().replaceAll("src=\'/", "src=\'"+value));
                if(StringUtils.isNotBlank(questions.getAnswer1())) {
                    questions.setAnswer1(questions.getAnswer1().replaceAll("src=\"/", "src=\""+value));
                    questions.setAnswer1(questions.getAnswer1().replaceAll("src=\'/", "src=\'"+value));
                }
                if(StringUtils.isNotBlank(questions.getAnswer2())) {
                    questions.setAnswer2(questions.getAnswer2().replaceAll("src=\"/", "src=\""+value));
                    questions.setAnswer2(questions.getAnswer2().replaceAll("src=\'/", "src=\'"+value));
                }
                if(StringUtils.isNotBlank(questions.getParse())) {
                    questions.setParse(questions.getParse().replaceAll("src=\"/", "src=\""+value));
                    questions.setParse(questions.getParse().replaceAll("src=\'/", "src=\'"+value));
                }

                if (StringUtils.isNotBlank(questions.getOptionA())) {
                    questions.setOptionA(questions.getOptionA().replaceAll("src=\"/", "src=\""+value));
                    questions.setOptionA(questions.getOptionA().replaceAll("src=\'/", "src=\'"+value));
                }
                if (StringUtils.isNotBlank(questions.getOptionB())) {
                    questions.setOptionB(questions.getOptionB().replaceAll("src=\"/", "src=\""+value));
                    questions.setOptionB(questions.getOptionB().replaceAll("src=\'/", "src=\'"+value));
                }
                if (StringUtils.isNotBlank(questions.getOptionC())) {
                    questions.setOptionC(questions.getOptionC().replaceAll("src=\"/", "src=\""+value));
                    questions.setOptionC(questions.getOptionC().replaceAll("src=\'/", "src=\'"+value));
                }
                if (StringUtils.isNotBlank(questions.getOptionD())) {
                    questions.setOptionD(questions.getOptionD().replaceAll("src=\"/", "src=\""+value));
                    questions.setOptionD(questions.getOptionD().replaceAll("src=\'/", "src=\'"+value));
                }
                if (StringUtils.isNotBlank(questions.getOptionE())) {
                    questions.setOptionE(questions.getOptionE().replaceAll("src=\"/", "src=\""+value));
                    questions.setOptionE(questions.getOptionE().replaceAll("src=\'/", "src=\'"+value));
                }

                if(null!=questions.getIsSub()&&questions.getIsSub()==1){
                    questionIds.add(questions.getId());
                }
            }
        }
    }

        @Override
    public void replaceImage(List<Questions> list) {
        replaceImage(list,false);
    }

    @Override
    public Questions selectQuestionsByIdNoChange(Long id) {
        Questions questions= questionsMapper.selectQuestionsById(id);
        return questions;
    }




//    @Override
//    public QuestionsQueryResultDto QuestionsQueryResultDtoById(Long questionId) {
//        QuestionsQueryResultDto questionsQueryResultDto = new QuestionsQueryResultDto();
//        Questions questions = questionsMapper.selectQuestionsById(questionId);
//        BeanUtils.copyProperties(questions,questionsQueryResultDto);
//        if(StringUtils.isNotNull(questions.getIssub())){
//            if(questions.getIssub().equals(1)){
//                Subquestions subquestions = new Subquestions();
//                subquestions.setPid(questions.getId());
//                List<Subquestions> subquestions1 = subquestionsService.selectSubquestionsList(subquestions);
//                questionsQueryResultDto.setSubquestions(subquestions1);
//            }
//        }
//        return questionsQueryResultDto;
//    }
}
