package com.dayou.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 类说明：poi word工具类
 *
 * @author: wucl
 * @since: 2024/3/18
 * created with IntelliJ IDEA.
 */
@Slf4j
public class POIWordUtil {

    public static void replaceWord(XWPFDocument document, Map<String,Object> textMap){
        changeText(document,textMap);
        changeTable(document,textMap);
    }

    /**
     * 替换表格文本
     * @param document
     * @param textMap
     */
    public static void changeTable(XWPFDocument document, Map<String, Object> textMap) {
        //获取表格对象集合
        List<XWPFTable> tables = document.getTables();
        for (int i = 0; i<tables.size(); i++){
            XWPFTable table = tables.get(i);
            //只处理行数大于2的表格 不循环表头
            if (table.getRows().size()>1){
                String text = table.getText();
                if (StrUtil.isNotBlank(text) && text.contains("${")){
                    List<XWPFTableRow> rows = table.getRows();
                    eachTable(rows,textMap);
                }
            }
        }
    }

    /**
     * 遍历表格
     * @param rows 表格行对象
     * @param textMap 替换信息
     */
    private static void eachTable(List<XWPFTableRow> rows, Map<String, Object> textMap) {
        for (XWPFTableRow row :rows){
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells){
                String text = cell.getText();
                if (StrUtil.isNotBlank(text) && text.contains("${")){
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph :paragraphs){
                        List<XWPFRun> runs = paragraph.getRuns();
                        for (XWPFRun run : runs){
                            if ("${validateCode}".equals(run.toString())){
                                String path = (String) textMap.get("validateCode");
                                try {
                                    run.setText("",0);
                                    XWPFPicture picture = run.addPicture(new FileInputStream("/opt" + path), XWPFDocument.PICTURE_TYPE_PNG, "电子二维码", Units.toEMU(120), Units.toEMU(120));
                                    picture.getCTPicture().getSpPr().getXfrm().getOff().setY(Units.toEMU(120));
                                    paragraph.setAlignment(ParagraphAlignment.HIGH_KASHIDA);
                                } catch (Exception e) {
                                    log.error("validateCode insert error!!!");
                                }
                            }else{
                                run.setText(changeValue(run.toString(),textMap),0);
                            }
                        }
                    }
                }
            }
        }

    }

    /**
     *  替换段落文本
     * @param document
     * @param textMap
     */
    public static void changeText(XWPFDocument document, Map<String, Object> textMap) {
        //获取段落集合
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs){
            //判断此段落是否需要替换
            String text = paragraph.getText();
            if (StrUtil.isNotBlank(text) && text.contains("${")){
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs){
                   String textValue =  changeValue(run.toString(),textMap);
                   run.setText(textValue,0);
                }
            }
        }
    }

    /**
     * 匹配传入信息集合与模板
     * @param value
     * @param textMap
     * @return
     */
    private static String changeValue(String value, Map<String, Object> textMap) {
        Set<Map.Entry<String, Object>> textSets = textMap.entrySet();
        for (Map.Entry<String,Object> textSet :textSets){
            String key = "${"+textSet.getKey()+"}";
            if (value.indexOf(key) !=-1){
                Object v = textSet.getValue();
                if (v==null){
                    value = "";
                }else{
                    String str = String.valueOf(v);
                    value = value.replace(key,str);
                }
            }
        }
        return value;
    }
}
