package org.sky.scientific.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.sky.core.log.exception.ServiceException;
import org.sky.scientific.utils.ImportResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Data
@Slf4j
public abstract class BaseReadListener implements ReadListener<Map<Integer, String>> {
	public List<ImportResult<Object>> resultList = new ArrayList<>();
	public List<Object> dataList = ListUtils.newArrayList();
	private final AtomicInteger successCount = new AtomicInteger(0);
	private final AtomicInteger errorCount = new AtomicInteger(0);

	@Override
	public void doAfterAllAnalysed(AnalysisContext analysisContext) {
		log.info("===每月领料燃料动力明细-专利解析完成 ===");
		log.info("成功: {}条，失败：{}条", successCount.get(), errorCount.get());
		// 打印错误详情
		if (errorCount.get() > 0) {
			StringBuilder sb = new StringBuilder();
			sb.append("成功: ").append(successCount.get()).append("条，失败：").append(errorCount.get()).append("条");
			log.info("错误详情:");
			sb.append("\n错误详情");
			for (ImportResult<Object> result : resultList) {
				if (!result.isSuccess()) {
					sb.append("\n第").append(result.getRowIndex()).append("行: ").append(String.join("; ", result.getErrors()));
					log.info("第{}行: {}", result.getRowIndex(), String.join("; ", result.getErrors()));
				}
			}
			throw new ServiceException(sb.toString());
		}
	}

	public void incrementSuccessCount() {
		successCount.incrementAndGet();
	}

	public void incrementErrorCount() {
		errorCount.incrementAndGet();
	}

}
