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

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.cf.imes.framework.common.util.validation.ValidationUtils;
import org.apache.commons.lang3.StringUtils;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

public class MobileValidator implements ConstraintValidator<Mobile, String> {

    private String[] ignoreWhenCheck;

    private String message;

    @Override
    public void initialize(Mobile constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.ignoreWhenCheck = constraintAnnotation.ignoreWhenCheck();
        this.message = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (ArrayUtil.isNotEmpty(ignoreWhenCheck) && ArrayUtil.contains(ignoreWhenCheck, value)) {
            return true;
        }
        // 如果手机号为空，默认不校验，即校验通过
        if (CharSequenceUtil.isEmpty(value)) {
            return true;
        }
        if (StringUtils.isNotEmpty(message)) {
            context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值
            context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        }
        // 校验手机
        return ValidationUtils.isMobile(value);
    }

}
