package com.ruoyi.common.utils.chartForWord;


import com.ruoyi.common.utils.StringFilterUtil;
import com.ruoyi.common.utils.chartForWord.CustomXWPFDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.List;

/**
 * @Author shuaihua zang
 * @date 2022/10/8
 * 导出word的工具类
 */

public class ExportUtils {


    /**
     * 读取模板
     *
     * @throws Exception
     */

    public void operatorWord(HttpServletResponse response) throws Exception {
        //获得模板文件
        InputStream docis = new FileInputStream("C:\\Users\\xkrs\\Desktop\\V3.0.docx");
        //转成word
        CustomXWPFDocument document = new CustomXWPFDocument(docis);

        //写入图片
        this.insertImage(document);
        //段落替换对象
        this.insertText(document);
        //把doc输出到输出流
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/msword");
        //文件名
        String fileName = "Evaluation report of planting monitoring in ITBA Nature Reserve - V2.0.docx";
        response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
        ServletOutputStream responseOutputStream = response.getOutputStream();
        document.write(responseOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
        //in.close();


    }

        /**
         * 写入图片在word中
         * @param document
         * @throws IOException
         * @throws InvalidFormatException
         */
        public void insertImage(CustomXWPFDocument document) throws Exception{

            //定义一个URL对象
            URL url = new URL("https://rs.sensetime.com/sl-temp/thumbs/cc1hsd7ng0b90dum9jcg.png");
            //打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方式为"GET"
            conn.setRequestMethod("GET");
            //超时响应时间为10秒
            conn.setConnectTimeout(10 * 1000);
            InputStream in = conn.getInputStream();
            //图片
            //FileInputStream in = new FileInputStream("https://rs.sensetime.com/sl-temp/thumbs/cc1hsd7ng0b90dum9jcg.png");
            //段落集合
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            for (XWPFParagraph paragraph : paragraphs) {
                //获取到段落中的所有文本内容
                String text = paragraph.getText();
                //判断此段落中是否有需要进行替换的文本
                if (checkText(text)) {
                    List<XWPFRun> runs = paragraph.getRuns();
                    for (XWPFRun run : runs) {
                        //替换模板原来位置
                        String key = "${ct_pg2_image_1}";
                        //if (run.toString().indexOf(key) != -1) {
                        if (run.text().contains(key)) {
                            byte[] ba = new byte[in.available()];
                            int len = in.read(ba);
                            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(ba, 0, len);
                            //设置图片
                            document.addPictureData(byteInputStream, XWPFDocument.PICTURE_TYPE_PNG);
                            //创建一个word图片，并插入到文档中-->像素可改
                            document.createPicture(document.getAllPictures().size() - 1, 100, 100, paragraph);
                        }
                        break;
                    }
                    //break;
                }
            }
            in.close();
        }
        public void insertText (CustomXWPFDocument document){
            //声明替换模板对象
            Map textMap = new HashMap();
            textMap.put("${ct_1}", "11");
            textMap.put("${ct_2}", "12");
            textMap.put("${ct_3}", "13");
            textMap.put("${ct_4}", "14");
            textMap.put("${ct_5}", "15");
            textMap.put("${ct_6}", "16");
            textMap.put("${ct_7}", "17");
            textMap.put("${ct_8}", "18");
            textMap.put("${ct_9}", "19");
            textMap.put("${ct_10}", "20");
            textMap.put("${ct_11}", "21");
            textMap.put("${ct_12}", "22");
            textMap.put("${ct_13}", "23");
            textMap.put("${ct_14}", "24");
            textMap.put("${ct_1515}", "25");
            textMap.put("${ct_16}", "26");
            textMap.put("${ct_17}", "27");
            textMap.put("${ct_18}", "28");
            textMap.put("${ct_19}", "29");
            textMap.put("${ct_20}", "30");
            textMap.put("${ct_21}", "31");
            textMap.put("${ct_22}", "32");
            textMap.put("${ct_23}", "33");
            textMap.put("${ct_24}", "34");
            textMap.put("${ct_25}", "35");
            textMap.put("${ct_26}", "36");
            textMap.put("${ct_27}", "37");
            textMap.put("${ct_28}", "38");
            textMap.put("${ct_29}", "39");
            //替换模板数据
            changeText(document, textMap);
        }

        /**
         * 替换段落文本
         *
         * @param document docx解析对象
         * @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 (checkText(text)) {
                    List<XWPFRun> runs = paragraph.getRuns();
                    for (XWPFRun run : runs) {
                        //替换模板原来位置
                        //System.out.println(run.text());
                        run.setText(changeText_$(run.text()) + (String) changeValue(run.text().toString(), textMap), 0);
                    }
                }
            }

        }
        /**
         * 判断文本中是否包含$
         *
         * @param text 文本
         * @return 包含返回true, 不包含返回false
         */
        public static boolean checkText (String text){
            boolean check = false;
            if (text.indexOf("$") != -1) {
                check = true;
            }
            return check;
        }
        /**
         * 替换模板${}
         */
        private static Object changeValue (String value, Map < String, Object > textMap){
            Set<Map.Entry<String, Object>> textSets = textMap.entrySet();
            Object valu = "";
            for (Map.Entry<String, Object> textSet : textSets) {
                // 匹配模板与替换值 格式${key}
                String key = textSet.getKey();
                if (value.contains(key)) {
                    valu = (String) textSet.getValue();
                }
            }
            return valu;
        }

        /**
         * 替换原先段落中的${}
         * @param text
         * @return
         */
        public static String changeText_$ (String text)
        {

            if (!text.contains("$")) {
                return text;
            }
            String filterForBetween = StringFilterUtil.filterForBetween(text, '$', '}');
            System.out.println(filterForBetween);
            return filterForBetween;
        }

    }
