package com.bcxin.infrastructure.offices.impls;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.bcxin.Infrastructures.components.models.ExcelModelAbstract;

import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Consumer;

/**
 * 自定义分页读取excel数据
 * @param <T>
 */
public class ExcelDataAnalysisEventListener<T extends ExcelModelAbstract> extends AnalysisEventListener<T> {
    private final Consumer<Collection<T>> consumer;
    private final int pageSize;
    private final Collection<T> cachedData;

    public ExcelDataAnalysisEventListener(Consumer<Collection<T>> consumer, int pageSize) {
        this.consumer = consumer;
        this.pageSize = pageSize;
        this.cachedData = new ArrayList<>();
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        this.cachedData.add(t);

        if (this.cachedData.size() > pageSize) {
            this.consumer.accept(this.cachedData);
            this.cachedData.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        this.consumer.accept(this.cachedData);
    }
}
