package com.guo.learningprogresstracker.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.guo.learningprogresstracker.dto.MindMapReportContext; import com.guo.learningprogresstracker.dto.RecallCompareOutcome; import com.guo.learningprogresstracker.dto.ReviewTiming; import com.guo.learningprogresstracker.entity.*; import com.guo.learningprogresstracker.enums.ReviewScopeTypeEnum; import com.guo.learningprogresstracker.exception.NotFindEntitiesException; import com.guo.learningprogresstracker.exception.OperationFailedException; import com.guo.learningprogresstracker.mapper.*; import com.guo.learningprogresstracker.service.StandardMindMapService; import com.guo.learningprogresstracker.utils.CompareResult; import com.guo.learningprogresstracker.utils.MindMapNode; import com.guo.learningprogresstracker.utils.MindMapTreeTool; import com.guo.learningprogresstracker.utils.ReviewDurationTool; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; /** * 标准思维导图服务实现 */ @Slf4j @Service @RequiredArgsConstructor public class StandardMindMapServiceImpl implements StandardMindMapService { private final ReviewStandardMindMapMapper standardMindMapMapper; private final ReviewRecallRecordMapper recallRecordMapper; private final TasksMapper tasksMapper; private final TaskApplicationMapper taskApplicationMapper; private final StudyReportFragmentsMapper studyReportFragmentsMapper; private final MindMapOutlineGenerator outlineGenerator; private final MindMapReportContextLoader reportContextLoader; private final ObjectMapper objectMapper; private final AiServiceClient aiServiceClient; private static final String GENERATOR_BUILTIN = "BUILTIN"; private static final String GENERATOR_USER = "USER"; private static final String GENERATOR_USER_MERGE = "USER_MERGE"; private static final String MATCH_STATUS_MATCHED = "MATCHED"; private static final String MATCH_STATUS_MISSED = "MISSED"; // ============ 查询与生成 ============ @Override public ReviewStandardMindMapEntity getExisting(String taskNum) throws NotFindEntitiesException { ensureTaskExists(taskNum); return queryByTaskNum(taskNum); } @Override public ReviewStandardMindMapEntity regenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException { ensureTaskExists(taskNum); // 并发生成由 ai_tasks 的进行中任务判定拦截(AI-04),不再依赖 JVM 内存锁 return doGenerate(taskNum); } @Override public ReviewStandardMindMapEntity incrementalGenerate(String taskNum) throws NotFindEntitiesException, OperationFailedException { ensureTaskExists(taskNum); ReviewStandardMindMapEntity existing = queryByTaskNum(taskNum); if (existing == null) { log.warn("任务[{}]标准思维导图尚不存在,无法增量更新", taskNum); throw new NotFindEntitiesException("还没有生成过标准思维导图,请先完整生成一次哦"); } // 生成(可能调用 AI)不放在事务里:等待 AI 期间不应占用数据库连接(AI-01) ReviewStandardMindMapEntity fresh = doGenerate(taskNum); // 合并新旧树:保留用户编辑过的节点,追加新节点 MindMapNode oldRoot = MindMapTreeTool.fromJson(existing.getContent(), objectMapper); MindMapNode newRoot = MindMapTreeTool.fromJson(fresh.getContent(), objectMapper); MindMapNode merged = MindMapTreeTool.mergeTrees(oldRoot, newRoot); existing.setContent(MindMapTreeTool.toJson(merged, objectMapper)); existing.setOutline(MindMapTreeTool.toFullOutline(merged)); existing.setTitle(merged.getTitle() != null ? merged.getTitle() : "思维导图"); existing.setGenerator(GENERATOR_USER_MERGE); existing.setGeneratorVersion(fresh.getGeneratorVersion()); existing.setSummary("增量更新,共 " + MindMapTreeTool.countNodes(merged) + " 个节点"); existing.setGeneratedTime(LocalDateTime.now()); standardMindMapMapper.updateById(existing); return existing; } @Override @Transactional public ReviewStandardMindMapEntity updateByOutline(String taskNum, String outline) throws NotFindEntitiesException { ensureTaskExists(taskNum); ReviewStandardMindMapEntity existing = queryByTaskNum(taskNum); if (existing == null) { existing = new ReviewStandardMindMapEntity(); existing.setTaskNum(taskNum); } // 解析大纲为树节点 MindMapNode root = MindMapTreeTool.parseOutline(outline); String contentJson = MindMapTreeTool.toJson(root, objectMapper); existing.setTitle(root.getTitle() != null ? root.getTitle() : "思维导图"); existing.setContent(contentJson); existing.setOutline(outline); existing.setGenerator(GENERATOR_USER); existing.setGeneratorVersion(null); existing.setSummary("用户编辑,共 " + MindMapTreeTool.countNodes(root) + " 个节点"); existing.setGeneratedTime(LocalDateTime.now()); if (existing.getId() == null) { standardMindMapMapper.insert(existing); } else { standardMindMapMapper.updateById(existing); } return existing; } // ============ 回忆对比 ============ @Override public RecallCompareOutcome recallCompare(String taskNum, String recallOutline, String focusPath, ReviewTiming timing) throws NotFindEntitiesException, OperationFailedException { ensureTaskExists(taskNum); // 1. 取标准导图;缺失时按需生成(可能调用 AI,故整个方法不持有事务) ReviewStandardMindMapEntity standard = queryByTaskNum(taskNum); if (standard == null) { standard = doGenerate(taskNum); } // 2. 解析标准树(用户回忆大纲在对比入口里解析,两条复习范围共用同一段逻辑) MindMapNode standardRoot = MindMapTreeTool.fromJson(standard.getContent(), objectMapper); // 2b. 若指定了起点节点路径,提取该子树作为对比基准 MindMapNode compareRoot = standardRoot; if (focusPath != null && !focusPath.isBlank()) { compareRoot = MindMapTreeTool.extractSubtree(standardRoot, focusPath); if (compareRoot == null) { log.warn("focusPath 未匹配到节点,使用全量标准导图: path={}", focusPath); compareRoot = standardRoot; } } // 3. 执行对比(优先 AI 语义对比,失败时降级为内置算法)——与标签导图共用同一套对比口径 CompareResult result = compareWithRecall(resolveScopeName(taskNum), compareRoot, recallOutline); // 4. 序列化对比结果 String resultJson; try { resultJson = objectMapper.writeValueAsString(result); } catch (Exception e) { log.error("任务[{}]对比结果序列化失败", taskNum, e); throw new OperationFailedException("对比结果解析失败了,请稍后再试"); } // 5. 保存回忆记录 ReviewRecallRecordEntity record = new ReviewRecallRecordEntity(); record.setTaskNum(taskNum); // 任务范围的复习范围列:任务导图;标签范围的行由标签导图服务自己写 record.setScopeType(ReviewScopeTypeEnum.TASK.name()); record.setStandardMapId(standard.getId()); record.setFocusPath(focusPath != null && !focusPath.isBlank() ? focusPath : null); record.setRecallContent(recallOutline); record.setCompareResult(resultJson); record.setRecallRatio(result.getRecallRatio()); record.setMatchedCount(result.getMatchedCount()); record.setMissedCount(result.getMissedCount()); record.setExtraCount(result.getExtraCount()); record.setReviewDurationSeconds(ReviewDurationTool.resolveSeconds( timing == null ? null : timing.startedAt(), timing == null ? null : timing.lastInteractionAt(), timing == null ? null : timing.durationSeconds(), LocalDateTime.now())); recallRecordMapper.insert(record); log.info("回忆对比: taskNum={}, recallRatio={}, matched={}, missed={}, extra={}, 复习耗时={}秒", taskNum, result.getRecallRatio(), result.getMatchedCount(), result.getMissedCount(), result.getExtraCount(), record.getReviewDurationSeconds()); return new RecallCompareOutcome(standard.getId(), record.getId(), result.getRecallRatio(), result.getMatchedCount(), result.getMissedCount(), result.getExtraCount()); } // ============ 节点查找 ============ @Override public Map findNode(String taskNum, String content) throws NotFindEntitiesException, OperationFailedException { ensureTaskExists(taskNum); ReviewStandardMindMapEntity standard = queryByTaskNum(taskNum); if (standard == null) { // 还没有标准导图时无从匹配;由调用方决定是否先发起生成任务 Map empty = new LinkedHashMap<>(); empty.put("path", ""); empty.put("nodeTitle", ""); empty.put("score", 0.0); return empty; } MindMapNode root = MindMapTreeTool.fromJson(standard.getContent(), objectMapper); MindMapNode closest = MindMapTreeTool.findClosestNode(root, content); Map result = new LinkedHashMap<>(); if (closest != null) { String path = MindMapTreeTool.getPath(root, closest.getTitle()); result.put("path", path); result.put("nodeTitle", closest.getTitle()); result.put("score", MindMapTreeTool.similarityScore(closest.getTitle(), content)); } else { result.put("path", ""); result.put("nodeTitle", ""); result.put("score", 0.0); } return result; } @Override public CompareResult compareWithRecall(String scopeName, MindMapNode standardRoot, String recallOutline) { MindMapNode recallRoot = MindMapTreeTool.parseOutline(recallOutline); // 优先 AI 语义对比,AI 不可用或返回失败时降级为内置文本相似度匹配 if (aiServiceClient.isConfigured()) { var optJson = aiServiceClient.compareRecall( scopeName, MindMapTreeTool.toFullOutline(standardRoot), recallOutline); if (optJson.isPresent()) { CompareResult result = buildCompareResultFromAI(optJson.get(), standardRoot); log.info("AI 回忆对比: scope={}, recallRatio={}, evaluation={}", scopeName, result.getRecallRatio(), result.getEvaluation() != null ? result.getEvaluation().substring(0, Math.min(50, result.getEvaluation().length())) : ""); return result; } } return compareTrees(standardRoot, recallRoot); } /** 对比口径里的范围名:默认用任务名(导图根节点也是它) */ private String resolveScopeName(String taskNum) { TaskEntity task = tasksMapper.selectOne(Wrappers.lambdaQuery() .eq(TaskEntity::getTaskNum, taskNum).last("LIMIT 1")); return task == null || !StringUtils.hasText(task.getTaskName()) ? taskNum : task.getTaskName(); } // ============ 对比算法核心 ============ /** * 两颗树的节点级对比算法。 */ CompareResult compareTrees(MindMapNode standardRoot, MindMapNode recallRoot) { CompareResult result = new CompareResult(); // 展平标准树 List standardFlat = MindMapTreeTool.flatten(standardRoot); // 展平回忆树(排除根节点本身) List recallFlat = MindMapTreeTool.flatten(recallRoot).stream() .filter(n -> n != recallRoot) .collect(Collectors.toList()); // 构建回忆节点标题 → 节点映射(标准化后) Map recallTitleMap = new LinkedHashMap<>(); for (MindMapNode node : recallFlat) { recallTitleMap.merge(normalize(node.getTitle()), node, (a, b) -> a); } // 标注标准树 int matched = 0, missed = 0; for (MindMapNode node : standardFlat) { if (node == standardRoot) continue; // 跳过根节点 String key = normalize(node.getTitle()); boolean found = recallTitleMap.containsKey(key); if (found) { node.setNotes(MATCH_STATUS_MATCHED + "|" + (node.getNotes() != null ? node.getNotes() : "")); matched++; } else { // 尝试模糊匹配 found = fuzzyMatch(node.getTitle(), recallTitleMap); if (found) { node.setNotes(MATCH_STATUS_MATCHED + "|" + (node.getNotes() != null ? node.getNotes() : "")); matched++; } else { node.setNotes(MATCH_STATUS_MISSED + "|" + (node.getNotes() != null ? node.getNotes() : "")); missed++; } } } // 找出额外节点(用户在回忆中新增的、标准树中没有的) Set standardNormTitles = standardFlat.stream() .map(n -> normalize(n.getTitle())) .collect(Collectors.toSet()); List extraNodes = new ArrayList<>(); for (MindMapNode node : recallFlat) { String key = normalize(node.getTitle()); if (!standardNormTitles.contains(key)) { CompareResult.FlatNode flat = new CompareResult.FlatNode(); flat.setTitle(node.getTitle()); flat.setPath(node.getTitle()); // 简化路径 extraNodes.add(flat); } } int total = matched + missed; result.setMatchedTree(standardRoot); result.setExtraNodes(extraNodes); result.setMatchedCount(matched); result.setMissedCount(missed); result.setExtraCount(extraNodes.size()); result.setRecallRatio(total > 0 ? (double) matched / total : 0); return result; } /** * 从 AI 返回的平铺匹配列表构建 CompareResult,并将 MATCHED/MISSED 标注回标准树。 *

AI 只输出哪些节点匹配/遗漏,树结构标注由本方法确定性完成,避免 LLM 输出不可靠的嵌套 JSON。

*/ private CompareResult buildCompareResultFromAI(JsonNode aiJson, MindMapNode standardRoot) { CompareResult result = new CompareResult(); // 1. 读取 AI 返回的匹配对 → 构建 standardNorm → matchFlag Set matchedStandardTitles = new HashSet<>(); JsonNode matchesArr = aiJson.path("matches"); if (matchesArr.isArray()) { for (JsonNode m : matchesArr) { String stdTitle = m.path("standardTitle").asText(null); if (stdTitle != null) { matchedStandardTitles.add(normalize(stdTitle)); } } } // 2. 读取遗漏列表 Set missedTitles = new HashSet<>(); JsonNode missedArr = aiJson.path("missedTitles"); if (missedArr.isArray()) { for (JsonNode t : missedArr) { String title = t.asText(null); if (title != null) missedTitles.add(normalize(title)); } } // 3. 标注标准树的每个非根节点 List standardFlat = MindMapTreeTool.flatten(standardRoot); int matched = 0, missed = 0; for (MindMapNode node : standardFlat) { if (node == standardRoot) continue; String key = normalize(node.getTitle()); if (matchedStandardTitles.contains(key)) { node.setNotes(MATCH_STATUS_MATCHED + "|" + (node.getNotes() != null ? node.getNotes() : "")); matched++; } else { node.setNotes(MATCH_STATUS_MISSED + "|" + (node.getNotes() != null ? node.getNotes() : "")); missed++; } } // 4. 读取 extraNodes(兼容字符串数组和对象数组两种格式) List extras = new ArrayList<>(); JsonNode extrasArr = aiJson.path("extraNodes"); if (extrasArr.isArray()) { for (JsonNode e : extrasArr) { CompareResult.FlatNode fn = new CompareResult.FlatNode(); if (e.isTextual()) { // 字符串格式 ["知识点D1", "知识点D2"] fn.setTitle(e.asText("")); fn.setPath(""); } else { // 对象格式 [{ title: "...", path: "..." }] fn.setTitle(e.path("title").asText("")); fn.setPath(e.path("path").asText("")); } extras.add(fn); } } // 5. 组装结果 result.setMatchedTree(standardRoot); result.setExtraNodes(extras); result.setMatchedCount(matched); result.setMissedCount(missed); result.setExtraCount(extras.size()); int total = matched + missed; result.setRecallRatio(total > 0 ? (double) matched / total : 0); result.setEvaluation(aiJson.path("evaluation").asText(null)); return result; } // ============ 回忆记录查询 ============ @Override public List listRecallRecords(String taskNum) throws NotFindEntitiesException { ensureTaskExists(taskNum); return recallRecordMapper.selectList( Wrappers.lambdaQuery() .eq(ReviewRecallRecordEntity::getTaskNum, taskNum) .orderByDesc(ReviewRecallRecordEntity::getCreatedTime)); } @Override public ReviewRecallRecordEntity getRecallRecord(Integer recordId) throws NotFindEntitiesException { return Optional.ofNullable(recallRecordMapper.selectById(recordId)) .orElseThrow(() -> { log.warn("回忆记录[{}]不存在", recordId); return new NotFindEntitiesException("这条回忆记录不存在或已被删除"); }); } // ============ 内部方法 ============ private ReviewStandardMindMapEntity doGenerate(String taskNum) throws OperationFailedException { TaskEntity task = tasksMapper.selectOne( Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum).last("LIMIT 1")); if (task == null) { log.warn("任务[{}]不存在,无法生成思维导图", taskNum); throw new OperationFailedException("这个任务不存在或已被删除"); } // 素材按**内容归属**取:该任务名下的知识碎片(归属-01)。 // 不再按「任务的会话里的报告」取,否则学 A 时记录的旁支知识会错误地进入 A 的导图。 List fragments = studyReportFragmentsMapper.selectList( Wrappers.lambdaQuery() .eq(StudyReportFragmentsEntity::getOwnerTaskNum, taskNum) .orderByAsc(StudyReportFragmentsEntity::getCreatedTime)); List applications = taskApplicationMapper.selectList( Wrappers.lambdaQuery().eq(TaskApplicationEntity::getTaskNum, taskNum)); if (fragments.isEmpty()) { log.warn("任务[{}]没有归属到它的知识碎片,无法生成思维导图", taskNum); throw new OperationFailedException("这个任务还没开始学习哦,学习后产生知识碎片后再来吧"); } // 「碎片 → 缩进大纲」生成链路(AI 优先、内置规则降级)与标签导图共用同一套口径; // 报告-02:把碎片同源会话的报告作为参考上下文带上,让 AI 提取总结里由碎片拼接出的新定义/观点 List reports = reportContextLoader.load(fragments); MindMapOutlineGenerator.GeneratedOutline generated = outlineGenerator.generate(task, fragments, applications, reports); MindMapNode root = generated.root(); String contentJson = MindMapTreeTool.toJson(root, objectMapper); String outline = MindMapTreeTool.toFullOutline(root); int nodeCount = MindMapTreeTool.countNodes(root); int depth = MindMapTreeTool.maxDepth(root); ReviewStandardMindMapEntity entity = queryByTaskNum(taskNum); boolean create = entity == null; if (create) { entity = new ReviewStandardMindMapEntity(); entity.setTaskNum(taskNum); } entity.setTitle(root.getTitle() != null ? root.getTitle() : "思维导图"); entity.setContent(contentJson); entity.setOutline(outline); entity.setSummary("共 " + nodeCount + " 个节点,最大层级 " + depth); entity.setGenerator(generated.generatorName()); entity.setGeneratorVersion("1.0"); entity.setSourceReportCount(0); entity.setSourceFragmentCount(fragments.size()); entity.setGeneratedTime(LocalDateTime.now()); // 重建完成后清除「待更新」标记 entity.setNeedsUpdate(false); entity.setNeedsUpdateTime(null); if (create) { standardMindMapMapper.insert(entity); } else { standardMindMapMapper.updateById(entity); } return entity; } private void ensureTaskExists(String taskNum) throws NotFindEntitiesException { if (!StringUtils.hasText(taskNum) || !tasksMapper.exists( Wrappers.lambdaQuery().eq(TaskEntity::getTaskNum, taskNum))) { log.warn("任务[{}]不存在", taskNum); throw new NotFindEntitiesException("这个任务不存在或已被删除"); } } private ReviewStandardMindMapEntity queryByTaskNum(String taskNum) { return standardMindMapMapper.selectOne( Wrappers.lambdaQuery() .eq(ReviewStandardMindMapEntity::getTaskNum, taskNum) .last("LIMIT 1")); } // ============ 标题归一化 ============ /** * 标准化标题用于对比:去空格、去标点、转小写。 */ static String normalize(String s) { if (s == null) return ""; // 先移除内部对比标记前缀,再清理标点 String result = s.replaceAll("^(?:MATCHED|MISSED)\\|", ""); result = result.replaceAll("[\\s 、,。!?:;()\\[\\]{},.!?:;()\\-—/\\\\|]", ""); return result.toLowerCase(Locale.ROOT).trim(); } /** * 模糊匹配:计算字符 bigram Jaccard 相似度 */ static boolean fuzzyMatch(String title, Map recallTitleMap) { if (title == null || title.isBlank()) return false; String norm = normalize(title); Set bigrams = bigramSet(norm); if (bigrams.isEmpty()) return false; for (String recallKey : recallTitleMap.keySet()) { Set recallBigrams = bigramSet(recallKey); if (recallBigrams.isEmpty()) continue; // Jaccard Set intersection = new HashSet<>(bigrams); intersection.retainAll(recallBigrams); Set union = new HashSet<>(bigrams); union.addAll(recallBigrams); double similarity = (double) intersection.size() / union.size(); if (similarity >= 0.6) { return true; } } return false; } static Set bigramSet(String s) { Set set = new HashSet<>(); for (int i = 0; i < s.length() - 1; i++) { set.add(s.substring(i, i + 2)); } return set; } }