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

import com.uas.report.util.ObjectUtils;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.export.Cut;
import net.sf.jasperreports.engine.export.XlsRowLevelInfo;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.export.ooxml.XlsxBorderHelper;
import net.sf.jasperreports.engine.export.ooxml.XlsxStyleHelper;
import net.sf.jasperreports.engine.util.FileBufferedWriter;

import java.io.OutputStream;
import java.lang.reflect.Field;

/**
 * 报表导出为Xls
 *
 * @author sunyj
 * @since 2016年12月14日 下午8:10:56
 */
public class CustomJRXlsxExporter extends JRXlsxExporter {

    /**
     * 单元格宽度
     */
    public static final int CELL_WIDTH = 50;

    /**
     * 单元格高度
     */
    public static final int CELL_HEIGHT = 12;

    /**
     * 是否自定义单元格格式
     */
    private boolean customCellStyle = false;

    public CustomJRXlsxExporter(boolean ifCustomCellStyle) {
        this.customCellStyle = ifCustomCellStyle;
    }

    @Override
    protected void setColumnWidth(int col, int width, boolean autoFit) {
        if (customCellStyle) {
            width = CELL_WIDTH;
        }
        super.setColumnWidth(col, width, autoFit);
    }

    @Override
    protected void setRowHeight(int rowIndex, int rowHeight, Cut yCut, XlsRowLevelInfo levelInfo) throws JRException {
        if (customCellStyle) {
            rowHeight = CELL_HEIGHT;
        }
        super.setRowHeight(rowIndex, rowHeight, yCut, levelInfo);
    }

    @Override
    protected void openWorkbook(OutputStream os) throws JRException {
        super.openWorkbook(os);
        if (customCellStyle) {
            FileBufferedWriter bordersWriter = (FileBufferedWriter) ObjectUtils.recursivelyGetValue("bordersWriter",
                    styleHelper);
            XlsxBorderHelper borderHelper = new CustomXlsxBorderHelper(jasperReportsContext, bordersWriter);
            // 通过反射替换 styleHelper 中的 borderHelper 为 CustomXlsxBorderHelper 类型
            Field borderHelperField = ObjectUtils.recursivelyGetField("borderHelper", XlsxStyleHelper.class);
            borderHelperField.setAccessible(true);
            try {
                borderHelperField.set(styleHelper, borderHelper);
            } catch (Throwable e) {
                throw new IllegalArgumentException("替换 borderHelper 失败", e);
            }
            borderHelperField.setAccessible(false);
        }
    }
}
