package com.ruoyi.learn.service.impl;

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

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.enums.QuestionType;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.learn.mapper.LearnQuestionsMapper;
import com.ruoyi.learn.domain.LearnQuestions;
import com.ruoyi.learn.service.ILearnQuestionsService;

/**
 * 试题Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-18
 */
@Service
public class LearnQuestionsServiceImpl implements ILearnQuestionsService
{
    @Autowired
    private LearnQuestionsMapper learnQuestionsMapper;
    @Autowired
    private ISysConfigService configService;

    /**
     * 获取图片路径列表（从配置中获取）
     * @return 图片路径列表
     */
    private List<String> getImagePaths() {
        String configValue = configService.selectConfigByKey("question.img.prefix");
        if (StringUtils.isBlank(configValue)) {
            // 如果配置为空，返回默认值
            return Arrays.asList("tikuimages", "mathJye");
        }
        // 将配置值按逗号分割并转换为List
        return Arrays.asList(configValue.split(","));
    }

    /**
     * 替换图片路径中的 tikuimages 和 mathJye
     * @param content 原始内容
     * @param value 替换值
     * @return 替换后的内容
     */
    private String replaceImagePath(String content, String value) {
        if (StringUtils.isBlank(content)) {
            return content;
        }
        String result = content;
        List<String> imagePaths = getImagePaths();
        for (String imagePath : imagePaths) {
            imagePath = imagePath.trim(); // 去除空格
            if (StringUtils.isNotBlank(imagePath)) {
                result = result.replaceAll("src=\"/" + imagePath, "src=\"" + value + imagePath);
                result = result.replaceAll("src=\'/" + imagePath, "src=\'" + value + imagePath);
            }
        }
        return result;
    }

    /**
     * 查询试题
     *
     * @param id 试题主键
     * @return 试题
     */
    @Override
    public LearnQuestions selectLearnQuestionsById(Long id)
    {
        LearnQuestions q = learnQuestionsMapper.selectLearnQuestionsById(id);
        List<LearnQuestions> questions = new ArrayList<>();
        questions.add(q);
        fillQuestionInfo(questions,false);
        return CollectionUtils.isNotEmpty(questions)?questions.get(0):q;
    }

    /**
     * 查询试题列表
     *
     * @param learnQuestions 试题
     * @return 试题
     */
    @Override
    public List<LearnQuestions> selectLearnQuestionsList(LearnQuestions learnQuestions)
    {
        // 判断qtpye是否为数字，如果是则使用枚举转换
        if (StringUtils.isNotEmpty(learnQuestions.getQtpye())){
            String qtpye = learnQuestions.getQtpye();
            // 判断是否为数字
            if (StringUtils.isNumeric(qtpye)) {
                try {
                    QuestionType questionType = QuestionType.of(qtpye);
                    if (questionType != null) {
                        // 设置qtpye为枚举的title
                        learnQuestions.setQtpye(questionType.getTitle());
                    }
                } catch (Exception e) {
                    // 如果转换失败，保持原值
                }
            }
        }
        List<LearnQuestions> questions = learnQuestionsMapper.selectLearnQuestionsList(learnQuestions);
        fillQuestionInfo(questions,false);
        return questions;
    }

    /**
     * 新增试题
     *
     * @param learnQuestions 试题
     * @return 结果
     */
    @Override
    public int insertLearnQuestions(LearnQuestions learnQuestions)
    {
        learnQuestions.setCreateTime(DateUtils.getNowDate());
        return learnQuestionsMapper.insertLearnQuestions(learnQuestions);
    }

    /**
     * 修改试题
     *
     * @param learnQuestions 试题
     * @return 结果
     */
    @Override
    public int updateLearnQuestions(LearnQuestions learnQuestions)
    {
        return learnQuestionsMapper.updateLearnQuestions(learnQuestions);
    }

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

    @Override
    public int updateQuestionType(String type, Collection<Long> ids)
    {
        return learnQuestionsMapper.updateQuestionType(type, ids);
    }


    /**
     * 删除试题信息
     *
     * @param id 试题主键
     * @return 结果
     */
    @Override
    public int deleteLearnQuestionsById(Long id)
    {
        return learnQuestionsMapper.deleteLearnQuestionsById(id);
    }

    @Override
    public List<LearnQuestions> selectCollectedList(LearnQuestions questions) {
        List<LearnQuestions> questionsList = learnQuestionsMapper.selectCollectedList(questions);
        fillQuestionInfo(questionsList,false);
        return questionsList;
    }

    @Override
    public void fillCollectInfo(Long userId, List<LearnQuestions> questions) {
        if (null == userId || CollectionUtils.isEmpty(questions)) {
            return;
        }
        List<Long> ids = questions.stream().map(LearnQuestions::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(ids)){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userId", userId);
            map.put("ids", ids);
            List<LearnQuestions> collectInfos = learnQuestionsMapper.selectCollectInfo(map);
            Set<Long> collected = collectInfos.stream().map(LearnQuestions::getId).collect(Collectors.toSet());
            questions.forEach(e -> {
                e.setCollect(collected.contains(e.getId()));
            });
        }
    }

