package com.muchinfo.mtp3century.handler;

import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

public class GoodsMergeStrategy extends AbstractRowWriteHandler implements CellWriteHandler {
    private WriteSheetHolder writeSheetHolder;
    private WriteTableHolder writeTableHolder;
    private String lastRowContent = null; // 上一行的内容
    private int lastRowNum = -1; // 上一行的行号

    @Override
    public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,Integer rowIndex, Integer relativeRowIndex, Boolean isHead) {
        this.writeSheetHolder = writeSheetHolder;
        this.writeTableHolder = writeTableHolder;
    }

    @Override
    public void afterCellCreate(CellWriteHandlerContext context) {
        if (!context.getHead()) { // 只处理数据行
            String currentRowContent = context.getCell().getStringCellValue();
            int currentRowNum = context.getRow().getRowNum();

            if (lastRowContent != null && lastRowContent.equals(currentRowContent)) {
                // 如果当前行和上一行内容相同，则合并单元格
                Sheet sheet = writeSheetHolder.getSheet();
                // 合并第0列和第1列
                CellRangeAddress cellRangeAddress = new CellRangeAddress(
                        lastRowNum, // 起始行号
                        currentRowNum, // 结束行号
                        0, // 起始列号
                        1); // 结束列号

                // 添加合并区域
                sheet.addMergedRegion(cellRangeAddress);
            } else {
                // 内容不同，记录当前行内容和行号
                lastRowContent = currentRowContent;
                lastRowNum = currentRowNum;
            }
        }
    }
}
