package com.cf.imes.framework.common.validation;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang3.StringUtils;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * @author Gqr
 * @since 2024/10/17 11:27
 */
public class NumberValidator implements ConstraintValidator<NumberValid, Number> {
    private static final String ZERO = "0";

    private static final String GREATER_THAN_ZERO_NOTIFICATION = "%s必须大于0";

    private static final String FLOAT_NUMBER_LENGTH_ERROR_NOTIFICATION = "%s长度不合法，总长度不超过%d位，小数点后不超过%d位";

    private String name;

    private int integer;

    private int fraction;

    @Override
    public void initialize(NumberValid constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.name = constraintAnnotation.name();
        this.integer = constraintAnnotation.integer();
        this.fraction = constraintAnnotation.fraction();
        ;
    }

    @Override
    public boolean isValid(Number value, ConstraintValidatorContext context) {
        // 空的不校验，由原生@NotNull之类的进行判断
        if (ObjectUtil.isNull(value)) {
            return true;
        }
        // 提示信息
        String notification = null;
        if (value instanceof Integer) {
            notification = handleInteger(value.intValue());
        } else if (value instanceof Long) {
            notification = handleLong(value.longValue());
        } else if (value instanceof Double) {
            notification = handleDouble(value.doubleValue());
        } else if (value instanceof BigDecimal) {
            notification = handleBigDecimal((BigDecimal) value);
        }
        if (StringUtils.isNotEmpty(notification)) {
            context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值
            context.buildConstraintViolationWithTemplate(notification).addConstraintViolation();
            return false;
        }
        return true;
    }

    /**
     * 校验整型
     *
     * @param value
     * @return
     */
    private String handleInteger(Integer value) {
        if (value < Integer.parseInt(ZERO)) {
            return String.format(GREATER_THAN_ZERO_NOTIFICATION, name);
        }
        return null;
    }

    /**
     * 校验长整型
     *
     * @param value
     * @return
     */
    private String handleLong(Long value) {
        if (value < Long.parseLong(ZERO)) {
            return String.format(GREATER_THAN_ZERO_NOTIFICATION, name);
        }
        return null;
    }

    /**
     * 校验浮点型
     *
     * @param value
     * @return
     */
    private String handleDouble(Double value) {
        if (value < Double.parseDouble(ZERO)) {
            return String.format(GREATER_THAN_ZERO_NOTIFICATION, name);
        }
        // 处理科学计数法,保留小数点后四位
        DecimalFormat decimalFormat = new DecimalFormat("#.####");
        String valueString = decimalFormat.format(value);

        String[] split = valueString.split("\\.");
        // 获取小数点前的位数
        int integerPartLength = split[0].length();
        // 获取小数点后的位数
        int fractionalPartLength = 0;
        if (split.length == 2) {
            fractionalPartLength = split[1].length();
        }

        // 总位数不超过 8 位，小数点后位数不超过 3 位
        if (integerPartLength > integer || fractionalPartLength > fraction) {
            return String.format(FLOAT_NUMBER_LENGTH_ERROR_NOTIFICATION, name, integer, fraction);
        }
        return null;
    }

    /**
     * 校验大浮点型
     *
     * @param value
     * @return
     */
    private String handleBigDecimal(BigDecimal value) {
        if (value.compareTo(BigDecimal.ZERO) < 0) {
            return String.format(GREATER_THAN_ZERO_NOTIFICATION, name);
        }

        String[] split = value.toPlainString().split("\\.");
        // 获取小数点前的位数
        int integerPartLength = split[0].length();
        // 获取小数点后的位数
        int fractionalPartLength = 0;
        if (split.length == 2) {
            fractionalPartLength = split[1].length();
        }

        // 总位数不超过 8 位，小数点后位数不超过 3 位
        if (integerPartLength > integer || fractionalPartLength > fraction) {
            return String.format(FLOAT_NUMBER_LENGTH_ERROR_NOTIFICATION, name, integer, fraction);
        }
        return null;
    }
}
