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.core.tool.utils.Func;
import org.sky.scientific.pojo.entity.XmTechnicianEntity;
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 class XmTechnicianImportListener implements ReadListener<Map<Integer, String>> {

	private List<ImportResult<XmTechnicianEntity>> resultList = new ArrayList<>();
	private List<XmTechnicianEntity> dataList = ListUtils.newArrayList();
	private final AtomicInteger successCount = new AtomicInteger(0);
	private final AtomicInteger errorCount = new AtomicInteger(0);

	@Override
	public void invoke(Map<Integer, String> map, AnalysisContext context) {
		int rowIndex = context.readRowHolder().getRowIndex() + 1;

		ImportResult<XmTechnicianEntity> result = convertAndValidate(map, rowIndex);
		resultList.add(result);
		if (result.isSuccess()) {
			dataList.add(result.getData());
			successCount.incrementAndGet();
		} else {
			errorCount.incrementAndGet();
		}
	}

	private ImportResult<XmTechnicianEntity> convertAndValidate(Map<Integer, String> data, int rowIndex) {

		List<String> errors = new ArrayList<>();

		XmTechnicianEntity excel = new XmTechnicianEntity();
		excel.setXmbh(data.get(1));
		if(Func.isBlank(excel.getXmbh())){
			errors.add("项目编号不能为空");
		}
		excel.setNumber(data.get(4));
		excel.setIdCard(data.get(5));
		if(Func.isAnyBlank(excel.getNumber(), excel.getIdCard())){
			errors.add("工号和身份证号不能同时为空");
		}
		return ImportResult.success(rowIndex, excel);
	}

	@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<XmTechnicianEntity> 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 int getSuccessCount() {
		return successCount.get();
	}

	public int getErrorCount() {
		return errorCount.get();
	}
}
