package com.youchain.utils;

import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.read.listener.ReadListener;
import com.youchain.exception.BadRequestException;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class FastExcelCellListener implements ReadListener<Map<Integer, String>> {
    private final Map<CellPosition, String> cellValues = new ConcurrentHashMap<>();
    private final Set<CellPosition> targetCells = new HashSet<>();
    private volatile boolean allCellsRead = false;

    /**
     * 添加目标单元格
     *
     * @param row 行索引（从1开始，Excel格式）
     * @param col 列索引（从1开始，Excel格式）
     * @return 当前监听器实例，支持链式调用
     */
    public FastExcelCellListener addTargetCell(int row, int col) {
        if (row < 1 || col < 1) {
            throw new BadRequestException("行列索引必须从1开始");
        }
        targetCells.add(new CellPosition(row, col));
        return this;
    }

    @Override
    public void invoke(Map<Integer, String> rowData, AnalysisContext context) {
        // 如果所有目标单元格已读取完毕，直接返回
        if (allCellsRead) {
            return;
        }
        // EasyExcel 的行索引从0开始，转换为Excel格式（从1开始）
        int currentRowIndex = context.readRowHolder().getRowIndex() + 1;

        // 检查当前行是否包含目标单元格
        for (CellPosition targetCell : targetCells) {
            if (currentRowIndex == targetCell.row) {
                // 列索引需要减1转换为0-based
                String cellValue = rowData.get(targetCell.col - 1);
                if (cellValue != null) {
                    cellValues.put(targetCell, cellValue);
                }
            }
        }

        // 检查是否所有目标单元格都已读取
        if (cellValues.size() == targetCells.size()) {
            allCellsRead = true;
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 可根据需要添加逻辑
    }

    /**
     * 获取指定单元格的值
     *
     * @param row 行索引（从1开始，Excel格式）
     * @param col 列索引（从1开始，Excel格式）
     * @return 单元格值，如果不存在返回null
     */
    public String getCellValue(int row, int col) {
        return cellValues.get(new CellPosition(row, col));
    }

    /**
     * 获取所有单元格值（字符串格式的key）
     *
     * @return 所有单元格值的Map，key为"row-col"格式
     */
    public Map<String, String> getAllCellValues() {
        Map<String, String> result = new HashMap<>();
        cellValues.forEach((pos, value) ->
                result.put(pos.row + "-" + pos.col, value));
        return result;
    }

    /**
     * 单元格位置封装类
     */
    public static class CellPosition {
        private final int row;
        private final int col;

        public CellPosition(int row, int col) {
            this.row = row;
            this.col = col;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            CellPosition that = (CellPosition) o;
            return row == that.row && col == that.col;
        }

        @Override
        public int hashCode() {
            return Objects.hash(row, col);
        }

        @Override
        public String toString() {
            return "(" + row + "," + col + ")";
        }
    }

}
