package com.cf.imes.module.executor.util.fileConversion.admin.files.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
public final class ExcelListener extends AnalysisEventListener<Map<Integer, String>> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
//    private static final int BATCH_COUNT = 100;
//    private List<Map<Integer, String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<Map<Integer, String>> cachedDataList = new ArrayList<Map<Integer, String>>();
    private boolean stopParsing = false; // 添加一个标志位用于控制是否停止解析数据

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        log.info("解析到一条数据: {}", JSON.toJSONString(data));

        if (data.get(0) != null && data.get(0).equals("***")) {
            log.info("遇到指定数据 ***, 停止写入！");
            stopParsing = true;
        }

        if (!stopParsing) {
            data.entrySet().removeIf(entry -> Objects.isNull(entry.getValue()));
            cachedDataList.add(data);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！");
    }

    public List<Map<Integer, String>> getDataLists() {
        return cachedDataList;
    }
}