package com.cmeeting.util;

import org.apache.poi.xwpf.usermodel.*;
import org.commonmark.node.*;
import org.commonmark.parser.Parser;
import java.io.*;

public class SimpleMarkdownToWord {

    public static void convert(String markdownFile, String outputDocx) throws IOException {
        // 读取Markdown文件
        String content = readFile(markdownFile);

        // 初始化Word文档
        XWPFDocument doc = new XWPFDocument();

        // 解析Markdown并遍历节点
        Parser parser = Parser.builder().build();
        Node rootNode = parser.parse(content);
        rootNode.accept(new AbstractVisitor() {
            XWPFParagraph currentPara;

            @Override
            public void visit(Heading heading) {
                // 创建标题段落
                currentPara = doc.createParagraph();
                XWPFRun run = currentPara.createRun();
                run.setText(extractText(heading));  // 提取纯文本
                setHeadingStyle(run, heading.getLevel()); // 设置标题样式
            }

            @Override
            public void visit(Paragraph paragraph) {
                // 创建普通段落
                currentPara = doc.createParagraph();
                XWPFRun run = currentPara.createRun();
                run.setText(extractText(paragraph)); // 提取纯文本
            }
        });

        // 输出Word文件
        try (FileOutputStream out = new FileOutputStream(outputDocx)) {
            doc.write(out);
        }
    }

    // 从节点中提取纯文本（忽略格式）
    private static String extractText(Node node) {
        StringBuilder text = new StringBuilder();
        Node child = node.getFirstChild();
        while (child != null) {
            if (child instanceof Text) {
                text.append(((Text) child).getLiteral());
            }
            child = child.getNext();
        }
        return text.toString().trim();
    }

    // 设置标题样式（仅调整字号和加粗）
    private static void setHeadingStyle(XWPFRun run, int level) {
        run.setBold(true);
        switch (level) {
            case 1: run.setFontSize(20); break;
            case 2: run.setFontSize(18); break;
            default: run.setFontSize(16); break;
        }
    }

    // 读取文件工具方法
    private static String readFile(String path) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        }
        return sb.toString();
    }

    // 测试
    public static void main(String[] args) throws IOException {
        convert("input.md", "output.docx");
        System.out.println("转换完成！");
    }
}
