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.DateUtil;
import org.sky.scientific.excel.CgRjzzqExcel;
import org.sky.scientific.utils.ImportResult;
import org.sky.scientific.utils.ValidationUtils;

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


@Data
@Slf4j
public class CgRjzzqImportListener implements ReadListener<Map<Integer, String>> {

	private List<ImportResult<CgRjzzqExcel>> resultList = new ArrayList<>();
	private List<CgRjzzqExcel> 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<CgRjzzqExcel> result = convertAndValidate(map, rowIndex);
		resultList.add(result);
		if (result.isSuccess()) {
			dataList.add(result.getData());
 			successCount.incrementAndGet();
		} else {
			errorCount.incrementAndGet();
		}
	}

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

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

		CgRjzzqExcel excel = new CgRjzzqExcel();
		excel.setXh(data.get(0));
		excel.setRjmc(data.get(1));
		excel.setRjjc(data.get(2));
		excel.setBbh(data.get(3));
		excel.setDjh(data.get(4));
		excel.setKfwcrq(ValidationUtils.safeParseDate(data.get(5), DateUtil.PATTERN_DATE));
		if (excel.getKfwcrq() == null) {
			errors.add("开发完成日期为空或格式错误，yyyy-MM-dd");
		}
		excel.setScfbrq(ValidationUtils.safeParseDate(data.get(6), DateUtil.PATTERN_DATE));
		if (excel.getScfbrq() == null) {
			errors.add("首次发布日期为空或格式错误，yyyy-MM-dd");
		}
		excel.setDjpzrq(ValidationUtils.safeParseDate(data.get(7), DateUtil.PATTERN_DATE));
		excel.setQdfs(data.get(8));
		excel.setXmmc(data.get(9));
		excel.setXmbh(data.get(10));

		errors.addAll(ValidationUtils.validate(excel));
		if (!errors.isEmpty()) {
			return ImportResult.error(rowIndex, errors, data.toString());
		}
		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<CgRjzzqExcel> 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();
	}
}
