package com.yunfeiyun.agmp.common.framework.validator;

import com.yunfeiyun.agmp.common.core.domain.model.LoginBody;
import com.yunfeiyun.agmp.common.framework.validator.annotation.PasswordEqual;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 密码校验
 */
public class PasswordValidator implements ConstraintValidator<PasswordEqual, LoginBody> {

    private int max;

    private int min;

    /**
     * 初始化方法
     * @param constraintAnnotation
     */
    @Override
    public void initialize(PasswordEqual constraintAnnotation) {

        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    /**
     * 校验的方法
     * @param loginBody
     * @param constraintValidatorContext
     * @return
     */
    @Override
    public boolean isValid(LoginBody loginBody, ConstraintValidatorContext constraintValidatorContext) {
        if(loginBody == null) {
            return false;
        }
        String password = loginBody.getPassword();
//        if(password.length() < min || password.length() > max) {
//            this.setErrorMessage(constraintValidatorContext, "密码的长度不能少于"+this.min+"个字符， 不能超过"+this.max+"个字符");
//            return false;
//        }
//        boolean match = password.equals(password2);
//        if(!match) {
//            this.setErrorMessage(constraintValidatorContext, "两次输入的密码不一致");
//        }

        return true;
    }

    // 设置校验失败的提示消息
    private void setErrorMessage(ConstraintValidatorContext constraintValidatorContext, String errorMessage) {
        constraintValidatorContext.disableDefaultConstraintViolation();
        constraintValidatorContext
                .buildConstraintViolationWithTemplate(errorMessage)
                .addConstraintViolation();
    }
}
