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}$");

    /**
     * 校验单条记录，返回错误信息（不抛异常）。
     * 用于批量写入场景，单条校验失败不影响其他记录。
     *
     * @return 校验通过返回 null，否则返回错误信息
     */
    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.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");
        }

        // 校验金额：至少一个金额大于0
        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("投诉罚款金额(complaintFineAmount)和违规乐捐金额(violationDonationAmount)至少需要一项大于0");
        }

        // 校验金额非负
        if (fineAmount != null && fineAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("投诉罚款金额(complaintFineAmount)不能为负数");
        }
        if (donationAmount != null && donationAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("违规乐捐金额(violationDonationAmount)不能为负数");
        }
    }
}
