package cn.qinys.platform.base.annotation;


import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import org.apache.commons.lang3.StringUtils;


import java.lang.annotation.*;

/**
 * 密码校验 注解
 */
@Constraint(validatedBy = PasswordMatches.PassWordValidator.class)
@Documented
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PasswordMatches {
    // 正则表达式
    String regexp() default "";

    // 校验不通过时的提示信息
    String message() default "请输入8-20位的密码，必须包含数字和大小写字母以及特殊符号";

    // 分组
    Class<?>[] groups() default {};

    // 集合校验
    Class<? extends Payload>[] payload() default {};

    class PassWordValidator implements ConstraintValidator<PasswordMatches, String> {
        //private String regexp = "^(?![0-9]+$)(?![a-zA-Z~!@#$%^*]+$)[0-9A-Za-z~!@#$%^*]{8,20}$";
        private String regexp = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[.=#?!@$%^&+*-]).{8,}$";
        @Override
        public void initialize(PasswordMatches constraintAnnotation) {
            if (StringUtils.isNotBlank(constraintAnnotation.regexp())) {
                this.regexp = constraintAnnotation.regexp();
            }
        }

        @Override
        public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
            return !StringUtils.isBlank(s) && s.matches(regexp);
        }
    }
}