package com.nantian.cloud.jljc.tools;

import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 调查（询问）笔录word填充
 */
@Slf4j
@Component
public class SurveyTakeDownUtil {
    /**
     * 以下两个常量所描述的行数不包括（以下空白）
     */
    private static final Integer FIR_LINE_TOTAL = 13; //现场（询问）笔录 第一页中问答的地方最多能有9行内容
    private static final Integer SEN_LINE_TOTAL = 13; // 现场（询问）笔录 续页中问答的地方最多能有14行内容
    private static final String BLANK_BELOW = "（以下空白）";
    private static final String NUMBER_JC = "监察编号：";

    private static SurveyTakeDownUtil minioTemplate;

    @Autowired
    private MinioTemplate minio;

    @PostConstruct
    public void init() {
        minioTemplate = this;
        minioTemplate.minio = this.minio;
    }


    /**
     * 中文逗号转为顿号
     * @param comma
     * @return
     */
    public static String commaConversion(String comma){
        StringBuilder pause = new StringBuilder();
        for (int i = 0; i < comma.length(); i++) {
            char a = comma.charAt(i);
            if (a == ',' || a == '，') {
                a = '、';
            }
            pause.append(a);
        }
        return pause.toString();
    };


    public static XWPFDocument conformityDocx(InputStream filePath1, InputStream filePath2,
                                              Map<String, Object> map, HttpServletResponse response) throws Exception {
        if (filePath2 != null) {
            filePath2.close();   // 没有用到，没有改接口参数，关掉这个流
        }
        int total = 0;
        XWPFDocument home = new XWPFDocument(OPCPackage.open(filePath1));
        List<String> question = (List<String>) map.get("question");
        map.remove("question"); // 剔除map中的questio，后续使用list计算
        XWPFDocument document = new XWPFDocument();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename="  + URLEncoder.encode("调查（询问）笔录.docx", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        if (question.size() > 0){
            /**
             * 对调查（询问）笔录首页进行操作，不涉及续页，如果首页行数不够再读续页
             */
            List<XWPFTable> tables = home.getTables();
            for (XWPFTable table : tables) {
                for (XWPFTableRow row : table.getRows()){
                    for (XWPFTableCell cell : row.getTableCells()){
                        if (cell.getText().equals("${wordAddr}")){
                            if (String.valueOf(map.get("wordAddr")).length() > 0){
                                cell.removeParagraph(0);
                                List<String> wordAddr = CharLengthUtil.getCharLength(String.valueOf(map.get("wordAddr")), 18);
                                total += wordAddr.size();
                                for (int i = 0; i < wordAddr.size(); i++) {
                                    XWPFRun run = cell.addParagraph().createRun();
                                    run.setText(wordAddr.get(i));
                                }
                                map.remove("wordAddr");
                            }else {
                                log.warn("${wordAddr}为空，请重新传入数据!");
                            }
                        }
                        if (cell.getText().equals("${mailingAddr}")){
                            if (String.valueOf(map.get("mailingAddr")).length() > 0){
                                cell.removeParagraph(0);
                                List<String> mailingAddr = CharLengthUtil.getCharLength(String.valueOf(map.get("mailingAddr")), 18);
                                total += mailingAddr.size();
                                for (int i = 0; i < mailingAddr.size(); i++) {
                                    XWPFRun run = cell.addParagraph().createRun();
                                    run.setText(mailingAddr.get(i));
                                }
                                map.remove("mailingAddr");
                            }
                        }
                        if(cell.getText().equals("${question}")){
                            //填充完wordAddr和mailingAddr后还剩下的首页行数
                            int surplusLine = FIR_LINE_TOTAL - total;
                            cell.removeParagraph(0);
                            List<List<String>> dataList = TestUtil.dataCut(question, surplusLine, 13);
                            if (dataList.size() == 1){
                                map.replace("total",1);  //设置总页数为1
                                EditWordZZUtil.setUnderLine(home,map,1); //设置下划线
                                for (int i = 0; i < dataList.get(0).size(); i++) {
                                    String str = dataList.get(0).get(i);
                                    XWPFRun run = cell.addParagraph().createRun();
                                    run.setText(str);
                                }
                                XWPFRun run = cell.addParagraph().createRun(); //添加（以下空白）
                                run.setText(BLANK_BELOW);
                                map.remove("question");
                                EditWordZZUtil.readWriteWord(home,map);
                                home.write(outputStream);
                            }else {
                                int pages = dataList.size();
                                map.replace("total", pages);
                                for (int i = 0; i < dataList.size(); i++) {
                                    if(i == 0){
                                        map.replace("index", i + 1);
                                        EditWordZZUtil.setUnderLine(home, map,1);
                                        for (int j = 0; j < dataList.get(0).size(); j++) {
                                            XWPFParagraph paragraph = cell.addParagraph();
                                            XWPFRun run = paragraph.createRun();
                                            run.setText(dataList.get(0).get(j));
                                            paragraph.setAlignment(ParagraphAlignment.LEFT);
                                        }
                                        XWPFRun run = cell.addParagraph().createRun();
                                        run.setText(BLANK_BELOW);
                                        EditWordZZUtil.readWriteWord(home,map);
                                    }else {
                                        InputStream continuationSheet = minioTemplate.minio.getObject("jljc", "bilu2.docx");
                                        XWPFDocument continuation = new XWPFDocument(OPCPackage.open(continuationSheet));
                                        map.replace("index", i + 1);
                                        EditWordZZUtil.setUnderLine(continuation, map,1);
                                        List<XWPFTable> xwpfTables = continuation.getTables();
                                        for (XWPFTable xwpfTable : xwpfTables){
                                            List<XWPFTableRow> tableRows = xwpfTable.getRows();
                                            for (XWPFTableRow tableRow : tableRows){
                                                List<XWPFTableCell> xwpfTableCells = tableRow.getTableCells();
                                                for (XWPFTableCell xwpfTableCell : xwpfTableCells) {
                                                    if (xwpfTableCell.getText().contains("question")) {
                                                        xwpfTableCell.removeParagraph(0);
                                                        for (int j = 0; j < dataList.get(i).size(); j++){
                                                            XWPFParagraph paragraph = xwpfTableCell.addParagraph();
                                                            XWPFRun run = paragraph.createRun();
                                                            run.setText(dataList.get(i).get(j));
                                                            paragraph.setAlignment(ParagraphAlignment.LEFT);
                                                        }
                                                        XWPFRun run1 = xwpfTableCell.addParagraph().createRun();
                                                        run1.setText(BLANK_BELOW);
                                                    }
                                                }
                                            }
                                        }
                                        EditWordZZUtil.readWriteWord(continuation,map);
                                        MergeDocx mergeDocx = new MergeDocx();
                                        if (i == 1){
                                            document = mergeDocx.mergeWord(home, continuation);
                                        }else {
                                            document = mergeDocx.mergeDocx(document,continuation);
                                        }
                                        if (continuationSheet != null){
                                            continuationSheet.close();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }else {
            log.warn("${question}为空，请重新传入数据!");
        }
        document.write(outputStream);
        if (outputStream != null){
            outputStream.close();
            outputStream.flush();
        }
        if (filePath1 != null){
            filePath1.close();
        }
        return null;
    }

}
