kongdeqiang
2026-10-12 7c687dd3c8fba9f7632f5e29d94a708e5f497abd
fix: 新增分组
13个文件已添加
1500 ■■■■■ 已修改文件
src/main/java/com/custom/webui/config/props/ExportProperties.java 45 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/controller/ChatGroupController.java 67 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/dto/req/ChatGroupMoveRequest.java 19 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/dto/req/ChatGroupRequest.java 14 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/dto/resp/ChatGroupDTO.java 22 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/entity/ChatGroup.java 29 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/mapper/ChatGroupMapper.java 8 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/service/ChatExportService.java 66 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/service/ChatGroupService.java 38 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/service/impl/ChatExportServiceImpl.java 408 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/service/impl/ChatGroupServiceImpl.java 157 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/util/ChatPdfWriter.java 300 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/util/PdfFontSupport.java 327 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/config/props/ExportProperties.java
New file
@@ -0,0 +1,45 @@
package com.custom.webui.config.props;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
 * 会话导出配置,前缀 {@code webui.export}。
 */
@Data
@ConfigurationProperties(prefix = "webui.export")
public class ExportProperties {
    /**
     * PDF 中文字体文件路径,留空时按内置候选列表自动探测。
     *
     * <p><b>为什么需要它</b>:PDF 里的中文必须靠**嵌入字体**才能保证任何阅读器
     * 都能正确显示。PDF 内置的 14 个标准字体(Helvetica 等)只覆盖 Latin-1,
     * 中文写进去会直接抛 {@code IllegalArgumentException: No glyph for U+4E2D};
     * 而使用不嵌入的「标准 CJK 字体」(如 STSong-Light + UniGB-UCS2-H)
     * 虽然不用带字体文件,但 macOS 预览等阅读器未必装了对应字体,
     * 打开就是一片空白或乱码 —— 导出的文件是给用户长期保存的,
     * 不能赌对方机器上装了什么。
     *
     * <p>所以默认自动探测系统里现成的中文字体(macOS 的 Arial Unicode、
     * Linux 的 Noto CJK、Windows 的微软雅黑等)。探测失败不会让程序起不来,
     * 只是 PDF 导出会返回一条带操作指引的错误,TXT / JSON 导出不受影响。
     */
    private String pdfFontPath = "";
    /**
     * 单次导出最多包含的消息条数。
     *
     * <p>防止一条超长对话生成几十兆的 PDF 把内存和响应时间拖垮;
     * 超出时会截断并在文件末尾写明「已截断」。
     */
    private int maxMessages = 2000;
    /**
     * 单条消息正文进入导出文件的字符上限。
     *
     * <p>比 maxMessages 更常见的失控来源其实是**单条**超长消息
     * (比如把一整篇文档粘进对话)。
     */
    private int maxCharsPerMessage = 20000;
}
src/main/java/com/custom/webui/controller/ChatGroupController.java
New file
@@ -0,0 +1,67 @@
package com.custom.webui.controller;
import com.custom.webui.dto.req.ChatGroupRequest;
import com.custom.webui.dto.resp.ChatGroupDTO;
import com.custom.webui.dto.resp.Result;
import com.custom.webui.security.CurrentUser;
import com.custom.webui.service.ChatGroupService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * 对话分组接口,对应侧边栏「分组」区块里的增删改。
 *
 * <p>把会话放进去 / 拿出来不在这里,而在
 * {@code PUT /api/chats/{id}/group} —— 分组是会话的属性,
 * 从会话那一侧改更自然,也避免这个控制器要依赖会话服务。
 */
@RestController
@RequestMapping("/api/chat-groups")
@RequiredArgsConstructor
public class ChatGroupController {
    private final ChatGroupService chatGroupService;
    /** 当前用户的全部分组 */
    @GetMapping
    public Result<List<ChatGroupDTO>> list() {
        return Result.success(chatGroupService.listByUser(CurrentUser.requireUserId()));
    }
    /** 新建分组 */
    @PostMapping
    public Result<ChatGroupDTO> create(@Valid @RequestBody ChatGroupRequest request) {
        return Result.success(chatGroupService.create(CurrentUser.requireUserId(), request));
    }
    /** 重命名分组 */
    @PutMapping("/{id}")
    public Result<ChatGroupDTO> rename(@PathVariable Long id,
                                       @Valid @RequestBody ChatGroupRequest request) {
        return Result.success(chatGroupService.rename(CurrentUser.requireUserId(), id, request));
    }
    /**
     * 删除分组。
     *
     * <p>返回 {@code movedChats}(被移出分组、回到未分组的会话数),
     * 让前端能明确告诉用户「分组删了,里面的 3 条对话已回到未分组」——
     * 只说「已删除」会让人担心对话是否也一起没了。
     */
    @DeleteMapping("/{id}")
    public Result<Map<String, Object>> delete(@PathVariable Long id) {
        int moved = chatGroupService.delete(CurrentUser.requireUserId(), id);
        return Result.success(Map.of("movedChats", moved));
    }
}
src/main/java/com/custom/webui/dto/req/ChatGroupMoveRequest.java
New file
@@ -0,0 +1,19 @@
package com.custom.webui.dto.req;
import lombok.Data;
/**
 * 把会话移入 / 移出分组的请求体。
 *
 * <p><b>为什么单独一个端点,而不是复用 {@code PUT /api/chats/{id}}</b>:
 * 会话更新接口约定「字段为 null 表示不修改」,而「移出分组」恰恰就是要把
 * groupId 置为 null —— 两种语义在同一个字段上无法区分。
 * 用一个专门的端点、body 里 {@code groupId: null} 明确表示「移出分组」,
 * 就不会有歧义。
 */
@Data
public class ChatGroupMoveRequest {
    /** 目标分组 id;null = 移出分组(回到未分组,继续按时间归类) */
    private Long groupId;
}
src/main/java/com/custom/webui/dto/req/ChatGroupRequest.java
New file
@@ -0,0 +1,14 @@
package com.custom.webui.dto.req;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/** 新建 / 重命名分组的请求体。 */
@Data
public class ChatGroupRequest {
    @NotBlank(message = "分组名不能为空")
    @Size(max = 64, message = "分组名过长(最多 64 字)")
    private String name;
}
src/main/java/com/custom/webui/dto/resp/ChatGroupDTO.java
New file
@@ -0,0 +1,22 @@
package com.custom.webui.dto.resp;
import lombok.Data;
/**
 * 对话分组返回体。
 */
