package com.nantian.cloud.jljc.tools;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class MergeDocx {

    /**
     * 对XWPFDocument对象进行合并操作
     * @param document
     * @param doucDocument2
     * @return
     * @throws XmlException
     */
    public XWPFDocument mergeWord(XWPFDocument document, XWPFDocument doucDocument2) throws Exception {
        XWPFDocument src1Document =document ;
        XWPFParagraph p = src1Document.createParagraph();
        //设置分页符
        p.setPageBreak(true);
        CTBody src1Body = src1Document.getDocument().getBody();
        XWPFDocument src2Document = doucDocument2;
        CTBody src2Body = src2Document.getDocument().getBody();
//      XWPFParagraph p2 = src2Document.createParagraph();
        XmlOptions optionsOuter = new XmlOptions();
        optionsOuter.setSaveOuter();
        String appendString = src2Body.xmlText(optionsOuter);
        String srcString = src1Body.xmlText();
        String prefix = srcString.substring(0,srcString.indexOf(">")+1);
        String mainPart = srcString.substring(srcString.indexOf(">")+1,srcString.lastIndexOf("<"));
        String sufix = srcString.substring( srcString.lastIndexOf("<") );
        String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
        CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+sufix);
        src1Body.set(makeBody);
        return src1Document;
    }

    /**
     *
     * @param documents
     * @return
     * @throws XmlException
     */
    public XWPFDocument mergeDocx(XWPFDocument... documents) throws Exception {
        List<XWPFDocument> list = Arrays.asList(documents);
        XWPFDocument xmd=list.get(0); //默认获取第一个作为模板
        for (int i=0;i<list.size()-1;i++) {
            xmd=mergeWord(xmd,list.get(i+1)); //相继合并
        }
        return xmd;
    }
}
