package com.yem.wm.utils;

import com.yem.wm.es.encasement.util.FileUtil;
import kd.bos.exception.KDBizException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 合同盖章
 * @Date: 2024/8/8 17:59
 * @Created: by ZZSLL
 */

public class ContactSignUtils {

    public static List<CTBookmark> getFileBookMarks(InputStream in) {
        List<CTBookmark> list = new ArrayList<>();
        try (XWPFDocument doc = new XWPFDocument(in)) {
            for (XWPFParagraph paragraph : doc.getParagraphs()) {
                list.addAll(paragraph.getCTP().getBookmarkStartList());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    /**
     * 在 Word 文档中的书签位置插入图片，并保存修改后的文档。
     *
     * @param wordFile     原始 Word 文档
     * @param imageFile    图片文件
     * @param outfileName   修改后的 Word 文档保存路径
     * @param bookmarkName 书签名称
     * @return 修改后的 Word 文件
     * @throws IOException      IO 异常
     * @throws InvalidFormatException 格式异常
     */
    public static File replaceBookmarkWithImage(InputStream wordFile, InputStream imageFile, String outfileName, String bookmarkName) throws IOException {
        byte[] imageBytes = readImageFile(imageFile);

        try (XWPFDocument doc = new XWPFDocument(wordFile)) {
            for (XWPFParagraph paragraph : doc.getParagraphs()) {
                List<CTBookmark> bookmarkStartList = paragraph.getCTP().getBookmarkStartList();
                for (CTBookmark bookmark : bookmarkStartList) {
                    if (bookmarkName.equals(bookmark.getName())) {
                        List<XWPFRun> runs = paragraph.getRuns();
                        XWPFRun run;
                        if (!runs.isEmpty()) {
                            run = runs.get(0);
                        } else {
                            run = paragraph.createRun();
                        }
                        //                                                                                                           设置图片大小 长宽比： 1.8586387435
                        run.addPicture(new ByteArrayInputStream(imageBytes), XWPFDocument.PICTURE_TYPE_PNG, "imageName.png", Units.toEMU(74), Units.toEMU(40));
                    }
                }
            }
            FileUtil fileUtil = new FileUtil("sales-order-sign-file");
            File outFile = fileUtil.createNewFile(outfileName);
            try (FileOutputStream out = new FileOutputStream(outFile)) {
                doc.write(out);
            }

            return outFile;
        } catch (InvalidFormatException e) {
            throw new KDBizException("无法解析文件 " + outfileName + " 格式：" + e.getMessage());
        }
    }

    private static byte[] readImageFile(InputStream file) throws IOException {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = file.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        }
    }
}
