package com.yc.ship.module.trade.utils.excel;

import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.yc.ship.module.trade.controller.admin.report.vo.CruiseOpsDailyRespVO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;

import java.util.*;

/**
 * 省际度假游轮经营情况日报表 导出样式处理器
 * 处理单元格合并和小计/累计行的背景色
 */
public class CruiseOpsDailyExportStyleHandler implements CellWriteHandler {

    private static final int TOTAL_COLUMNS = 15;

    private final List<CruiseOpsDailyRespVO> dataList;

    /** 预计算的合并区域 */
    private final List<CellRangeAddress> mergeRegions = new ArrayList<>();

    /** 小计行（含同比行）在 data 中的索引集合 */
    private final Set<Integer> subtotalRowIndices = new HashSet<>();
    /** 累计行（含同比行）在 data 中的索引集合 */
    private final Set<Integer> cumulativeRowIndices = new HashSet<>();

    /** 已处理的单元格计数 */
    private int processedCells = 0;
    private final int totalCells;
    private boolean mergesApplied = false;

    /** 缓存的样式（避免每个单元格创建新样式） */
    private CellStyle subtotalStyle;
    private CellStyle cumulativeStyle;

    public CruiseOpsDailyExportStyleHandler(List<CruiseOpsDailyRespVO> dataList) {
        this.dataList = dataList;
        this.totalCells = dataList.size() * TOTAL_COLUMNS;
        precompute();
    }

    /**
     * 预计算合并区域和行类型
     */
    private void precompute() {
        for (int i = 0; i < dataList.size(); i++) {
            CruiseOpsDailyRespVO row = dataList.get(i);
            boolean isSubtotal = Boolean.TRUE.equals(row.getIsSubtotal());
            boolean isCumulative = Boolean.TRUE.equals(row.getIsCumulative());
            boolean isYoy = "同比".equals(row.getVoyageNo());

            int excelRowIndex = i + 1; // +1 因为第0行是表头

            if (isSubtotal && !isYoy) {
                // 小计数据行 + 紧随的同比行都标记为小计行
                subtotalRowIndices.add(i);
                if (i + 1 < dataList.size()) {
                    subtotalRowIndices.add(i + 1);
                }
                // 序号列：纵向合并2行
                mergeRegions.add(new CellRangeAddress(excelRowIndex, excelRowIndex + 1, 0, 0));
                // 月份~航线列(1-4)：纵向2行 + 横向4列合并
                mergeRegions.add(new CellRangeAddress(excelRowIndex, excelRowIndex + 1, 1, 4));
            }

            if (isCumulative && !isYoy) {
                cumulativeRowIndices.add(i);
                if (i + 1 < dataList.size()) {
                    cumulativeRowIndices.add(i + 1);
                }
                mergeRegions.add(new CellRangeAddress(excelRowIndex, excelRowIndex + 1, 0, 0));
                mergeRegions.add(new CellRangeAddress(excelRowIndex, excelRowIndex + 1, 1, 4));
            }
        }
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        // 跳过表头行
        if (Boolean.TRUE.equals(context.getHead())) {
            return;
        }

        Cell cell = context.getCell();
        int excelRowIndex = cell.getRow().getRowNum();
        int dataRowIndex = excelRowIndex - 1; // 减去表头行

        if (dataRowIndex < 0 || dataRowIndex >= dataList.size()) {
            return;
        }

        Sheet sheet = context.getWriteSheetHolder().getSheet();
        Workbook workbook = sheet.getWorkbook();

        // 1. 应用背景色
        applyRowStyle(cell, dataRowIndex, workbook);

        // 2. 所有单元格处理完成后，统一应用合并
        processedCells++;
        if (!mergesApplied && processedCells >= totalCells) {
            mergesApplied = true;
            for (CellRangeAddress merge : mergeRegions) {
                sheet.addMergedRegion(merge);
            }
        }
    }

    /**
     * 根据行类型应用样式
     */
    private void applyRowStyle(Cell cell, int dataRowIndex, Workbook workbook) {
        boolean isSubtotalRow = subtotalRowIndices.contains(dataRowIndex);
        boolean isCumulativeRow = cumulativeRowIndices.contains(dataRowIndex);

        if (!isSubtotalRow && !isCumulativeRow) {
            return;
        }

        CellStyle style;
        if (isSubtotalRow) {
            if (subtotalStyle == null) {
                subtotalStyle = createFillStyle(workbook, new byte[]{(byte) 0xFE, (byte) 0xF0, (byte) 0xF0});
            }
            style = subtotalStyle;
        } else {
            if (cumulativeStyle == null) {
                cumulativeStyle = createFillStyle(workbook, new byte[]{(byte) 0xF5, (byte) 0xF7, (byte) 0xFA});
            }
            style = cumulativeStyle;
        }

        cell.setCellStyle(style);
    }

    /**
     * 创建带填充色和居中的单元格样式
     */
    private CellStyle createFillStyle(Workbook workbook, byte[] rgb) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        // 尝试使用XSSF自定义颜色
        if (style instanceof XSSFCellStyle) {
            XSSFColor customColor = new XSSFColor(rgb, null);
            ((XSSFCellStyle) style).setFillForegroundColor(customColor);
        } else {
            // HSSF 降级：使用最接近的 IndexedColor
            style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        }

        return style;
    }
}
