package com.zt.plat.module.base.service.doctemplate.render.export;

import com.zt.plat.module.base.service.doctemplate.DocumentRenderApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.base.enums.ErrorCodeConstants.*;

/**
 * Word 导出策略实现
 * 基于现有的 DocumentRenderApiService 进行扩展
 *
 * @author hwc
 */
@Component("docTemplateWordExportTemplateStrategy")
@Slf4j
public class WordExportTemplateStrategyDocTemplate extends DocTemplateAbstractExportStrategy {

    @Resource
    private DocumentRenderApiService documentRenderApiService;

    @Override
    protected Object doExport(String htmlContent, String fileName) {
        try {
            log.debug("开始导出Word文档，文件名: {}", fileName);

            // 调用 DocumentRenderApiService 将HTML转换为Word
            byte[] wordContent = documentRenderApiService.exportToWord(htmlContent, fileName);

            // 构建导出结果
            WordExportResult result = WordExportResult.builder()
                    .fileName(fileName + getFileExtension())
                    .fileContent(wordContent)
                    .fileSize((long) wordContent.length)
                    .contentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                    .build();

            log.info("Word导出完成，文件名: {}, 大小: {} bytes", fileName, wordContent.length);
            return result;

        } catch (Exception e) {
            log.error("Word导出失败，文件名: {}", fileName, e);
            throw exception(TEMPLATE_EXPORT_FAILED);
        }
    }

    @Override
    protected String getFileExtension() {
        return ".docx";
    }

    @Override
    public ExportType getExportType() {
        return ExportType.WORD;
    }

    @Override
    protected void postProcess(String fileName, Object result) {
        // Word导出特定的后处理逻辑
        if (result instanceof WordExportResult) {
            WordExportResult wordResult = (WordExportResult) result;
            log.info("Word导出后处理完成: {}, 文件大小: {}字节", fileName, wordResult.getFileSize());
        }
    }
}