package cn.com.poc.expose.rest.impl;

import cn.com.poc.common.service.BosConfigService;
import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.common.utils.UUIDTool;
import cn.com.poc.expose.dto.ContentReportDto;
import cn.com.poc.expose.rest.ContentReportRest;
import cn.com.yict.framemax.core.exception.BusinessException;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Document;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author alex.yao
 * @date 2025/3/7
 */
@Component
public class ContentReportRestImpl implements ContentReportRest {

    @Resource
    private BosConfigService bosConfigService;


    @Override
    public String report(ContentReportDto dto) throws IOException {
        String markdown = dto.getContent();
        if (StringUtils.isBlank(markdown)) {
            throw new BusinessException("markdown is blank");
        }
        String reportType = dto.getReportType();
        File file = File.createTempFile(UUIDTool.getUUID(), "." + reportType);
        String result = "";
        if ("docx".equals(reportType) || "doc".equals(reportType)) {
            String htmlContent = convertMarkdownToHtml(markdown);
            result = exportWord(htmlContent);
        } else if ("html".equals(reportType)) {
            String htmlContent = convertMarkdownToHtml(markdown);
            result = bosConfigService.uploadFileByByteArray2Oss(htmlContent.getBytes(), UUIDTool.getUUID(), reportType);
        } else if ("md".equals(reportType)) {
            result = bosConfigService.uploadFileByByteArray2Oss(markdown.getBytes(), UUIDTool.getUUID(), reportType);
        } else {
            throw new BusinessException("reportType is not supported");
        }
        file.delete();
        return result;
    }

    private String convertMarkdownToHtml(String markdown) {
        Pattern p = Pattern.compile("(\r?\n(\\s*\r?\n)+)");
        Matcher m = p.matcher(markdown);
        String result = m.replaceAll("\r\n");

        Parser parser = Parser.builder().build();
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        Document document = parser.parse(result);
        return renderer.render(document);
    }


    /**
     * @param content 富文本内容转word
     * @throws Exception
     */
    public String exportWord(String content) throws IOException {
        if (!content.startsWith("<html>")) {
            content = "<html>" + content;
        }
        if (!content.contains("<body>")) {
            content = content.replaceFirst("<html>", "<html><body>") + "</body></html>";
        }

        byte b[] = content.getBytes("GBK"); //这里是必须要设置编码的，不然导出中文就会乱码。
        ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
        POIFSFileSystem poifs = new POIFSFileSystem();
        DirectoryEntry directory = poifs.getRoot();
        DocumentEntry documentEntry = directory.createDocument("WordDocument", bais); //该步骤不可省略，否则会出现乱码。
        //输出文件
        File file = File.createTempFile(UUIDTool.getUUID(), ".docx");
        FileOutputStream ostream = new FileOutputStream(file);
        poifs.writeFilesystem(ostream);
        FileInputStream fileInputStream = new FileInputStream(file);
        String upload = bosConfigService.upload(fileInputStream, "docx", "application/msword");
        bais.close();
        ostream.close();
        poifs.close();
        fileInputStream.close();
        return upload;
    }
}
