package top.tqx.demo_1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tqx.demo_1.common.PageResult;
import top.tqx.demo_1.dto.*;
import top.tqx.demo_1.entity.File;
import top.tqx.demo_1.entity.Question;
import top.tqx.demo_1.entity.UserAnswer;
import top.tqx.demo_1.entity.WrongQuestionCollection;
import top.tqx.demo_1.mapper.FileMapper;
import top.tqx.demo_1.mapper.QuestionMapper;
import top.tqx.demo_1.mapper.UserAnswerMapper;
import top.tqx.demo_1.mapper.WrongQuestionCollectionMapper;
import top.tqx.demo_1.service.UserAnswerService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserAnswerServiceImpl implements UserAnswerService {

    @Autowired
    private UserAnswerMapper userAnswerMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private WrongQuestionCollectionMapper wrongQuestionCollectionMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean saveAnswer(UserAnswer userAnswer) {
        try {
            int result = userAnswerMapper.insert(userAnswer);
            if (result > 0) {
                log.info("用户答题记录保存成功: userId={}, questionId={}",
                        userAnswer.getUserId(), userAnswer.getQuestionId());
                return true;
            }
            log.warn("用户答题记录保存失败: userId={}, questionId={}",
                    userAnswer.getUserId(), userAnswer.getQuestionId());
            return false;
        } catch (Exception e) {
            log.error("用户答题记录保存异常: userId={}, questionId={}, error={}",
                    userAnswer.getUserId(), userAnswer.getQuestionId(), e.getMessage(), e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveAnswers(List<UserAnswer> userAnswers) {
        if (CollectionUtils.isEmpty(userAnswers)) {
            return;
        }
        
        log.info("开始批量保存答题记录: count={}", userAnswers.size());
        
        for (UserAnswer ua : userAnswers) {
            // 先检查是否已存在该答题记录
            UserAnswer existing = userAnswerMapper.selectOne(
                new LambdaQueryWrapper<UserAnswer>()
                    .eq(UserAnswer::getUserId, ua.getUserId())
                    .eq(UserAnswer::getQuestionId, ua.getQuestionId())
                    .eq(UserAnswer::getPaperId, ua.getPaperId())
                    .eq(UserAnswer::getAnswerType, ua.getAnswerType()));
            
            if (existing != null) {
                // 如果是正式考试，不能重复答题
                if ("formal_exam".equals(ua.getAnswerType())) {
                    throw new RuntimeException("正式考试题目已答题，不能重复答题");
                }
                // 如果是模拟考或日常练习，更新答题记录
                ua.setId(existing.getId());
                ua.setCreatedAt(existing.getCreatedAt()); // 保持创建时间
                userAnswerMapper.updateById(ua);
            } else {
                // 不存在则插入新记录
                userAnswerMapper.insert(ua);
            }
        }
        
        log.info("批量保存答题记录完成: count={}", userAnswers.size());
    }

    @Override
    public UserAnswerQueryResponse queryUserAnswers(UserAnswerQueryRequest request) {
        UserAnswerQueryResponse response = new UserAnswerQueryResponse();
        response.setSuccess(true);
        response.setGroups(new ArrayList<>());
        response.setTotalCount(0);

        LambdaQueryWrapper<UserAnswer> queryWrapper = new LambdaQueryWrapper<>();

        if (request.getUserId() != null) {
            queryWrapper.eq(UserAnswer::getUserId, request.getUserId());
        }

        if (request.getPaperId() != null && !request.getPaperId().isEmpty()) {
            queryWrapper.eq(UserAnswer::getPaperId, request.getPaperId());
        } else if (request.getSessionId() != null && !request.getSessionId().isEmpty()) {
            queryWrapper.eq(UserAnswer::getSessionId, request.getSessionId());
        }

        List<UserAnswer> userAnswers = userAnswerMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(userAnswers)) {
            log.info("未找到答题记录: paperId={}, sessionId={}, userId={}",
                    request.getPaperId(), request.getSessionId(), request.getUserId());
            return response;
        }

        Map<String, List<UserAnswer>> groupedAnswers;
        String groupType;

        if (request.getPaperId() != null && !request.getPaperId().isEmpty()) {
            groupedAnswers = userAnswers.stream()
                    .collect(Collectors.groupingBy(a -> a.getPaperId() != null ? a.getPaperId() : "unknown"));
            groupType = "exam";
        } else {
            groupedAnswers = userAnswers.stream()
                    .collect(Collectors.groupingBy(a -> a.getSessionId() != null ? a.getSessionId() : "unknown"));
            groupType = "practice";
        }

        Map<String, Question> questionMap = loadQuestions(userAnswers);
        Map<String, File> fileMap = loadFiles(questionMap.values());

        for (Map.Entry<String, List<UserAnswer>> entry : groupedAnswers.entrySet()) {
            String groupId = entry.getKey();
            List<UserAnswer> answers = entry.getValue();

            UserAnswerQueryResponse.AnswerGroup group = new UserAnswerQueryResponse.AnswerGroup();
            group.setGroupType(groupType);
            group.setGroupId(groupId);
            group.setGroupName(buildGroupName(groupType, groupId));
            group.setCreatedAt(findEarliestCreatedAt(answers));

            List<UserAnswerQueryResponse.AnswerDetail> answerDetails = new ArrayList<>();
            BigDecimal totalScore = BigDecimal.ZERO;
            BigDecimal totalMaxScore = BigDecimal.ZERO;
            int correctCount = 0;

            for (UserAnswer answer : answers) {
                UserAnswerQueryResponse.AnswerDetail detail = buildAnswerDetail(answer, questionMap, fileMap);
                answerDetails.add(detail);

                if (answer.getScore() != null) {
                    totalScore = totalScore.add(answer.getScore());
                }
                if (answer.getMaxScore() != null) {
                    totalMaxScore = totalMaxScore.add(answer.getMaxScore());
                }
                if (answer.getIsCorrect() != null && answer.getIsCorrect() == 1) {
                    correctCount++;
                }
            }

            group.setAnswers(answerDetails);
            group.setAnswerCount(answerDetails.size());
            group.setCorrectCount(correctCount);
            group.setTotalScore(totalScore);
            group.setTotalMaxScore(totalMaxScore);

            if (totalMaxScore.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal scoreRate = totalScore.multiply(BigDecimal.valueOf(100))
                        .divide(totalMaxScore, 2, RoundingMode.HALF_UP);
                group.setScoreRate(scoreRate);
            } else {
                group.setScoreRate(BigDecimal.ZERO);
            }

            response.getGroups().add(group);
        }

        response.setTotalCount(userAnswers.size());
        log.info("查询答题记录成功: totalCount={}, groups={}", response.getTotalCount(), response.getGroups().size());

        return response;
    }

    private Map<String, Question> loadQuestions(List<UserAnswer> answers) {
        Set<String> questionIds = answers.stream()
                .map(UserAnswer::getQuestionId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        if (CollectionUtils.isEmpty(questionIds)) {
            return Collections.emptyMap();
        }

        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Question::getQuestionId, questionIds);
        List<Question> questions = questionMapper.selectList(queryWrapper);

        return questions.stream()
                .collect(Collectors.toMap(Question::getQuestionId, q -> q));
    }

    private Map<String, File> loadFiles(Collection<Question> questions) {
        Set<String> filePaths = questions.stream()
                .map(Question::getKnowledgeBasePath)
                .filter(p -> p != null && !p.isEmpty())
                .collect(Collectors.toSet());

        if (CollectionUtils.isEmpty(filePaths)) {
            return Collections.emptyMap();
        }

        LambdaQueryWrapper<File> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(File::getFilePath, filePaths);
        List<File> files = fileMapper.selectList(queryWrapper);

        return files.stream()
                .collect(Collectors.toMap(File::getFilePath, f -> f));
    }

    private UserAnswerQueryResponse.AnswerDetail buildAnswerDetail(
            UserAnswer answer, Map<String, Question> questionMap, Map<String, File> fileMap) {

        UserAnswerQueryResponse.AnswerDetail detail = new UserAnswerQueryResponse.AnswerDetail();
        detail.setAnswerId(answer.getId());
        detail.setQuestionId(answer.getQuestionId());
        detail.setQuestionType(answer.getQuestionType());
        detail.setQuestionTypeName(mapQuestionTypeName(answer.getQuestionType()));
        detail.setScore(answer.getScore());
        detail.setMaxScore(answer.getMaxScore());
        detail.setIsCorrect(answer.getIsCorrect());
        detail.setIsCorrectText(mapIsCorrectText(answer.getIsCorrect()));
        detail.setFeedback(answer.getFeedback());
        detail.setGradingType(answer.getGradingType());
        detail.setTimeSpent(answer.getTimeSpent());
        detail.setAnsweredAt(answer.getCreatedAt());

        if (answer.getUserAnswer() != null) {
            try {
                detail.setUserAnswer(objectMapper.treeToValue(answer.getUserAnswer(), Object.class));
            } catch (Exception e) {
                log.warn("解析用户答案失败: {}", e.getMessage());
            }
        }

        Question question = questionMap.get(answer.getQuestionId());
        if (question != null) {
            detail.setKnowledgeBasePath(question.getKnowledgeBasePath());

            if (question.getChunkIds() != null && !question.getChunkIds().isNull()) {
                try {
                    List<String> chunkIds = objectMapper.convertValue(
                            question.getChunkIds(), new TypeReference<List<String>>() {});
                    detail.setChunkIds(chunkIds);
                } catch (Exception e) {
                    log.warn("解析chunk_ids失败: {}", e.getMessage());
                }
            }

            if (question.getPageNumbers() != null && !question.getPageNumbers().isNull()) {
                try {
                    List<Integer> pageNumbers = objectMapper.convertValue(
                            question.getPageNumbers(), new TypeReference<List<Integer>>() {});
                    detail.setPageNumbers(pageNumbers);
                } catch (Exception e) {
                    log.warn("解析page_numbers失败: {}", e.getMessage());
                }
            }

            File file = fileMap.get(question.getKnowledgeBasePath());
            if (file != null) {
                detail.setDocumentName(file.getFileName());
            }
        }

        return detail;
    }

    private String mapQuestionTypeName(String questionType) {
        if (questionType == null) {
            return "未知";
        }
        return switch (questionType) {
            case "single_choice" -> "单选题";
            case "multiple_choice" -> "多选题";
            case "true_false" -> "判断题";
            case "fill_blank" -> "填空题";
            case "subjective" -> "简答题";
            default -> questionType;
        };
    }

    private String mapIsCorrectText(Integer isCorrect) {
        if (isCorrect == null) {
            return "未批改";
        }
        return switch (isCorrect) {
            case 0 -> "错误";
            case 1 -> "正确";
            case 2 -> "部分正确";
            default -> "未知";
        };
    }

    private String buildGroupName(String groupType, String groupId) {
        if ("exam".equals(groupType)) {
            return "试卷 - " + groupId;
        } else {
            return "练习 - " + groupId;
        }
    }

    private LocalDateTime findEarliestCreatedAt(List<UserAnswer> answers) {
        return answers.stream()
                .map(UserAnswer::getCreatedAt)
                .filter(Objects::nonNull)
                .min(LocalDateTime::compareTo)
                .orElse(null);
    }

    @Override
    public WrongQuestionListResponse getWrongQuestions(Long userId, WrongQuestionListRequest request) {
        WrongQuestionListResponse response = new WrongQuestionListResponse();

        LambdaQueryWrapper<UserAnswer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAnswer::getUserId, userId);
        queryWrapper.and(wrapper -> wrapper.eq(UserAnswer::getIsCorrect, 0).or().eq(UserAnswer::getIsCorrect, 2));

        if (request.getQuestionType() != null && !request.getQuestionType().isEmpty()) {
            queryWrapper.eq(UserAnswer::getQuestionType, request.getQuestionType());
        }

        if (request.getStartTime() != null) {
            queryWrapper.ge(UserAnswer::getCreatedAt, request.getStartTime());
        }

        if (request.getEndTime() != null) {
            queryWrapper.le(UserAnswer::getCreatedAt, request.getEndTime());
        }

        if (request.getKnowledgeBasePath() != null && !request.getKnowledgeBasePath().isEmpty()) {
            Set<String> questionIds = getQuestionIdsByKnowledgeBasePath(request.getKnowledgeBasePath());
            if (questionIds.isEmpty()) {
                response.setPage(new PageResult<WrongQuestionListResponse.WrongQuestionItem>(new ArrayList<>(), 0L, request.getPage().longValue(), request.getPageSize().longValue()));
                response.setStats(new WrongQuestionListResponse.WrongQuestionStats());
                return response;
            }
            queryWrapper.in(UserAnswer::getQuestionId, questionIds);
        }

        queryWrapper.orderByDesc(UserAnswer::getCreatedAt);

        Page<UserAnswer> page = new Page<>(request.getPage(), request.getPageSize());
        IPage<UserAnswer> iPage = userAnswerMapper.selectPage(page, queryWrapper);

        List<UserAnswer> wrongAnswers = iPage.getRecords();
        List<WrongQuestionListResponse.WrongQuestionItem> items = new ArrayList<>();

        Map<String, Question> questionMap = loadQuestions(wrongAnswers);
        Map<String, File> fileMap = loadFiles(questionMap.values());
        Set<Long> collectedAnswerIds = getCollectedAnswerIds(userId);
        Map<String, Long> wrongCountMap = getWrongCountMap(userId);

        for (UserAnswer answer : wrongAnswers) {
            WrongQuestionListResponse.WrongQuestionItem item = buildWrongQuestionItem(
                    answer, questionMap, fileMap, collectedAnswerIds, wrongCountMap);
            items.add(item);
        }

        if (request.getIsCollected() != null) {
            if (request.getIsCollected()) {
                items = items.stream().filter(WrongQuestionListResponse.WrongQuestionItem::getIsCollected).collect(Collectors.toList());
            } else {
                items = items.stream().filter(item -> !item.getIsCollected()).collect(Collectors.toList());
            }
        }

        PageResult<WrongQuestionListResponse.WrongQuestionItem> pageResult = new PageResult<>(
                items, iPage.getTotal(), request.getPage().longValue(), request.getPageSize().longValue());
        response.setPage(pageResult);
        response.setStats(calculateStats(userId));

        log.info("查询错题列表成功: userId={}, total={}", userId, iPage.getTotal());
        return response;
    }

    @Override
    @Transactional
    public boolean toggleWrongQuestionCollection(Long userId, WrongQuestionCollectRequest request) {
        // 修复查询逻辑：分别处理answerId和questionId
        LambdaQueryWrapper<WrongQuestionCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WrongQuestionCollection::getUserId, userId);
        
        if (request.getAnswerId() != null) {
            queryWrapper.eq(WrongQuestionCollection::getAnswerId, request.getAnswerId());
            // 如果同时有questionId，也添加条件
            if (request.getQuestionId() != null) {
                queryWrapper.eq(WrongQuestionCollection::getQuestionId, request.getQuestionId());
            }
        } else if (request.getQuestionId() != null) {
            // 仅通过questionId查询
            queryWrapper.eq(WrongQuestionCollection::getQuestionId, request.getQuestionId());
        } else {
            return false;
        }

        WrongQuestionCollection existing = wrongQuestionCollectionMapper.selectOne(queryWrapper);

        if (Boolean.TRUE.equals(request.getIsCollected())) {
            if (existing != null) {
                // 已存在，更新备注
                existing.setNote(request.getNote());
                existing.setUpdatedAt(LocalDateTime.now());
                return wrongQuestionCollectionMapper.updateById(existing) > 0;
            } else {
                // 不存在，新增收藏
                WrongQuestionCollection collection = new WrongQuestionCollection();
                collection.setUserId(userId);
                collection.setAnswerId(request.getAnswerId());
                collection.setQuestionId(request.getQuestionId());
                collection.setNote(request.getNote());
                collection.setCreatedAt(LocalDateTime.now());
                collection.setUpdatedAt(LocalDateTime.now());
                return wrongQuestionCollectionMapper.insert(collection) > 0;
            }
        } else {
            // 取消收藏
            if (existing != null) {
                return wrongQuestionCollectionMapper.deleteById(existing.getId()) > 0;
            }
            return true; // 不存在也算成功
        }
    }

    @Override
    public ExamPaperGenerateResponse redoWrongQuestions(Long userId, WrongQuestionRedoRequest request) {
        ExamPaperGenerateResponse response = new ExamPaperGenerateResponse();

        List<UserAnswer> wrongAnswers;
        if (request.getAnswerIds() != null && !request.getAnswerIds().isEmpty()) {
            LambdaQueryWrapper<UserAnswer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserAnswer::getUserId, userId);
            queryWrapper.in(UserAnswer::getId, request.getAnswerIds());
            wrongAnswers = userAnswerMapper.selectList(queryWrapper);
        } else {
            LambdaQueryWrapper<UserAnswer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserAnswer::getUserId, userId);
            queryWrapper.and(wrapper -> wrapper.eq(UserAnswer::getIsCorrect, 0).or().eq(UserAnswer::getIsCorrect, 2));
            
            if (request.getQuestionType() != null && !request.getQuestionType().isEmpty()) {
                queryWrapper.eq(UserAnswer::getQuestionType, request.getQuestionType());
            }

            if (Boolean.TRUE.equals(request.getIsCollected())) {
                Set<Long> collectedAnswerIds = getCollectedAnswerIds(userId);
                if (!collectedAnswerIds.isEmpty()) {
                    queryWrapper.in(UserAnswer::getId, collectedAnswerIds);
                }
            }

            queryWrapper.orderByDesc(UserAnswer::getCreatedAt);
            wrongAnswers = userAnswerMapper.selectList(queryWrapper);
        }

        Set<String> usedQuestionIds = new HashSet<>();
        List<ExamPaperGenerateResponse.ExamPaperQuestion> questions = new ArrayList<>();

        int count = 0;
        for (UserAnswer answer : wrongAnswers) {
            if (count >= request.getQuestionCount()) break;
            if (usedQuestionIds.contains(answer.getQuestionId())) continue;

            Question question = questionMapper.selectOne(
                    new LambdaQueryWrapper<Question>()
                            .eq(Question::getQuestionId, answer.getQuestionId())
            );

            if (question != null) {
                ExamPaperGenerateResponse.ExamPaperQuestion examQuestion = new ExamPaperGenerateResponse.ExamPaperQuestion();
                examQuestion.setQuestionId(question.getQuestionId());
                examQuestion.setQuestionType(question.getQuestionType());
                examQuestion.setQuestionTypeName(mapQuestionTypeName(question.getQuestionType()));
                examQuestion.setDifficulty(question.getDifficulty());
                examQuestion.setScore(question.getScore());
                examQuestion.setContent(question.getContent());
                examQuestion.setDocumentName(question.getDocumentName());
                examQuestion.setKnowledgeBasePath(question.getKnowledgeBasePath());
                questions.add(examQuestion);
                usedQuestionIds.add(answer.getQuestionId());
                count++;
            }
        }

        response.setPaperId("WRONG_REDO_" + System.currentTimeMillis());
        response.setPaperTitle("错题重练 - " + LocalDateTime.now().toString());
        response.setQuestions(questions);
        response.setQuestionCount(questions.size());
        response.setTotalScore(questions.stream()
                .map(ExamPaperGenerateResponse.ExamPaperQuestion::getScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        response.setGeneratedAt(LocalDateTime.now());

        log.info("生成错题重练试卷成功: userId={}, questionCount={}", userId, questions.size());
        return response;
    }

    @Override
    public List<WrongQuestionListResponse.WrongQuestionItem> exportWrongQuestions(Long userId, WrongQuestionListRequest request) {
        request.setPage(1);
        request.setPageSize(10000);
        WrongQuestionListResponse response = getWrongQuestions(userId, request);
        return response.getPage().getRecords();
    }

    @Override
    public boolean checkQuestionCollected(Long userId, String questionId) {
        if (userId == null || questionId == null || questionId.isEmpty()) {
            return false;
        }
        
        LambdaQueryWrapper<WrongQuestionCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WrongQuestionCollection::getUserId, userId);
        queryWrapper.eq(WrongQuestionCollection::getQuestionId, questionId);
        
        Long count = wrongQuestionCollectionMapper.selectCount(queryWrapper);
        return count > 0;
    }

    private WrongQuestionListResponse.WrongQuestionItem buildWrongQuestionItem(
            UserAnswer answer, Map<String, Question> questionMap,
            Map<String, File> fileMap, Set<Long> collectedAnswerIds,
            Map<String, Long> wrongCountMap) {

        WrongQuestionListResponse.WrongQuestionItem item = new WrongQuestionListResponse.WrongQuestionItem();
        item.setAnswerId(answer.getId());
        item.setQuestionId(answer.getQuestionId());
        item.setQuestionType(answer.getQuestionType());
        item.setQuestionTypeName(mapQuestionTypeName(answer.getQuestionType()));
        item.setScore(answer.getScore());
        item.setMaxScore(answer.getMaxScore());
        item.setFeedback(answer.getFeedback());
        item.setAnsweredAt(answer.getCreatedAt());
        // 通过answerId判断是否收藏
        item.setIsCollected(collectedAnswerIds.contains(answer.getId()));
        item.setWrongCount(wrongCountMap.getOrDefault(answer.getQuestionId(), 1L).intValue());

        if (answer.getUserAnswer() != null) {
            try {
                item.setUserAnswer(objectMapper.treeToValue(answer.getUserAnswer(), Object.class));
            } catch (Exception e) {
                log.warn("解析用户答案失败: {}", e.getMessage());
            }
        }

        Question question = questionMap.get(answer.getQuestionId());
        if (question != null) {
            item.setQuestionContent(question.getContent());
            item.setDifficulty(question.getDifficulty());
            item.setKnowledgeBasePath(question.getKnowledgeBasePath());

            if (question.getContent() != null) {
                try {
                    JsonNode contentNode = question.getContent();
                    if (contentNode.has("answer")) {
                        item.setCorrectAnswer(contentNode.get("answer"));
                    } else if (contentNode.has("correctAnswer")) {
                        item.setCorrectAnswer(contentNode.get("correctAnswer"));
                    }
                } catch (Exception e) {
                    log.warn("解析正确答案失败: {}", e.getMessage());
                }
            }

            if (question.getTags() != null && !question.getTags().isNull()) {
                try {
                    List<String> tags = objectMapper.convertValue(
                            question.getTags(), new TypeReference<List<String>>() {});
                    item.setTags(tags);
                } catch (Exception e) {
                    log.warn("解析tags失败: {}", e.getMessage());
                }
            }

            File file = fileMap.get(question.getKnowledgeBasePath());
            if (file != null) {
                item.setDocumentName(file.getFileName());
            }
        }

        return item;
    }

    private WrongQuestionListResponse.WrongQuestionStats calculateStats(Long userId) {
        WrongQuestionListResponse.WrongQuestionStats stats = new WrongQuestionListResponse.WrongQuestionStats();

        LambdaQueryWrapper<UserAnswer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAnswer::getUserId, userId);
        queryWrapper.and(wrapper -> wrapper.eq(UserAnswer::getIsCorrect, 0).or().eq(UserAnswer::getIsCorrect, 2));
        List<UserAnswer> allWrongAnswers = userAnswerMapper.selectList(queryWrapper);

        int singleChoiceCount = 0, multipleChoiceCount = 0, trueFalseCount = 0;
        int fillBlankCount = 0, subjectiveCount = 0;

        for (UserAnswer answer : allWrongAnswers) {
            switch (answer.getQuestionType()) {
                case "single_choice" -> singleChoiceCount++;
                case "multiple_choice" -> multipleChoiceCount++;
                case "true_false" -> trueFalseCount++;
                case "fill_blank" -> fillBlankCount++;
                case "subjective" -> subjectiveCount++;
            }
        }

        stats.setTotalWrongCount(allWrongAnswers.size());
        stats.setSingleChoiceCount(singleChoiceCount);
        stats.setMultipleChoiceCount(multipleChoiceCount);
        stats.setTrueFalseCount(trueFalseCount);
        stats.setFillBlankCount(fillBlankCount);
        stats.setSubjectiveCount(subjectiveCount);

        LambdaQueryWrapper<WrongQuestionCollection> collectionWrapper = new LambdaQueryWrapper<>();
        collectionWrapper.eq(WrongQuestionCollection::getUserId, userId);
        stats.setCollectedCount(Math.toIntExact(wrongQuestionCollectionMapper.selectCount(collectionWrapper)));

        return stats;
    }

    private Set<Long> getCollectedAnswerIds(Long userId) {
        LambdaQueryWrapper<WrongQuestionCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WrongQuestionCollection::getUserId, userId);
        queryWrapper.isNotNull(WrongQuestionCollection::getAnswerId);
        List<WrongQuestionCollection> collections = wrongQuestionCollectionMapper.selectList(queryWrapper);
        return collections.stream()
                .map(WrongQuestionCollection::getAnswerId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
    }

    // 新增：获取收藏的questionId集合
    private Set<String> getCollectedQuestionIds(Long userId) {
        LambdaQueryWrapper<WrongQuestionCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WrongQuestionCollection::getUserId, userId);
        queryWrapper.isNotNull(WrongQuestionCollection::getQuestionId);
        List<WrongQuestionCollection> collections = wrongQuestionCollectionMapper.selectList(queryWrapper);
        return collections.stream()
                .map(WrongQuestionCollection::getQuestionId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
    }

    private Map<String, Long> getWrongCountMap(Long userId) {
        LambdaQueryWrapper<UserAnswer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAnswer::getUserId, userId);
        queryWrapper.and(wrapper -> wrapper.eq(UserAnswer::getIsCorrect, 0).or().eq(UserAnswer::getIsCorrect, 2));
        List<UserAnswer> wrongAnswers = userAnswerMapper.selectList(queryWrapper);

        return wrongAnswers.stream()
                .collect(Collectors.groupingBy(
                        UserAnswer::getQuestionId,
                        Collectors.counting()
                ));
    }

    private Set<String> getQuestionIdsByKnowledgeBasePath(String knowledgeBasePath) {
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Question::getKnowledgeBasePath, knowledgeBasePath);
        List<Question> questions = questionMapper.selectList(queryWrapper);
        return questions.stream()
                .map(Question::getQuestionId)
                .collect(Collectors.toSet());
    }
}
