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

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.PhoneUtil;

import com.cf.imes.framework.common.constants.ResourceBundleConstants;
import com.cf.imes.framework.common.util.i18n.core.util.ResourceBundleUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

public class TelephoneValidator implements ConstraintValidator<Telephone, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 如果手机号为空，默认不校验，即校验通过
        if (CharSequenceUtil.isEmpty(value)) {
            return true;
        }
        String defaultConstraintMessageTemplate = context.getDefaultConstraintMessageTemplate();
        Locale locale = LocaleContextHolder.getLocale();
        defaultConstraintMessageTemplate = ResourceBundleUtils.getMessage(ResourceBundleConstants.MESSAGE_ENUM_PATH, defaultConstraintMessageTemplate, defaultConstraintMessageTemplate, locale);

        // 校验不通过，自定义提示语句（因为，注解上的 value 是枚举类，无法获得枚举类的实际值）
        context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值
        context.buildConstraintViolationWithTemplate(defaultConstraintMessageTemplate).addConstraintViolation(); // 重新添加错误提示语句

        // 校验手机
        return PhoneUtil.isTel(value) || PhoneUtil.isPhone(value);
    }

}
