package com.maintain.common.utils.poi;

import com.alibaba.excel.constant.OrderConstant;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * 多行表头时，仅将第一行（大标题行，relativeRowIndex=0）设为白底，其余表头行保持实体类上的 {@code @HeadStyle}。
 */
public class HeadTitleRowWhiteStyleHandler implements CellWriteHandler {

    private CellStyle whiteTitleRowStyle;

    /**
     * 在注解 {@code @HeadStyle} 等样式写入之后再执行（EasyExcel：order 越小越早）。
     */
    @Override
    public int order() {
        return OrderConstant.FILL_STYLE + 10000;
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        if (!Boolean.TRUE.equals(context.getHead())) {
            return;
        }
        Integer relativeRowIndex = context.getRelativeRowIndex();
        if (relativeRowIndex == null || relativeRowIndex != 0) {
            return;
        }
        Cell cell = context.getCell();
        if (cell == null) {
            return;
        }
        Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
        if (whiteTitleRowStyle == null) {
            whiteTitleRowStyle = workbook.createCellStyle();
            whiteTitleRowStyle.cloneStyleFrom(cell.getCellStyle());
            whiteTitleRowStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            whiteTitleRowStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        }
        cell.setCellStyle(whiteTitleRowStyle);
    }
}
