package com.ag.secp.platform.office.word;


import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * poi方法生成word
 * 简单的例子
 * Created by Administrator on 2018/1/1.
 */
public class ExpPoiSimWord {

    /**
     * Description: 通用查询
     * @param inFilePath 原文件路径
     * @param osFilePath 生成文件路径
     * @param params 传入变量参数Map集合
     * @throws Exception
     * Note: Nothing much.
     */
    public void expPoiSimWord(String inFilePath,String osFilePath,Map<String, Object> params)  throws Exception{
        InputStream is = new FileInputStream(inFilePath);
        XWPFDocument doc = new XWPFDocument(is);
        ExpPoiSimWord expPoiSimWord = new ExpPoiSimWord();
        //替换段落里面的变量
        expPoiSimWord.replaceInPara(doc, params);
        //替换表格里面的变量
        expPoiSimWord.replaceInTable(doc, params);
        OutputStream os = new FileOutputStream(osFilePath);
        doc.write(os);
        expPoiSimWord.close(os);
        expPoiSimWord.close(is);
    }

    /**
     * 替换段落里面的变量
     *
     * @param doc    要替换的文档
     * @param params 参数
     */
    public void replaceInPara(XWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while (iterator.hasNext()) {
            para = iterator.next();
            this.replaceInPara(para, params);
        }
    }

    /**
     * 替换段落里面的变量
     *
     * @param para   要替换的段落
     * @param params 参数
     */
    public void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
        List<XWPFRun> runs;
        Matcher matcher;
        if (this.matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();

            int start = -1;
            int end = -1;
            String str = "";
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                String runText = run.toString();
                if ('$' == runText.charAt(0)&&'{' == runText.charAt(1)) {
                    start = i;
                }
                if ((start != -1)) {
                    str += runText;
                }
                if ('}' == runText.charAt(runText.length() - 1)) {
                    if (start != -1) {
                        end = i;
                        break;
                    }
                }
            }
            for (int i = start; i <= end; i++) {
                para.removeRun(i);
                i--;
                end--;
            }

            for (String key : params.keySet()) {
                if (str.equals(key)) {
                    para.createRun().setText((String) params.get(key));
                    break;
                }
            }


        }
    }

    /**
     * 替换表格里面的变量
     *
     * @param doc    要替换的文档
     * @param params 参数
     */
    public void replaceInTable(XWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFTable> iterator = doc.getTablesIterator();
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        List<XWPFParagraph> paras;
        while (iterator.hasNext()) {
            table = iterator.next();
            rows = table.getRows();
            for (XWPFTableRow row : rows) {
                cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    paras = cell.getParagraphs();
                    for (XWPFParagraph para : paras) {
                        this.replaceInPara(para, params);
                    }
                }
            }
        }
    }

    /**
     * 正则匹配字符串
     *
     * @param str
     * @return
     */
    private Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

    /**
     * 关闭输入流
     *
     * @param is
     */
    public void close(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭输出流
     *
     * @param os
     */
    public void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


//    public static void main(String[] args) throws IOException {
//        Map<String, Object> params = new HashMap();
//        params.put("${time}","2017-10-10");
//        params.put("${name}","张老师");
//        params.put("${sex}","1");
//        params.put("${title}","教授");
//        params.put("${subjectCod}","Math");
//        ExpPoiSimWord expPoiSimWord = new ExpPoiSimWord();
//        String filePath = "D:\\test\\teacher.docx";
//        InputStream is = new FileInputStream(filePath);
//        XWPFDocument doc = new XWPFDocument(is);
//        //替换段落里面的变量
//        expPoiSimWord.replaceInPara(doc,params);
//        //替换表格里面的变量
//        expPoiSimWord.replaceInTable(doc,params);
//        OutputStream os = new FileOutputStream("D:\\test\\t"+System.currentTimeMillis()+".docx");
//        doc.write(os);
//        expPoiSimWord.close(os);
//        expPoiSimWord.close(is);
//    }
}
