package com.nokia.common.excel.entity;

import java.awt.Color;
import java.util.List;
import java.util.regex.Pattern;

import lombok.Data;

/**
 * Excel上一个矩形区域的全部信息
 */
@Data
public class CellRect {

    // 总宽度
    private int totalWidth;
    // 总高度
    private int totalHeight;
    // 边框像素数
    private int margin = 5;

    // excel上的起止位置信息
    private int startCol;
    private int endCol;
    private int startRow;
    private int endRow;

    // 背景色，默认白色
    private Color backgroundColor = Color.WHITE;
    // 统一字体
    private String fontFamily = null;
    private int fontSizeMin = 11;

    // 范围内的全部单元格信息CellInfo
    private List<CellInfo> cellInfos;

    // 识别Rect区域的正则表达式
    private static final Pattern PATTERN = Pattern.compile("^[A-Z]+\\d+:[A-Z]+\\d+$");

    public static CellRect parse(String rect) {
        boolean matches = PATTERN.matcher(rect).matches();
        if (!matches) {
            throw new RuntimeException(String.format("输入的%s格式错误，正确的示例A1:AA33,表示第0-32行，0-26列", rect));
        }
        String[] split = rect.split(":");
        CellRect cellRect = new CellRect();
        cellRect.setStartCol(getCol(split[0]));
        cellRect.setStartRow(getRow(split[0]));
        cellRect.setEndCol(getCol(split[1]));
        cellRect.setEndRow(getRow(split[1]));
        return cellRect;
    }

    /**
     * 26进制字符串转10进制数
     * 注意，AA = 1*26+1 所以是无0的
     * 
     * @param cell
     * @return
     */
    private static int getCol(String cell) {
        int result = 0;
        // 位数
        for (int i = 0; i < cell.length(); i++) {
            int a = cell.charAt(i);
            // 不是A-Z的字符直接忽略
            if (a > 90 || a < 65)
                continue;
            // 发现1个A-Z的字符 位数+1
            result = result * 26 + a - 64;
        }
        return result - 1;
    }

    /**
     * 字符串转10进制数
     * 
     * @param cell
     * @return
     */
    private static int getRow(String cell) {
        int result = 0;
        for (int i = 0; i < cell.length(); i++) {
            int c = cell.charAt(i);
            // 不是0-9
            if (c < 48 || c > 57)
                continue;
            result = result * 10 + c - 48;
        }
        return result - 1;
    }

    /**
     * 从列号转为列名 如26转为AA
     * 
     * @param colNum
     * @return
     */
    public static String getColumnName(int colNum) {
        StringBuffer stringBuffer = new StringBuffer();
        int realCol = colNum + 1;
        while (realCol > 26) {
            stringBuffer.append((char) (realCol / 26 + 64));
            realCol %= 26;
        }
        stringBuffer.append((char) (realCol + 64));
        return stringBuffer.toString();
    }
}
