package cn.iocoder.yudao.module.system.util;

import cn.iocoder.yudao.module.system.controller.admin.biz.vo.ImportResultVO;

import java.util.ArrayList;
import java.util.List;

public class ImportUtil {
    public static void addFailure(List<ImportResultVO.RowError> failures,
                                   Integer rowNum,
                                   String elderName,
                                   String contractNumber,
                                   String reason) {
        addFailure(failures, rowNum, elderName, contractNumber, reason, null);
    }

    public static void addFailure(List<ImportResultVO.RowError> failures,
                                   Integer rowNum,
                                   String elderName,
                                   String contractNumber,
                                   String reason,
                                   Exception ex) {
        if (failures == null) {
            throw new IllegalArgumentException("failures 不能为空");
        }
        ImportResultVO.RowError error = new ImportResultVO.RowError();
        error.setRowNum(rowNum);
        error.setElderName(trimToNull(elderName));
        error.setContractNumber(trimToNull(contractNumber));
        error.setReason(trimToNull(reason) == null ? "未知错误" : reason);

        // 避免把超长堆栈直接返回前端：只放简述
        if (ex != null) {
            error.setException(ex.getClass().getSimpleName() + ": " + safeMsg(ex.getMessage()));
        }
        failures.add(error);
    }

    public static ImportResultVO buildResult(int successCount,
                                              List<ImportResultVO.RowError> failures) {
        ImportResultVO result = new ImportResultVO();
        result.setSuccessCount(Math.max(successCount, 0));
        result.setFailures(failures == null ? new ArrayList<>() : failures);
        result.setFailureCount(result.getFailures().size());
        return result;
    }

    private static String trimToNull(String s) {
        if (s == null) return null;
        String t = s.trim();
        return t.isEmpty() ? null : t;
    }

    private static String safeMsg(String msg) {
        if (msg == null) return null;
        // 你也可以限制长度，避免数据库异常信息过长
        return msg.length() > 500 ? msg.substring(0, 500) : msg;
    }
}