@Data
public class ChatGroupDTO {
    private Long id;
    private String name;
    /**
     * 该分组下的会话数(不含已归档的)。
     *
     * <p>归档的会话不在主列表里显示,自然也不该算进分组的数字里,
     * 否则用户会看到「分组里有 3 条」但点开只有 1 条。
     */
    private Long chatCount;
}
src/main/java/com/custom/webui/entity/ChatGroup.java
New file
@@ -0,0 +1,29 @@
package com.custom.webui.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
 * 对话分组实体,对应表 {@code chat_group}。
 *
 * <p>这是**用户自建**的文件夹,与侧边栏里的「今天 / 昨天 / 更早」
 * 自动时间分组是两回事:时间分组是只读的视图归类,分组是可命名、可增删的。
 */
@Data
@TableName("chat_group")
public class ChatGroup {
    @TableId(type = IdType.AUTO)
    private Long id;
    /** 所属用户 id,所有查询必须带上该条件做数据隔离 */
    private Long userId;
    private String name;
    private LocalDateTime createdAt;
}
src/main/java/com/custom/webui/mapper/ChatGroupMapper.java
New file
@@ -0,0 +1,8 @@
package com.custom.webui.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.custom.webui.entity.ChatGroup;
/** 对话分组 Mapper。 */
public interface ChatGroupMapper extends BaseMapper<ChatGroup> {
}
src/main/java/com/custom/webui/service/ChatExportService.java
New file
@@ -0,0 +1,66 @@
package com.custom.webui.service;
import com.custom.webui.exception.BusinessException;
/**
 * 会话导出服务:把一个对话导出成 JSON / TXT / PDF。
 *
 * <p>三者的定位不同,不是同一份内容换三种后缀:
 * <ul>
 *   <li><b>JSON</b> —— 给程序用的。除当前显示的分支外,还带上扁平的全量消息
 *       (含 parentId),因此**分支结构不会丢**,可以完整还原消息树。</li>
 *   <li><b>TXT</b> —— 给人看的纯文本,随便什么工具都能打开、能 grep。</li>
 *   <li><b>PDF</b> —— 用于归档、打印、发给别人。中文字体按子集嵌入,
 *       在任何阅读器里都能正确显示。</li>
 * </ul>
 */
public interface ChatExportService {
    /** 导出格式 */
    enum Format {
        JSON, TXT, PDF;
        /** 解析格式参数,不认识的值直接报错而不是悄悄按默认值处理 */
        public static Format parse(String raw) {
            if (raw == null || raw.isBlank()) {
                return TXT;
            }
            for (Format f : values()) {
                if (f.name().equalsIgnoreCase(raw.trim())) {
                    return f;
                }
            }
            throw BusinessException.badRequest(
                    "不支持的导出格式:" + raw + "(可选 json / txt / pdf)");
        }
        public String extension() {
            return name().toLowerCase();
        }
        public String contentType() {
            return switch (this) {
                case JSON -> "application/json;charset=UTF-8";
                case TXT -> "text/plain;charset=UTF-8";
                case PDF -> "application/pdf";
            };
        }
    }
    /**
     * 导出结果。
     *
     * @param data        文件字节
     * @param filename    建议的文件名(已做非法字符清洗)
     * @param contentType MIME 类型
     */
    record ExportFile(byte[] data, String filename, String contentType) {
    }
    /**
     * 导出一个会话。
     *
     * @throws com.custom.webui.exception.BusinessException 会话不存在或不属于该用户(404)
     */
    ExportFile export(Long userId, Long chatId, Format format);
}
src/main/java/com/custom/webui/service/ChatGroupService.java
New file
@@ -0,0 +1,38 @@
package com.custom.webui.service;
import com.custom.webui.dto.req.ChatGroupRequest;
import com.custom.webui.dto.resp.ChatGroupDTO;
import com.custom.webui.entity.ChatGroup;
import java.util.List;
/**
 * 对话分组服务(用户自建的文件夹)。
 *
 * <p><b>数据隔离约定</b>:所有方法都必须接收 {@code userId} 并在查询条件里带上,
 * 与 {@link ChatService} 一致。分组与收藏夹类似,越权读取他人分组名同样属于信息泄露。
 */
