package com.cf.imes.module.executor.validation.manage.parts;

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

/**
 * 数组校验
 */
public class PartsNumberValidator implements ConstraintValidator<PartsNumberValid, Object> {

    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长度不合法，总长度不超过8位，小数点后不超过3位";

    private String name;

    private int integer;

    private int fraction;

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

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        // 空的不校验，由原生@NotNull之类的进行判断
        if (value == null) {
            return true;
        }

        if (value instanceof Number[]) {
            return validateArray((Number[]) value, context);
        } else if (value instanceof Number) {
            return validateSingleValue((Number) value, context);
        }

        return true;
    }

    private boolean validateArray(Number[] values, ConstraintValidatorContext context) {
        for (Number value : values) {
            if (!validateSingleValue(value, context)) {
                return false;
            }
        }
        return true;
    }

    private boolean validateSingleValue(Number value, ConstraintValidatorContext context) {
        // 提示信息
        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 (notification != null) {
            context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值
            context.buildConstraintViolationWithTemplate(notification).addConstraintViolation();
            return false;
        }
        return true;
    }

    private String handleInteger(Integer value) {
        if (value < Integer.parseInt(ZERO)) {
            return String.format(GREATER_THAN_ZERO_NOTIFICATION, name);
        }
        return null;
    }

    private String handleLong(Long value) {
        if (value < Long.parseLong(ZERO)) {
            return String.format(GREATER_THAN_ZERO_NOTIFICATION, name);
        }
        return null;
    }

    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 > 1) {
            fractionalPartLength = split[1].length();
        }

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

    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 > 1) {
            fractionalPartLength = split[1].length();
        }

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