package com.uas.report.jasperreports.engine.export;

import net.sf.jasperreports.engine.JRLineBox;
import net.sf.jasperreports.engine.JRPen;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.engine.export.JRExporterGridCell;
import net.sf.jasperreports.engine.export.JRXlsAbstractExporter;
import net.sf.jasperreports.engine.export.ooxml.XlsxBorderHelper;
import net.sf.jasperreports.engine.export.ooxml.XlsxBorderInfo;

import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class CustomXlsxBorderHelper extends XlsxBorderHelper {

    /**
     * 单元格边框宽度
     */
    public static final String CELL_BORDER_WIDTH = "thin";

    /**
     * 单元格边框颜色 25% GREY
     */
    public static final String CELL_BORDER_CORLOR = "AFABAB";

    private Map<String, Integer> borderCache = new HashMap<String, Integer>();

    public CustomXlsxBorderHelper(JasperReportsContext jasperReportsContext, Writer writer) {
        super(jasperReportsContext, writer);
    }

    @Override
    public int getBorder(JRExporterGridCell gridCell, JRXlsAbstractExporter.SheetInfo sheetInfo) {
        if (Boolean.TRUE.equals(sheetInfo.ignoreCellBackground) || gridCell.getBox() == null) {
            return -1;
        }

        XlsxBorderInfo borderInfo = new XlsxBorderInfo(gridCell.getBox());
        Integer borderIndex = borderCache.get(borderInfo.getId());
        if (borderIndex == null) {
            borderIndex = borderCache.size();
            export(borderInfo);
            borderCache.put(borderInfo.getId(), borderIndex);
        }
        return borderIndex;
    }

    @Override
    public void export(JRLineBox box) {
        if (box != null) {
            export(new XlsxBorderInfo(box));
        }
    }

    @Override
    public void export(JRPen pen) {
        if (pen != null) {
            export(new XlsxBorderInfo(pen));
        }
    }

    private void export(XlsxBorderInfo info) {
        {
            write("<border>");
            exportBorder(info, "left");
            exportBorder(info, "right");
            exportBorder(info, "top");
            exportBorder(info, "bottom");
            write("<diagonal/></border>\n");
        }
    }

    private void exportBorder(XlsxBorderInfo info, String side) {
        write("<" + side);
        write(" style=\"" + CELL_BORDER_WIDTH + "\">");
        write(">");
        write("<color rgb=\"" + CELL_BORDER_CORLOR + "\"/>");
        write("</" + side + ">");
    }
}
