package com.custom.webui.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.custom.webui.config.props.ExportProperties;
import com.custom.webui.dto.resp.MessageDTO;
import com.custom.webui.dto.resp.StreamEvent;
import com.custom.webui.entity.Chat;
import com.custom.webui.entity.Message;
import com.custom.webui.exception.BusinessException;
import com.custom.webui.mapper.MessageMapper;
import com.custom.webui.service.ChatExportService;
import com.custom.webui.service.ChatService;
import com.custom.webui.util.ChatPdfWriter;
import com.custom.webui.util.MessageTreeUtil;
import com.custom.webui.util.PdfFontSupport;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdfwriter.compress.CompressParameters;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 会话导出实现。
*
*
导出的是「当前分支」而不是整棵树
* 一个会话因为「重新生成 / 编辑消息」可能存在多条分支,而用户屏幕上同一时刻
* 只看到其中一条。导出的语义是「把我现在看到的这段对话存下来」,
* 所以 TXT / PDF 只走当前活跃分支(与前端 {@code buildPath} 完全一致的规则:
* 从最后一个根节点出发,沿 {@code activeChildId} 前进,缺失时回退到最后一个子节点)。
*
* 但**分支本身就是这个项目的核心能力**,直接丢掉太可惜,
* 因此 JSON 里额外给出 {@code allMessages}(扁平全量,带 parentId)——
* 想看全部内容或做二次处理的人可以用它还原整棵树。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatExportServiceImpl implements ChatExportService {
private static final DateTimeFormatter DATE_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final DateTimeFormatter FILE_STAMP =
DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
/** 文件名里保留的最大字符数(中文文件名过长在部分系统上会被截断甚至失败) */
private static final int MAX_FILENAME_CHARS = 40;
/** Windows / macOS 都不允许出现在文件名里的字符 */
private static final String ILLEGAL_FILENAME_CHARS = "[\\\\/:*?\"<>|\\r\\n\\t]";
private final ChatService chatService;
private final MessageMapper messageMapper;
private final PdfFontSupport pdfFontSupport;
private final ExportProperties properties;
private final ObjectMapper objectMapper;
@Override
public ExportFile export(Long userId, Long chatId, Format format) {
Chat chat = chatService.requireOwnedChat(userId, chatId);
List all = messageMapper.selectList(
Wrappers.lambdaQuery()
.eq(Message::getChatId, chatId)
.orderByAsc(Message::getId));
// 树 → 当前分支。没有任何消息时给出空列表,仍然导出一份带标题的空文档,
// 而不是报错 —— 「导出」是只读操作,没有理由因为对话为空就失败。
List tree = MessageTreeUtil.buildTree(all);
List branch = activeBranch(tree);
String stamp = LocalDateTime.now().format(FILE_STAMP);
String filename = buildFilename(chat, stamp, format);
byte[] data = switch (format) {
case JSON -> toJson(chat, all, branch);
case TXT -> toText(chat, branch).getBytes(StandardCharsets.UTF_8);
case PDF -> toPdf(chat, branch);
};
log.info("导出会话 userId={} chatId={} 格式={} 消息={}/{} 字节={}",
userId, chatId, format, branch.size(), all.size(), data.length);
return new ExportFile(data, filename, format.contentType());
}
// ==================================================================
// 当前分支
// ==================================================================
/**
* 沿活跃分支走出一条线性对话。
*
* 规则与前端 {@code utils/treeBuild.js} 的 {@code buildPath} 保持一致 ——
* 两处必须同源,否则会出现「屏幕上是这样、导出来是那样」的诡异问题:
*
* - 起点取**最后一个**根节点(脏数据下可能有多个根)
* - 每步优先走 {@code activeChildId},它缺失或已失效时回退到最后一个子节点
* - 带步数上限,防止脏数据成环时死循环
*
*/
private List activeBranch(List tree) {
List path = new ArrayList<>();
if (tree == null || tree.isEmpty()) {
return path;
}
MessageDTO current = tree.get(tree.size() - 1);
int guard = 0;
while (current != null && guard++ < 10000) {
path.add(current);
List children = current.getChildren();
if (children == null || children.isEmpty()) {
break;
}
MessageDTO next = null;
if (current.getActiveChildId() != null) {
for (MessageDTO child : children) {
if (child.getId() != null && child.getId().equals(current.getActiveChildId())) {
next = child;
break;
}
}
}
if (next == null) {
next = children.get(children.size() - 1);
}
current = next;
}
return path;
}
// ==================================================================
// JSON
// ==================================================================
private byte[] toJson(Chat chat, List all, List branch) {
Map root = new LinkedHashMap<>();
root.put("exportedAt", LocalDateTime.now().format(DATE_TIME));
root.put("formatVersion", 1);
root.put("source", "custom-webui");
Map chatNode = new LinkedHashMap<>();
chatNode.put("id", chat.getId());
chatNode.put("title", chat.getTitle());
chatNode.put("createdAt", chat.getCreatedAt());
chatNode.put("updatedAt", chat.getUpdatedAt());
chatNode.put("pinned", Boolean.TRUE.equals(chat.getPinned()));
chatNode.put("archived", Boolean.TRUE.equals(chat.getArchived()));
chatNode.put("messageCount", all.size());
root.put("chat", chatNode);
// 当前分支:带引用来源、图片等展示所需的信息
List