package com.njcn.gather.tools.report.service.impl;

import com.njcn.gather.tools.report.service.IWordReportService;
import com.njcn.gather.tools.report.util.PlaceholderUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;

/**
 * Word报告生成服务实现类
 *
 * @author hongawen
 * @version 1.0
 * @data 2025/9/5 10:14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WordReportServiceImpl implements IWordReportService {

    @Override
    public InputStream replacePlaceholders(InputStream templateInputStream, Map<String, String> placeholderMap) throws Exception {
        if (templateInputStream == null || placeholderMap == null) {
            throw new IllegalArgumentException("输入参数不能为空");
        }
        log.info("开始执行占位符替换，共有 {} 个占位符", placeholderMap.size());
        
        // 加载 Word 文档
        WordprocessingMLPackage wordPackage = WordprocessingMLPackage.load(templateInputStream);
        MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
        
        // 使用工具类批量替换占位符
        PlaceholderUtil.replaceAllPlaceholders(mainDocumentPart, placeholderMap);
        
        // 将处理后的文档转换为字节数组输入流
        // 注：返回类型必须是 ByteArrayInputStream 或 close() 为空操作的等价流，
        // 以满足 IWordReportService.replacePlaceholders 接口契约
        // （多个调用方未对返回流做 try-with-resources 兜底）。
        // 若需改为依赖文件 / 网络 / 临时文件的真实流，必须先改造所有调用方再合并。
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            wordPackage.save(outputStream);
            byte[] documentBytes = outputStream.toByteArray();
            log.info("占位符替换完成，生成文档大小: {} bytes", documentBytes.length);
            return new ByteArrayInputStream(documentBytes);
        }
    }
}
