package com.yaoyicloud.tools;

import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;

import com.deepoove.poi.util.TableTools;

public final class Util {

    /**
     * 合并第n列
     *
     * @param table 表格对象

     */
    public static void mergeFirstNCol(XWPFTable table, int n, int keySeq) {
        if (table.getNumberOfRows() < 1) {
            return;
        }
        int currentStart = 1;
        for (int i = 1; i < table.getNumberOfRows() - 1; i++) { // 最后一行是合计
            XWPFParagraph par = getParagraphForCell(table.getRow(i).getCell(keySeq));
            String key = par.getRuns().get(0).getText(0);
            for (int j = 0; j < n; j++) {
                if (key.equals("")) {
                    TableTools.mergeCellsVertically(table, j, currentStart, i);
                } else {
                    currentStart = i;
                }
                // 设置居中
                verticalCentering(table.getRow(i).getCell(j));
            }
        }
        int i = 0;
        while (table.getRow(table.getNumberOfRows() - 1).getCell(i) != null) {
            verticalCentering(table.getRow(table.getNumberOfRows() - 1).getCell(i));
            i++;
        }
    }

    /**
     * 简单合并表格中前N列的垂直单元格（按指定列的关键字分组合并）
     * 功能：遍历表格行，根据指定列（keySeq）的关键字是否相同，将前N列的单元格进行垂直合并
     *
     * @param table   要处理的XWPF表格对象
     * @param n       需要合并的前N列（例如n=2表示合并第0列和第1列）
     * @param keySeq  用于判断是否合并的关键字所在列的索引（以此列的内容作为分组依据）
     */
    public static void mergeFirstNColSimple(XWPFTable table, int n, int keySeq) {
        if (table.getNumberOfRows() < 1) {
            return;
        }
        int currentStart = 1;
        String lastKey = "impossible_to_collide";
        for (int i = 1; i < table.getNumberOfRows(); i++) {
            XWPFParagraph par = getParagraphForCell(table.getRow(i).getCell(keySeq));
            String key = par.getRuns().get(0).getText(0);
            for (int j = 0; j < n; j++) {
                if (lastKey.equals(key)) {
                    // 清除被合并单元格内容
                    getParagraphForCell(table.getRow(i).getCell(j)).getRuns().get(0).setText("");
                    TableTools.mergeCellsVertically(table, j, currentStart, i);
                } else {
                    currentStart = i;
                }
                // 设置居中
                verticalCentering(table.getRow(i).getCell(j));
            }
            lastKey = key;
        }
    }

    /**
     * 垂直居中
     *
     * @param cell 单元格
     */
    public static void verticalCentering(XWPFTableCell cell) {
        CTTc cttc = cell.getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
        // cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
    }

    /**
     *
     * @param cell
     * @param val
     */
    public static void setText(XWPFTableCell cell, String val) {
        cell.setText(val);
        verticalCentering(cell);
    }

    /**
     * 合计染色
     *
     * @param cell
     */
    public static XWPFTableCell colorSummary(XWPFTableCell cell, String value) {
        XWPFParagraph par = getParagraphForCell(cell);
        XWPFRun run = par.createRun();
        run.setColor("8FAADC");
        run.setText(value);
        verticalCentering(cell);
        return cell;
    }

    /**
     *
     * @param cell
     * @param value
     */
    public static void replaceLastRowText(XWPFTableCell cell, String value) {
        if (cell.getParagraph(cell.getCTTc().getPArray(0)) != null
            && cell.getParagraph(cell.getCTTc().getPArray(0)).getRuns().size() > 0
            && cell.getParagraph(cell.getCTTc().getPArray(0)).getRuns().get(0) != null) {
            cell.getParagraph(cell.getCTTc().getPArray(0)).getRuns().get(0).setText(value, 0);
        } else {
            cell.setText(value);
        }
    }

    private static XWPFParagraph getParagraphForCell(XWPFTableCell cell) {
        CTTc ctTc = cell.getCTTc();
        CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0);
        return new XWPFParagraph(ctP, cell);
    }

    public static int getColIndexOfFirstRow(XWPFTableCell cell) {
        XWPFTableRow tableRow = cell.getTableRow();
        int orginalCol = 0;
        for (int i = 0; i < tableRow.getTableCells().size(); i++) {
            XWPFTableCell current = tableRow.getCell(i);
            int intValue = 1;
            CTTcPr tcPr = current.getCTTc().getTcPr();
            if (null != tcPr) {
                CTDecimalNumber gridSpan = tcPr.getGridSpan();
                if (null != gridSpan) {
                    intValue = gridSpan.getVal().intValue();
                }
            }
            orginalCol += intValue;
            if (current.getCTTc() == cell.getCTTc()) {
                return orginalCol - intValue;
            }
        }
        return -1;
    }
}
