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.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * 将指定数据行、指定列（一般为合并区域左上角）的单元格设为水平、垂直居中，用于合并后「合计」等文案居中显示。
 */
public class MergedAnchorCellCenterStyleHandler implements CellWriteHandler {

    private final int excelRowIndex;
    private final int columnIndex;

    public MergedAnchorCellCenterStyleHandler(int excelRowIndex, int columnIndex) {
        this.excelRowIndex = excelRowIndex;
        this.columnIndex = columnIndex;
    }

    @Override
    public int order() {
        return OrderConstant.FILL_STYLE + 15000;
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        if (Boolean.TRUE.equals(context.getHead())) {
            return;
        }
        Cell cell = context.getCell();
        if (cell == null) {
            return;
        }
        if (cell.getRowIndex() != excelRowIndex || cell.getColumnIndex() != columnIndex) {
            return;
        }
        Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
        CellStyle style = workbook.createCellStyle();
        style.cloneStyleFrom(cell.getCellStyle());
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        cell.setCellStyle(style);
    }
}
