package com.kingdee.eas.custom.integration.riskcontrol.validator;

import com.kingdee.eas.custom.integration.riskcontrol.dto.ComplaintDonationDeductRequest;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.regex.Pattern;

/**
 * 投诉乐捐扣除校验器。
 */
public class ComplaintDonationDeductValidator {

    private static final Pattern DATE_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");

    /**
     * 校验单条记录，返回错误消息（不抛异常）。
     * 用于批量写入场景，校验失败不影响其他记录。
     */
    public static String validateAndGetError(ComplaintDonationDeductRequest request) {
        try {
            validate(request);
        } catch (IllegalArgumentException e) {
            return e.getMessage();
        }
        return null;
    }

    private static void validate(ComplaintDonationDeductRequest request) {
        if (request == null) throw new IllegalArgumentException("请求体不能为空");

        if (StringUtils.isBlank(request.getBizId()))
            throw new IllegalArgumentException("业务单据号(bizId)不能为空");

        if (request.getBizId().length() > 80)
            throw new IllegalArgumentException("业务单据号(bizId)长度不能超过80位");

        if (StringUtils.isBlank(request.getPersonNumber()))
            throw new IllegalArgumentException("人员编号(personNumber)不能为空");

        if (StringUtils.isBlank(request.getViolationTypeCode()))
            throw new IllegalArgumentException("违规类型编码(violationTypeCode)不能为空");

        if (StringUtils.isBlank(request.getVoucherDate()))
            throw new IllegalArgumentException("凭证日期(voucherDate)不能为空");

        if (!DATE_PATTERN.matcher(request.getVoucherDate()).matches())
            throw new IllegalArgumentException("凭证日期(voucherDate)格式不正确，正确格式为: yyyy-MM-dd");

        BigDecimal fineAmount = request.getComplaintFineAmount();
        BigDecimal donationAmount = request.getViolationDonationAmount();

        boolean hasFine = fineAmount != null && fineAmount.compareTo(BigDecimal.ZERO) > 0;
        boolean hasDonation = donationAmount != null && donationAmount.compareTo(BigDecimal.ZERO) > 0;

        if (!hasFine && !hasDonation)
            throw new IllegalArgumentException("投诉罚款金额和违规捐赠金额至少需要一项大于0");

        if (fineAmount != null && fineAmount.compareTo(BigDecimal.ZERO) < 0)
            throw new IllegalArgumentException("投诉罚款金额不能为负数");
        if (donationAmount != null && donationAmount.compareTo(BigDecimal.ZERO) < 0)
            throw new IllegalArgumentException("违规捐赠金额不能为负数");
    }
}
