package com.njcn.gather.tools.report.util;

import org.docx4j.wml.*;

import javax.xml.bind.JAXBElement;
import java.util.ArrayList;
import java.util.List;


/**
 * 递归查找所有书签，并在书签处插入内容
 * @author hongawen
 */
public class BookmarkUtil {

    /**
     * 书签信息
     */
    public static class BookmarkInfo {
        public CTBookmark bookmark;
        public P parentParagraph;
        public ContentAccessor parentContainer;
    }

    /**
     * 递归查找所有书签
     */
    public static List<BookmarkInfo> findAllBookmarks(ContentAccessor contentAccessor) {
        List<BookmarkInfo> result = new ArrayList<>();
        for (Object obj : contentAccessor.getContent()) {
            Object realObj = (obj instanceof JAXBElement) ? ((JAXBElement<?>) obj).getValue() : obj;
            if (realObj instanceof P) {
                P p = (P) realObj;
                for (Object o2 : p.getContent()) {
                    Object realO2 = (o2 instanceof JAXBElement) ? ((JAXBElement<?>) o2).getValue() : o2;
                    if (realO2 instanceof CTBookmark) {
                        BookmarkInfo info = new BookmarkInfo();
                        info.bookmark = (CTBookmark) realO2;
                        info.parentParagraph = p;
                        info.parentContainer = contentAccessor;
                        result.add(info);
                    }
                }
            } else if (realObj instanceof ContentAccessor) {
                result.addAll(findAllBookmarks((ContentAccessor) realObj));
            }
        }
        return result;
    }


    /**
     * 在书签后插入段落
     */
    public static void insertParagraphsAfter(BookmarkInfo info, P paragraph) {
        List<Object> parentContent = info.parentContainer.getContent();
        int idx = parentContent.indexOf(info.parentParagraph);
        parentContent.add(idx + 1, paragraph);
    }

    /**
     * 在书签后插入表格
     */
    public static void insertTableAfter(BookmarkInfo info, Tbl table) {
        List<Object> parentContent = info.parentContainer.getContent();
        int idx = parentContent.indexOf(info.parentParagraph);
        parentContent.add(idx + 1, table);
    }

    /**
     * 在书签后插入元素，可能是段落、表格、图片、书签等
     */
    public static void insertElement(BookmarkInfo info, List<Object> elements) {
        List<Object> parentContent = info.parentContainer.getContent();
        int idx = parentContent.indexOf(info.parentParagraph);
        // 遍历元素，如果是通道回路这种大标题需要新起一个空的文档页
        for (int i = 0; i < elements.size(); i++) {
            Object element = elements.get(i);
            if (element instanceof P) {
                P p = (P) element;
                String textFromP = Docx4jUtil.getTextFromP(p);
                if (textFromP.contains("测量回路")) {
//                    if (!textFromP.contains("1")) {
//                        // 另起一页
//                        P pagePara = Docx4jUtil.getPageBreak();
//                        idx = idx + 1;
//                        parentContent.add(idx, pagePara);
//                    }
                    idx = idx + 1;
                    parentContent.add(idx, p);
                }
//                else if (
//                        textFromP.startsWith(PowerIndexEnum.IMBV.getDesc())
//                        || textFromP.startsWith(PowerIndexEnum.HV.getDesc())
//                        || textFromP.startsWith(PowerIndexEnum.HI.getDesc())
//
//                ) {
//                    // 另起一页
//                    P pagePara = Docx4jUtil.getPageBreak();
//                    idx = idx + 1;
//                    parentContent.add(idx, pagePara);
//                    idx = idx + 1;
//                    parentContent.add(idx, element);
//                }else if(textFromP.startsWith("注：基波电流幅值5.000A，基波频率50.0Hz,各次间谐波电流含有率均为3.0%。")){
//                    idx = idx + 1;
//                    parentContent.add(idx, element);
//                    P pagePara = Docx4jUtil.getPageBreak();
//                    idx = idx + 1;
//                    parentContent.add(idx, pagePara);
//                }
                else {
                    idx = idx + 1;
                    parentContent.add(idx, element);
                }
            } else {
                idx = idx + 1;
                parentContent.add(idx, element);
            }
        }
    }


    /**
     * 删除书签
     *
     * @param bookmarkInfo 书签信息
     */
    public static void removeBookmark(BookmarkInfo bookmarkInfo) {
        try {
            // 获取书签所在的段落
            P paragraph = bookmarkInfo.parentParagraph;

            // 遍历段落内容，找到并删除书签开始和结束标记
            List<Object> paragraphContent = new ArrayList<>(paragraph.getContent());
            for (Object obj : paragraphContent) {
                if (obj instanceof JAXBElement) {
                    JAXBElement<?> element = (JAXBElement<?>) obj;
                    Object value = element.getValue();

                    // 删除书签开始标记
                    if (value instanceof CTBookmark) {
                        paragraph.getContent().remove(obj);
                    }
                    // 删除书签结束标记
                    else if (value instanceof CTMarkupRange) {
                        paragraph.getContent().remove(obj);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取指定标签的标签信息
     *
     * @param key       标签名
     * @param bookmarks 所有标签信息
     */
    public static BookmarkInfo getBookmarkInfo(String key, List<BookmarkInfo> bookmarks) {
        BookmarkInfo bookmarkInfo = null;
        for (BookmarkInfo info : bookmarks) {
            String name = info.bookmark.getName();
            if (key.equalsIgnoreCase(name)) {
                bookmarkInfo = info;
            }
        }
        return bookmarkInfo;
    }
}