    @Override
    public List<LearnQuestions> selectQuestionByPaperId(Long paperId){
        List<LearnQuestions> questions = learnQuestionsMapper.selectQuestionByPaperId(paperId);
        fillQuestionInfo(questions,false);
        return questions;
    }

    @Override
    public void fillQuestionInfo(List<LearnQuestions> list,Boolean isFillTitleOption) {
        String value = configService.selectConfigByKey("file_pre");
        if(StringUtils.isBlank(value)) {
            value = "https://file.mingxue100.com/tikubao/";
        }
        if(StringUtils.isBlank(value)) {
            value = "https://file.mingxuejinbang.com/tikubao/";
        }
        List<LearnQuestions> res = list;
        List<Long> questionIds = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(res)) {
            for(LearnQuestions questions: res) {
                if (StringUtils.isNotEmpty(questions.getTitle())) {
                    questions.setTitle(replaceImagePath(questions.getTitle(), value));
                }
                if (StringUtils.isNotBlank(questions.getOptionA())) {
                    questions.setOptionA(replaceImagePath(questions.getOptionA(), value));
                }
                if (StringUtils.isNotBlank(questions.getOptionB())) {
                    questions.setOptionB(replaceImagePath(questions.getOptionB(), value));
                }
                if (StringUtils.isNotBlank(questions.getOptionC())) {
                    questions.setOptionC(replaceImagePath(questions.getOptionC(), value));
                }
                if (StringUtils.isNotBlank(questions.getOptionD())) {
                    questions.setOptionD(replaceImagePath(questions.getOptionD(), value));
                }
                if (StringUtils.isNotBlank(questions.getOptionE())) {
                    questions.setOptionE(replaceImagePath(questions.getOptionE(), value));
                }
                if(StringUtils.isNotBlank(questions.getAnswer1())) {
                    questions.setAnswer1(replaceImagePath(questions.getAnswer1(), value));
                }
                if(StringUtils.isNotBlank(questions.getAnswer2())) {
                    questions.setAnswer2(replaceImagePath(questions.getAnswer2(), value));
                }
                if(StringUtils.isNotBlank(questions.getParse())) {
                    questions.setParse(replaceImagePath(questions.getParse(), value));
                }
                if(null!=questions.getIsSub()&&questions.getIsSub()==1){
                    questionIds.add(questions.getId());
                }
            }

            for(LearnQuestions question : res) {
                String title = question.getTitle();
                if (null!=isFillTitleOption&&isFillTitleOption){
                    if(StringUtils.isNotBlank(question .getOptionA())) {
                        String option = replaceImagePath(question.getOptionA(), value);
                        title = title + "<br/>A." + option;
                    }
                    if(StringUtils.isNotBlank(question .getOptionB())) {
                        String option = replaceImagePath(question.getOptionB(), value);
                        title = title + "<br/>B." + option;
                    }
                    if(StringUtils.isNotBlank(question .getOptionC())) {
                        String option = replaceImagePath(question.getOptionC(), value);
                        title = title + "<br/>C." + option;
                    }
                    if(StringUtils.isNotBlank(question .getOptionD())) {
                        String option = replaceImagePath(question.getOptionD(), value);
                        title = title + "<br/>D." + option;
                    }
                    if(StringUtils.isNotBlank(question .getOptionE())) {
                        String option = replaceImagePath(question.getOptionE(), value);
                        title = title + "<br/>E." + option;
                    }
                }

                question.setTitle(title);
            }
        }
    }

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

            return replaceImagePath(content, value);
        }
        return content;
    }

    public List<LearnQuestions> selectLearnQuestionsByIds(Long[] ids){
        List<LearnQuestions> questions = learnQuestionsMapper.selectLearnQuestionsByIds(ids);
        fillQuestionInfo(questions,false);
        return questions;
    }

    @Override
    public List<LearnQuestions> statByKnowledgeType(Map cond) {
        List<LearnQuestions> questions = learnQuestionsMapper.statByKnowledgeType(cond);
        fillQuestionInfo(questions,false);
        return questions;
    }
//
//    @Override
//    public List<LearnQuestions> statByKnowledge(Map cond) {
//        List<LearnQuestions> questions = learnQuestionsMapper.statByKnowledge(cond);
//        fillQuestionInfo(questions,false);
//        return questions;
//    }

//    @Override
//    public List<LearnQuestions> selectCollectInfo(Map<String, Object> map) {
//        List<LearnQuestions> questions = learnQuestionsMapper.selectCollectInfo(map);
//        fillQuestionInfo(questions,false);
//        return questions;
//    }
    @Override
    public List<LearnQuestions> selectQuestionsForPaper(LearnQuestions cond) {
        List<LearnQuestions> questions = learnQuestionsMapper.selectQuestionsForPaper(cond);
        fillQuestionInfo(questions,false);
        return questions;
    }

}