public interface ChatGroupService {
    /** 当前用户的全部分组,按创建顺序(新建的排在后面) */
    List<ChatGroupDTO> listByUser(Long userId);
    /** 新建分组,同名时返回 400 而不是数据库唯一键错误 */
    ChatGroupDTO create(Long userId, ChatGroupRequest request);
    /** 重命名分组 */
    ChatGroupDTO rename(Long userId, Long groupId, ChatGroupRequest request);
    /**
     * 删除分组。
     *
     * <p><b>不会删除组内会话</b>:只把它们的 group_id 置空,回到「未分组」
     * 继续按时间归类。分组只是整理手段,删一个文件夹不该连带毁掉里面的内容。
     *
     * @return 被移出分组的会话数,用于给用户一个明确提示
     */
    int delete(Long userId, Long groupId);
    /** 校验分组归属;不属于该用户时抛 404(而非 403,避免探测他人分组是否存在) */
    ChatGroup requireOwnedGroup(Long userId, Long groupId);
}
src/main/java/com/custom/webui/service/impl/ChatExportServiceImpl.java
New file
@@ -0,0 +1,408 @@
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;
/**
 * 会话导出实现。
 *
 * <h2>导出的是「当前分支」而不是整棵树</h2>
 * 一个会话因为「重新生成 / 编辑消息」可能存在多条分支,而用户屏幕上同一时刻
 * 只看到其中一条。导出的语义是「把我现在看到的这段对话存下来」,
 * 所以 TXT / PDF 只走当前活跃分支(与前端 {@code buildPath} 完全一致的规则:
 * 从最后一个根节点出发,沿 {@code activeChildId} 前进,缺失时回退到最后一个子节点)。
 *
 * <p>但**分支本身就是这个项目的核心能力**,直接丢掉太可惜,
 * 因此 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<Message> all = messageMapper.selectList(
                Wrappers.<Message>lambdaQuery()
                        .eq(Message::getChatId, chatId)
                        .orderByAsc(Message::getId));
        // 树 → 当前分支。没有任何消息时给出空列表,仍然导出一份带标题的空文档,
        // 而不是报错 —— 「导出」是只读操作,没有理由因为对话为空就失败。
        List<MessageDTO> tree = MessageTreeUtil.buildTree(all);
        List<MessageDTO> 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());
    }
    // ==================================================================
    // 当前分支
    // ==================================================================
    /**
     * 沿活跃分支走出一条线性对话。
     *
     * <p>规则与前端 {@code utils/treeBuild.js} 的 {@code buildPath} 保持一致 ——
     * 两处必须同源,否则会出现「屏幕上是这样、导出来是那样」的诡异问题:
     * <ol>
     *   <li>起点取**最后一个**根节点(脏数据下可能有多个根)</li>
     *   <li>每步优先走 {@code activeChildId},它缺失或已失效时回退到最后一个子节点</li>
     *   <li>带步数上限,防止脏数据成环时死循环</li>
     * </ol>
     */
    private List<MessageDTO> activeBranch(List<MessageDTO> tree) {
        List<MessageDTO> 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<MessageDTO> 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<Message> all, List<MessageDTO> branch) {
        Map<String, Object> root = new LinkedHashMap<>();
        root.put("exportedAt", LocalDateTime.now().format(DATE_TIME));
        root.put("formatVersion", 1);
        root.put("source", "custom-webui");
        Map<String, Object> 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<Map<String, Object>> messages = new ArrayList<>();
        for (MessageDTO m : branch) {
            Map<String, Object> node = new LinkedHashMap<>();
            node.put("id", m.getId());
            node.put("parentId", m.getParentId());
            node.put("role", m.getRole());
            node.put("content", m.getContent());
            node.put("model", m.getModel());
            node.put("createdAt", m.getCreatedAt());
            if (m.getSources() != null && !m.getSources().isEmpty()) {
                node.put("sources", m.getSources());
            }
            if (m.getImageFileIds() != null && !m.getImageFileIds().isEmpty()) {
                node.put("imageFileIds", m.getImageFileIds());
            }
            messages.add(node);
        }
        root.put("messages", messages);
        // 扁平全量:含其他分支,parentId 可还原整棵树
        List<Map<String, Object>> flat = new ArrayList<>();
        for (Message m : all) {
            Map<String, Object> node = new LinkedHashMap<>();
            node.put("id", m.getId());
            node.put("parentId", m.getParentId());
            node.put("role", m.getRole());
            node.put("content", m.getContent());
            node.put("model", m.getModel());
            node.put("createdAt", m.getCreatedAt());
            flat.add(node);
        }
        root.put("allMessages", flat);
        root.put("note", "messages 为当前显示的分支;allMessages 为扁平全量(含其他分支),"
                + "用 parentId 可还原完整消息树");
        try {
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsBytes(root);
        } catch (Exception e) {
            throw BusinessException.serverError("生成 JSON 失败:" + e.getMessage());
        }
    }
    // ==================================================================
    // TXT
    // ==================================================================
    private String toText(Chat chat, List<MessageDTO> branch) {
        StringBuilder sb = new StringBuilder(4096);
        sb.append(chat.getTitle() == null ? "新对话" : chat.getTitle()).append('\n');
        sb.append("=".repeat(48)).append('\n');
        sb.append("导出时间:").append(LocalDateTime.now().format(DATE_TIME)).append('\n');
        sb.append("创建时间:").append(formatTime(chat.getCreatedAt())).append('\n');
        sb.append("消息条数:").append(branch.size()).append('\n');
        sb.append('\n');
        if (branch.isEmpty()) {
            sb.append("(这段对话还没有消息)\n");
            return sb.toString();
        }
        // 截断说明单独收集,最后再追加 —— 不能塞进 sb 让它在文档中间冒出来
        StringBuilder truncationNote = new StringBuilder();
        List<MessageDTO> visible = truncateBranch(branch, truncationNote);
        boolean first = true;
        for (MessageDTO m : visible) {
            if (!first) {
                sb.append('\n');
            }
            first = false;
            sb.append('[').append(formatTime(m.getCreatedAt())).append("] ")
                    .append(roleLabel(m)).append('\n');
            sb.append("─".repeat(32)).append('\n');
            sb.append(clip(m.getContent())).append('\n');
            appendExtras(sb, m);
        }
        if (truncationNote.length() > 0) {
            sb.append('\n').append(truncationNote).append('\n');
        }
        return sb.toString();
    }
    // ==================================================================
    // PDF
    // ==================================================================
    private byte[] toPdf(Chat chat, List<MessageDTO> branch) {
        try (PDDocument document = new PDDocument();
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            PDDocumentInformation info = new PDDocumentInformation();
            info.setTitle(chat.getTitle() == null ? "对话" : chat.getTitle());
            info.setProducer("custom-webui");
            document.setDocumentInformation(info);
            // 注意生命周期:embedSubset 是延迟到 save() 才读字体的,
            // 所以 handle 必须活到 save() 之后(见 PdfFontSupport 的类注释)
            try (PdfFontSupport.PdfFontHandle handle = pdfFontSupport.open(document)) {
                ChatPdfWriter writer = new ChatPdfWriter(document, handle);
                writer.writeTitle(chat.getTitle() == null ? "新对话" : chat.getTitle());
                writer.writeMeta("导出时间:" + LocalDateTime.now().format(DATE_TIME)
                        + "    创建时间:" + formatTime(chat.getCreatedAt())
                        + "    消息条数:" + branch.size());
                writer.writeSpacing(6f);
                writer.writeRule();
                if (branch.isEmpty()) {
                    writer.writeSpacing(10f);
                    writer.writeMeta("(这段对话还没有消息)");
                }
                StringBuilder truncationNote = new StringBuilder();
                for (MessageDTO m : truncateBranch(branch, truncationNote)) {
                    writer.writeMessageHeader("[" + formatTime(m.getCreatedAt()) + "] " + roleLabel(m));
                    writer.writeParagraph(clip(m.getContent()));
                    String extras = extrasText(m);
                    if (!extras.isEmpty()) {
                        writer.writeSpacing(2f);
                        writer.writeMeta(extras);
                    }
                    writer.writeSpacing(6f);
                }
                if (truncationNote.length() > 0) {
                    writer.writeSpacing(6f);
                    writer.writeMeta(truncationNote.toString());
                }
                writer.close();
                // 压缩内容流:中文长对话不压缩时体积会明显偏大
                document.save(out, CompressParameters.DEFAULT_COMPRESSION);
            }
            return out.toByteArray();
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("生成 PDF 失败 chatId={}", chat.getId(), e);
            throw BusinessException.serverError("生成 PDF 失败:" + e.getMessage());
        }
    }
    // ==================================================================
    // 公共小工具
    // ==================================================================
    /**
     * 按上限截断分支,并把「截断了」这件事写进 {@code note}。
     *
     * <p>静默截断是不可接受的:用户会以为导出的就是全部内容。
     */
    private List<MessageDTO> truncateBranch(List<MessageDTO> branch, StringBuilder note) {
        int max = properties.getMaxMessages();
        if (max <= 0 || branch.size() <= max) {
            return branch;
        }
        note.append("注意:该对话共 ").append(branch.size())
                .append(" 条消息,已按配置上限只导出前 ").append(max)
                .append(" 条(可调整 webui.export.max-messages)。");
        return branch.subList(0, max);
    }
    private String clip(String content) {
        if (content == null) {
            return "";
        }
        int max = properties.getMaxCharsPerMessage();
        if (max > 0 && content.length() > max) {
            return content.substring(0, max) + "\n…(本条消息过长,已截断 " + (content.length() - max) + " 字)";
        }
        return content;
    }
    /** TXT 里附在消息下方的补充信息:引用来源、图片数量 */
    private void appendExtras(StringBuilder sb, MessageDTO m) {
        String extras = extrasText(m);
        if (!extras.isEmpty()) {
            sb.append(extras).append('\n');
        }
    }
    private String extrasText(MessageDTO m) {
        List<String> parts = new ArrayList<>();
        if (m.getSources() != null && !m.getSources().isEmpty()) {
            List<String> refs = new ArrayList<>();
            int index = 1;
            for (StreamEvent.Source s : m.getSources()) {
                StringBuilder one = new StringBuilder();
                one.append('[').append(index++).append("] ");
                one.append(s.getFilename() == null ? "(未知文件)" : s.getFilename());
                if (s.getSection() != null && !s.getSection().isBlank()) {
                    one.append(" · ").append(s.getSection());
                }
                refs.add(one.toString());
            }
            parts.add("引用来源:" + String.join(";", refs));
        }
        if (m.getImageFileIds() != null && !m.getImageFileIds().isEmpty()) {
            // 导出文件不带图片本体:图片存在服务端,且 PDF 里嵌图会让体积和实现复杂度都陡增。
            // 但必须**明确写出来**,否则用户会以为图片内容被丢掉了。
            parts.add("[本条消息附带 " + m.getImageFileIds().size() + " 张图片,"
                    + "导出文件不含图片本体,可在网页里查看]");
        }
        return String.join("\n", parts);
    }
    private String roleLabel(MessageDTO m) {
        String role = m.getRole() == null ? "" : m.getRole();
        return switch (role) {
            case "user" -> "我";
            case "assistant" -> m.getModel() == null || m.getModel().isBlank()
                    ? "AI" : "AI(" + m.getModel() + ")";
            case "system" -> "系统";
            default -> role;
        };
    }
    private String formatTime(LocalDateTime time) {
        return time == null ? "-" : time.format(DATE_TIME);
    }
    /**
     * 生成下载文件名:{标题}_{时间戳}.{后缀}
     *
     * <p>标题来自用户输入(早期版本甚至是模型生成的),里面完全可能出现
     * {@code /}、{@code :}、换行等字符 —— 直接拼进 Content-Disposition
     * 轻则文件名错乱,重则触发响应头注入,所以必须白名单化清洗。
     */
    private String buildFilename(Chat chat, String stamp, Format format) {
        String title = chat.getTitle() == null ? "" : chat.getTitle().trim();
        title = title.replaceAll(ILLEGAL_FILENAME_CHARS, " ")
                .replaceAll("\\s+", " ")
                .trim();
        if (title.isEmpty()) {
            title = "对话" + chat.getId();
        }
        if (title.length() > MAX_FILENAME_CHARS) {
            title = title.substring(0, MAX_FILENAME_CHARS);
        }
        return title + "_" + stamp + "." + format.extension();
    }
}
src/main/java/com/custom/webui/service/impl/ChatGroupServiceImpl.java
New file
@@ -0,0 +1,157 @@
package com.custom.webui.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.custom.webui.dto.req.ChatGroupRequest;
import com.custom.webui.dto.resp.ChatGroupDTO;
import com.custom.webui.entity.Chat;
import com.custom.webui.entity.ChatGroup;
import com.custom.webui.exception.BusinessException;
import com.custom.webui.mapper.ChatGroupMapper;
import com.custom.webui.mapper.ChatMapper;
import com.custom.webui.service.ChatGroupService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/** 对话分组服务实现。 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatGroupServiceImpl implements ChatGroupService {
    private final ChatGroupMapper chatGroupMapper;
    private final ChatMapper chatMapper;
    @Override
    public List<ChatGroupDTO> listByUser(Long userId) {
        List<ChatGroup> groups = chatGroupMapper.selectList(
                Wrappers.<ChatGroup>lambdaQuery()
                        .eq(ChatGroup::getUserId, userId)
                        .orderByAsc(ChatGroup::getId));
        if (groups.isEmpty()) {
            return Collections.emptyList();
        }
        // 一次聚合出每个分组的会话数,避免逐个分组查一次(N+1)
        Map<Long, Long> countByGroup = chatMapper.selectList(
                        Wrappers.<Chat>lambdaQuery()
                                .select(Chat::getGroupId)
                                .eq(Chat::getUserId, userId)
                                .eq(Chat::getArchived, false)
                                .isNotNull(Chat::getGroupId))
                .stream()
                .collect(Collectors.groupingBy(Chat::getGroupId, Collectors.counting()));
        return groups.stream().map(g -> toDto(g, countByGroup.getOrDefault(g.getId(), 0L))).toList();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChatGroupDTO create(Long userId, ChatGroupRequest request) {
        String name = normalizeName(request.getName());
        requireNameAvailable(userId, name, null);
        ChatGroup group = new ChatGroup();
        group.setUserId(userId);
        group.setName(name);
        group.setCreatedAt(LocalDateTime.now());
        chatGroupMapper.insert(group);
        log.info("新建对话分组 userId={} groupId={} name={}", userId, group.getId(), name);
        return toDto(group, 0L);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChatGroupDTO rename(Long userId, Long groupId, ChatGroupRequest request) {
        requireOwnedGroup(userId, groupId);
        String name = normalizeName(request.getName());
        requireNameAvailable(userId, name, groupId);
        ChatGroup update = new ChatGroup();
        update.setId(groupId);
        update.setName(name);
        chatGroupMapper.updateById(update);
        Long count = chatMapper.selectCount(
                Wrappers.<Chat>lambdaQuery()
                        .eq(Chat::getGroupId, groupId)
                        .eq(Chat::getArchived, false));
        return toDto(chatGroupMapper.selectById(groupId), count);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long userId, Long groupId) {
        requireOwnedGroup(userId, groupId);
        // 只解除关联,**不删会话**:删文件夹不该毁掉里面的东西。
        // 把 group_id 显式置 NULL 用 UpdateWrapper —— 实体的 null 字段
        // 会被 MyBatis-Plus 忽略,表达不了「置空」这个意图。
        int moved = chatMapper.update(null,
                Wrappers.<Chat>lambdaUpdate()
                        .eq(Chat::getGroupId, groupId)
                        .eq(Chat::getUserId, userId)
                        .set(Chat::getGroupId, null));
        chatGroupMapper.deleteById(groupId);
        log.info("删除对话分组 userId={} groupId={},{} 条会话回到未分组", userId, groupId, moved);
        return moved;
    }
    @Override
    public ChatGroup requireOwnedGroup(Long userId, Long groupId) {
        if (groupId == null) {
            throw BusinessException.badRequest("分组 id 不能为空");
        }
        ChatGroup group = chatGroupMapper.selectById(groupId);
        // 不存在与不属于当前用户统一 404:返回 403 等于确认「这个 id 存在」
        if (group == null || !group.getUserId().equals(userId)) {
            throw BusinessException.notFound("分组不存在或无权访问");
        }
        return group;
    }
    // ==================== 内部辅助 ====================
    private String normalizeName(String raw) {
        String name = raw == null ? "" : raw.trim();
        if (name.isEmpty()) {
            throw BusinessException.badRequest("分组名不能为空");
        }
        // 列宽 64,超长直接截断而不是抛数据库异常
        return name.length() > 64 ? name.substring(0, 64) : name;
    }
    /**
     * 检查重名。
     *
     * <p>先查一次是为了给用户一句「已有同名分组」的人话提示;
     * 数据库上的唯一键仍然保留,用于兜住并发插入(两个请求同时通过检查)。
     */
    private void requireNameAvailable(Long userId, String name, Long excludeId) {
        ChatGroup exists = chatGroupMapper.selectOne(
                Wrappers.<ChatGroup>lambdaQuery()
                        .eq(ChatGroup::getUserId, userId)
                        .eq(ChatGroup::getName, name)
                        .last("LIMIT 1"));
        if (exists != null && !exists.getId().equals(excludeId)) {
            throw BusinessException.badRequest("已有同名分组:" + name);
        }
    }
    private ChatGroupDTO toDto(ChatGroup group, Long chatCount) {
        ChatGroupDTO dto = new ChatGroupDTO();
        dto.setId(group.getId());
        dto.setName(group.getName());
        dto.setChatCount(chatCount == null ? 0L : chatCount);
        return dto;
    }
}
src/main/java/com/custom/webui/util/ChatPdfWriter.java
New file
@@ -0,0 +1,300 @@
package com.custom.webui.util;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 极简的 PDF 排版器:把一段段文字按 A4 页面排下来,自动换行、自动翻页、带页码。
 *
 * <h2>为什么不用现成的排版库</h2>
 * openhtmltopdf / iText 这类库都要额外引入依赖,而本项目只需要
 * 「标题 + 元信息 + 若干条消息」这一种版式,自己画反而更可控,
 * 也避免了为导出一个功能背上几 MB 的依赖和许可证问题。
 *
 * <h2>三个必须自己处理的细节</h2>
 * <ol>
 *   <li><b>字形缺失</b>:字体里没有的字符(emoji、罕见符号)直接写进去会抛
 *       {@code IllegalArgumentException: No glyph for U+1F600},
 *       整个导出就失败了。这里统一替换成 {@code □} 并缓存判断结果。</li>
 *   <li><b>换行</b>:中文没有空格,不能按单词断行。这里按**字符**宽度累加,
 *       同时对「不能出现在行首」的标点(,。!?等)做悬挂处理,
 *       避免出现「一行结尾孤零零一个逗号」。</li>
 *   <li><b>页码</b>:内容写完后才知道总页数,所以页码统一在
 *       {@link #close()} 里补画(用 APPEND 模式重新打开每一页)。</li>
 * </ol>
 */
public class ChatPdfWriter implements Closeable {
    private static final float PAGE_WIDTH = PDRectangle.A4.getWidth();
    private static final float PAGE_HEIGHT = PDRectangle.A4.getHeight();
    private static final float MARGIN = 56f;
    private static final float CONTENT_WIDTH = PAGE_WIDTH - MARGIN * 2;
    private static final float CURSOR_TOP = PAGE_HEIGHT - MARGIN;
    private static final float CURSOR_BOTTOM = MARGIN + 12f;
    /** 不允许出现在行首的标点(避头尾规则) */
    private static final String NO_LINE_START = ",。、;:!?)》」』】…—·%℃";
    /** 缺字形时的替代符 */
    private static final char REPLACEMENT = '□';
    private final PDDocument document;
    private final PdfFontSupport.PdfFontHandle handle;
    private final PDType0Font font;
    private final List<PDPage> pages = new ArrayList<>();
    /** 码位 -> 字体里有没有这个字形。判定要走 cmap 查询,缓存一下省时间 */
    private final Map<Integer, Boolean> glyphCache = new HashMap<>();
    private PDPageContentStream stream;
    private float cursorY;
    private boolean finished;
    public ChatPdfWriter(PDDocument document, PdfFontSupport.PdfFontHandle handle) throws IOException {
        this.document = document;
        this.handle = handle;
        this.font = handle.font();
        newPage();
    }
    // ------------------------------------------------------------------
    // 对外的写入接口(按语义命名,比通用的 draw(text, size) 更能防止用错字号)
    // ------------------------------------------------------------------
    /** 文档标题 */
    public void writeTitle(String text) throws IOException {
        for (String line : wrap(text, 16f)) {
            writeLine(line, 16f, 0.11f, 0.11f, 0.13f, 24f);
        }
    }
    /** 元信息行(导出时间、消息数等),小字灰色 */
    public void writeMeta(String text) throws IOException {
        for (String line : wrap(text, 9f)) {
            writeLine(line, 9f, 0.42f, 0.45f, 0.50f, 14f);
        }
    }
    /** 消息头(「我 · 2026-10-09 10:32」这类) */
    public void writeMessageHeader(String text) throws IOException {
        for (String line : wrap(text, 10f)) {
            // 与前一条消息留出间距,靠调用方保证「先 spacing 再 header」不稳妥,
            // 这里统一在消息头之前多留 8pt
            ensureSpace(8f + 16f + 14f);
            cursorY -= 8f;
            writeLine(line, 10f, 0.12f, 0.35f, 0.60f, 16f);
        }
    }
    /** 正文段落,保留原有换行 */
    public void writeParagraph(String text) throws IOException {
        for (String line : wrap(text, 10.5f)) {
            writeLine(line, 10.5f, 0.16f, 0.17f, 0.20f, 15.5f);
        }
    }
    /** 一条分隔线(用于标题与正文之间) */
    public void writeRule() throws IOException {
        ensureSpace(12f);
        stream.setNonStrokingColor(0.80f, 0.82f, 0.85f);
        stream.addRect(MARGIN, cursorY - 4f, CONTENT_WIDTH, 0.8f);
        stream.fill();
        cursorY -= 12f;
    }
    /** 段落之间的空白 */
    public void writeSpacing(float height) throws IOException {
        ensureSpace(height);
        cursorY -= height;
    }
    // ------------------------------------------------------------------
    // 内部实现
    // ------------------------------------------------------------------
    private void writeLine(String text, float size, float r, float g, float b, float lineHeight)
            throws IOException {
        ensureSpace(lineHeight);
        if (!text.isEmpty()) {
            stream.setNonStrokingColor(r, g, b);
            stream.beginText();
            stream.setFont(font, size);
            stream.newLineAtOffset(MARGIN, cursorY - size);
            stream.showText(text);
            stream.endText();
        }
        cursorY -= lineHeight;
    }
    /**
     * 按宽度折行。
     *
     * <p>按**字符**而不是单词断行:中文没有词间空格,按单词断会得到一整段不断行的文本。
     * 同时做两件小事:
     * <ul>
     *   <li>原始文本里的换行/tab 得到保留(tab 展开成 4 个空格)</li>
     *   <li>不让「,。!?」这类标点出现在行首</li>
     * </ul>
     */
    private List<String> wrap(String raw, float size) {
        List<String> lines = new ArrayList<>();
        if (raw == null || raw.isEmpty()) {
            lines.add("");
            return lines;
        }
        for (String paragraph : sanitize(raw).split("\n", -1)) {
            if (paragraph.isEmpty()) {
                lines.add("");
                continue;
            }
            StringBuilder current = new StringBuilder();
            float width = 0f;
            int i = 0;
            while (i < paragraph.length()) {
                int cp = paragraph.codePointAt(i);
                String ch = new String(Character.toChars(cp));
                float chWidth = widthOf(ch, size);
                boolean overflow = width + chWidth > CONTENT_WIDTH && current.length() > 0;
                // 避头尾:不因为标点而断行,宁可让它稍微出界(悬挂标点)
                boolean isNoStart = ch.length() == 1 && NO_LINE_START.indexOf(ch.charAt(0)) >= 0;
                if (overflow && !isNoStart) {
                    lines.add(current.toString());
                    current.setLength(0);
                    width = 0f;
                }
                current.append(ch);
                width += chWidth;
                i += Character.charCount(cp);
            }
            lines.add(current.toString());
        }
        return lines;
    }
    private float widthOf(String text, float size) {
        try {
            return font.getStringWidth(text) / 1000f * size;
        } catch (IOException e) {
            return size;   // 估算即可,不该因为测量失败而中断导出
        }
    }
    /**
     * 清洗文本:控制字符、tab、以及**字体里没有的字符**。
     *
     * <p>字体缺字形这一点是必须处理的:Arial Unicode 这类字体覆盖了中日韩,
     * 但不含 emoji(U+1F600 等)。PDFBox 遇到缺字形会抛异常,
     * 表现就是「对话里有表情符号,整个 PDF 导出就失败」——
     * 一个 emoji 毁掉整份导出,显然不可接受,所以替换成方框继续导。
     *
     * <p>字形判断走字体句柄的 cmap 查询,**不能**用
     * {@code PDType0Font.hasGlyph()}:实测它对本该存在的全角逗号也会返回
     * false,那样中文标点会被整片替换成方框(详见 {@link PdfFontSupport})。
     */
    private String sanitize(String raw) {
        StringBuilder sb = new StringBuilder(raw.length() + 16);
        int i = 0;
        while (i < raw.length()) {
            int cp = raw.codePointAt(i);
            i += Character.charCount(cp);
            if (cp == '\r') {
                continue;
            }
            if (cp == '\t') {
                sb.append("    ");
                continue;
            }
            if (cp != '\n' && Character.isISOControl(cp)) {
                continue;
            }
            if (cp == '\n' || hasGlyph(cp)) {
                sb.appendCodePoint(cp);
            } else {
                sb.append(REPLACEMENT);
            }
        }
        return sb.toString();
    }
    private boolean hasGlyph(int codePoint) {
        Boolean cached = glyphCache.get(codePoint);
        if (cached != null) {
            return cached;
        }
        boolean has = handle.hasGlyph(codePoint);
        glyphCache.put(codePoint, has);
        return has;
    }
    private void ensureSpace(float needed) throws IOException {
        if (cursorY - needed < CURSOR_BOTTOM) {
            newPage();
        }
    }
    private void newPage() throws IOException {
        if (stream != null) {
            stream.close();
        }
        PDPage page = new PDPage(PDRectangle.A4);
        document.addPage(page);
        pages.add(page);
        // compress=true 让内容流走 Flate 压缩;resetContext=true 保证每页图形状态独立
        stream = new PDPageContentStream(document, page,
                PDPageContentStream.AppendMode.APPEND, true, true);
        cursorY = CURSOR_TOP;
    }
    @Override
    public void close() throws IOException {
        if (finished) {
            return;
        }
        finished = true;
        if (stream != null) {
            stream.close();
            stream = null;
        }
        writeFooters();
    }
    /**
     * 补画页码。
     *
     * <p>必须在全部内容写完之后做:页码要落在「第 N 页 / 共 M 页」上,
     * 而 M 只有写到最后才知道。用 APPEND 模式重新打开每一页的内容流即可。
     */
    private void writeFooters() throws IOException {
        int total = pages.size();
        for (int index = 0; index < total; index++) {
            String text = "第 " + (index + 1) + " 页 / 共 " + total + " 页";
            float size = 8f;
            float width = widthOf(text, size);
            try (PDPageContentStream footer = new PDPageContentStream(
                    document, pages.get(index), PDPageContentStream.AppendMode.APPEND, true, true)) {
                footer.setNonStrokingColor(0.62f, 0.65f, 0.70f);
                footer.beginText();
                footer.setFont(font, size);
                footer.newLineAtOffset((PAGE_WIDTH - width) / 2f, MARGIN / 2f);
                footer.showText(text);
                footer.endText();
            }
        }
    }
}
src/main/java/com/custom/webui/util/PdfFontSupport.java
New file
@@ -0,0 +1,327 @@
package com.custom.webui.util;
import com.custom.webui.config.props.ExportProperties;
import com.custom.webui.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.fontbox.ttf.CmapLookup;
import org.apache.fontbox.ttf.TTFParser;
import org.apache.fontbox.ttf.TrueTypeCollection;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.springframework.stereotype.Component;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * 为 PDF 导出准备一份**能写中文**的字体。
 *
 * <h2>为什么必须嵌入字体</h2>
 * PDF 内置的 14 个标准字体(Helvetica / Times 等)只覆盖 Latin-1,
 * 写中文会直接抛 {@code IllegalArgumentException: No glyph for U+4E2D}。
 * 而「引用系统里的 CJK 标准字体」(STSong-Light + UniGB-UCS2-H)虽然省事,
 * 但阅读器不一定装了对应字体 —— 用户拿到的是一个打开就空白或乱码的文件,
 * 而导出文件往往就是用来长期保存和发给别人的,不能赌对方的环境。
 * 所以这里从系统里找一份真实的中文字体,**按子集嵌入**(只带用到的字形,
 * 一个几百字的中文对话最终 PDF 通常只有几十 KB)。
 *
 * <h2>为什么用 cmap 判断字形,而不是 PDType0Font.hasGlyph()</h2>
 * 这是实测踩到的坑:{@code PDType0Font.hasGlyph(',')} 对 Arial Unicode 返回
 * <b>false</b>,而同一份字体的 cmap 里 U+FF0C 明明有字形(glyphId=6632)。
 * 如果信了它,会有两个后果:
 * <ol>
 *   <li>字体选择阶段会把 Arial Unicode 误判成「不含中文」而跳过;</li>
 *   <li>文本清洗阶段会把每个全角逗号都替换成方框 —— 中文回答里满地 □。</li>
 * </ol>
 * 因此这里统一用 fontbox 的 {@link CmapLookup#getGlyphId(int)}
 * (返回 0 才代表真的没有这个字形)。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PdfFontSupport {
    /**
     * 兜底候选字体,按顺序探测。
     *
     * <p>只放**单体**字体文件(.ttf / .otf)与常见的字体集合(.ttc):
     * .ttc 会由 {@link TrueTypeCollection} 逐个挑出含中文字形的那一款。
     */
    private static final List<String> CANDIDATES = List.of(
            // macOS
            "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
            "/Library/Fonts/Arial Unicode.ttf",
            "/System/Library/Fonts/Supplemental/Songti.ttc",
            "/System/Library/Fonts/PingFang.ttc",
            "/System/Library/Fonts/Hiragino Sans GB.ttc",
            // Linux
            "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
            "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
            "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc",
            "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
            "/usr/share/fonts/truetype/arphic/uming.ttc",
            "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
            // Windows
            "C:/Windows/Fonts/msyh.ttc",
            "C:/Windows/Fonts/msyh.ttf",
            "C:/Windows/Fonts/simsun.ttc",
            "C:/Windows/Fonts/simhei.ttf"
    );
    /** 用来判断「这份字体到底认不认识中文」的探针字符 */
    private static final int[] CJK_PROBE = {'中', '文', ',', '。'};
    private final ExportProperties properties;
    private volatile File cachedFont;
    private volatile boolean probed;
    /**
     * 为给定文档打开字体。
     *
     * @throws BusinessException 找不到可用字体时抛出,message 里带具体配置方法
     */
    public PdfFontHandle open(PDDocument document) {
        File file = resolveFontFile();
        if (file == null) {
            throw BusinessException.serverError(
                    "导出 PDF 需要一份中文字体,但系统里没有探测到可用的。"
                            + "请在配置里显式指定:webui.export.pdf-font-path=/path/to/中文字体.ttf"
                            + "(TXT / JSON 导出不受影响)");
        }
        try {
            if (isCollection(file)) {
                TrueTypeCollection collection = new TrueTypeCollection(file);
                TrueTypeFont picked = pickFace(collection);
                if (picked == null) {
                    closeQuietly(collection);
                    throw BusinessException.serverError("字体 " + file
                            + " 里没有找到包含中文字形的字体,请改配 webui.export.pdf-font-path");
                }
                return new PdfFontHandle(PDType0Font.load(document, picked, true),
                        new Closeable[]{collection}, picked.getUnicodeCmapLookup());
            }
            RandomAccessReadBufferedFile raf = new RandomAccessReadBufferedFile(file);
            TrueTypeFont ttf = new TTFParser().parse(raf);
            CmapLookup lookup = ttf.getUnicodeCmapLookup();
            if (lookup == null || !knowsChinese(lookup)) {
                closeQuietly(ttf);
                closeQuietly(raf);
                throw BusinessException.serverError("字体 " + file
                        + " 不含中文字形,请改配 webui.export.pdf-font-path");
            }
            // 注意:子集化发生在 save() 阶段,所以 ttf / raf 必须活到那时,
            // 由 handle 统一关闭(见 PdfFontHandle 的说明)
            return new PdfFontHandle(PDType0Font.load(document, ttf, true),
                    new Closeable[]{ttf, raf}, lookup);
        } catch (BusinessException e) {
            throw e;
        } catch (IOException e) {
            throw BusinessException.serverError("加载 PDF 字体失败:" + file + " —— " + e.getMessage());
        }
    }
    /** 供启动自检展示 */
    public String describe() {
        File file = resolveFontFile();
        if (file == null) {
            return "未找到中文字体 —— PDF 导出不可用(TXT / JSON 仍可用)。"
                    + "可配置 webui.export.pdf-font-path 指定字体文件";
        }
        return "已就绪:" + file;
    }
    // ------------------------------------------------------------------
    // 字体探测
    // ------------------------------------------------------------------
    private File resolveFontFile() {
        if (probed) {
            return cachedFont;
        }
        synchronized (this) {
            if (probed) {
                return cachedFont;
            }
            List<String> paths = new ArrayList<>();
            if (properties.getPdfFontPath() != null && !properties.getPdfFontPath().isBlank()) {
                // 显式配置优先,且**只**用它:用户指定了字体却静默回退到别的字体,
                // 会让人以为配置没生效(本项目已经踩过好几次「配置被静默忽略」的坑)
                paths.add(properties.getPdfFontPath().trim());
            } else {
                paths.addAll(CANDIDATES);
            }
            for (String path : paths) {
                File file = new File(path);
                if (!file.isFile() || file.length() == 0) {
                    continue;
                }
                if (recognizesChinese(file)) {
                    log.info("PDF 导出将使用中文字体: {}", file);
                    cachedFont = file;
                    probed = true;
                    return cachedFont;
                }
                log.debug("字体 {} 存在但不含中文字形,跳过", file);
            }
            log.warn("未找到可用于 PDF 导出的中文字体,PDF 导出将不可用(TXT/JSON 不受影响)");
            probed = true;
            return null;
        }
    }
    /**
     * 从字体集合里挑一款。
     *
     * <p>两轮:先找名字里带 Regular 的(字体集合的第一个 face 往往是 Black / Bold
     * 之类的重字重,导出的正文会粗得没法看),找不到再退回第一个含中文字形的。
     */
    private TrueTypeFont pickFace(TrueTypeCollection collection) throws IOException {
        List<TrueTypeFont> faces = new ArrayList<>();
        collection.processAllFonts(faces::add);
        if (faces.isEmpty()) {
            return null;
        }
        TrueTypeFont regular = null;
        TrueTypeFont fallback = null;
        for (TrueTypeFont face : faces) {
            CmapLookup lookup = face.getUnicodeCmapLookup();
            if (lookup == null || !knowsChinese(lookup)) {
                continue;
            }
            if (fallback == null) {
                fallback = face;
            }
            String name = face.getName();
            if (name != null) {
                String lower = name.toLowerCase();
                if (lower.contains("regular") || lower.contains("light")) {
                    regular = face;
                    break;
                }
            }
        }
        return regular != null ? regular : fallback;
    }
    private boolean recognizesChinese(File file) {
        try {
            if (isCollection(file)) {
                try (TrueTypeCollection collection = new TrueTypeCollection(file)) {
                    return pickFace(collection) != null;
                }
            }
            try (RandomAccessReadBufferedFile raf = new RandomAccessReadBufferedFile(file)) {
                TrueTypeFont ttf = new TTFParser().parse(raf);
                try {
                    CmapLookup lookup = ttf.getUnicodeCmapLookup();
                    return lookup != null && knowsChinese(lookup);
                } finally {
                    closeQuietly(ttf);
                }
            }
        } catch (Exception e) {
            log.debug("字体探测失败 {}: {}", file, e.getMessage());
            return false;
        }
    }
    /** glyphId 为 0 表示 .notdef,即这份字体确实没有该字形 */
    private boolean knowsChinese(CmapLookup lookup) {
        try {
            for (int cp : CJK_PROBE) {
                if (lookup.getGlyphId(cp) == 0) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    private boolean isCollection(File file) {
        return file.getName().toLowerCase().endsWith(".ttc");
    }
    private void closeQuietly(Closeable closeable) {
        try {
            closeable.close();
        } catch (Exception ignored) {
            // 关闭失败不影响主流程
        }
    }
    /**
     * 字体句柄:给出绘图用的 {@code PDType0Font},同时把**底层字体资源**
     * 与**字形判断能力**一起带出来。
     *
     * <p>三样东西缺一不可,所以绑在一个句柄里:
     * <ul>
     *   <li>{@code font} —— 真正往 PDF 里写字的对象</li>
     *   <li>底部资源 —— 用 {@code embedSubset=true} 加载时,PDFBox 是
     *       <b>延迟到 {@code save()}</b> 才去读字体文件裁子集的;
     *       若在此之前关闭了文件句柄,保存时会报「TTF is closed」
     *       这种与导出内容毫不相干的错误</li>
     *   <li>{@code cmap} —— 判断某个字符有没有字形(用来把 emoji 之类的
     *       缺字形字符替换掉,否则一个表情符号就能让整份导出失败)</li>
     * </ul>
     *
     * <p>用法固定为:
     * <pre>
     * try (var handle = fontSupport.open(doc)) {
     *     ... 写内容 ...
     *     doc.save(out);      // 子集化发生在这里,此时字体必须还活着
     * }
     * </pre>
     */
    public static final class PdfFontHandle implements Closeable {
        private final PDType0Font font;
        private final Closeable[] resources;
        private final CmapLookup cmap;
        PdfFontHandle(PDType0Font font, Closeable[] resources, CmapLookup cmap) {
            this.font = font;
            this.resources = resources;
            this.cmap = cmap;
        }
        public PDType0Font font() {
            return font;
        }
        /** 该码位在这份字体里是否有字形(false 时应替换成占位符) */
        public boolean hasGlyph(int codePoint) {
            if (cmap == null) {
                // 拿不到 cmap 时保守地认为「有」,交给 PDFBox 去报错,
                // 也好过把正常文字大量替换成方框
                return true;
            }
            try {
                return cmap.getGlyphId(codePoint) != 0;
            } catch (Exception e) {
                return true;
            }
        }
        @Override
        public void close() throws IOException {
            for (Closeable resource : resources) {
                resource.close();
            }
        }
    }
}