package cn.ibizlab.r7.runtime.core.r7rt_base.valuerule.validator.loginaccount;

import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.r7.runtime.util.valuerule.DefaultValueRule;
import cn.ibizlab.r7.runtime.util.valuerule.VRCondition;
import cn.ibizlab.r7.runtime.util.valuerule.condition.*;
import cn.ibizlab.r7.runtime.core.r7rt_base.valuerule.anno.loginaccount.LoginAccountPwdValueRule;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import java.math.BigDecimal;


/**
 * 值规则注解解析类
 * 实体：LoginAccount
 * 属性：Pwd
 * 值规则：ValueRule
 * 值规则信息：(大写规则。)
 */
@Slf4j
@Component("LoginAccountPwdValueRuleValidator")
public class LoginAccountPwdValueRuleValidator implements ConstraintValidator<LoginAccountPwdValueRule, String>,Validator {
    private static final String MESSAGE = "值规则校验失败：【(大写规则。)】";

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean isValid = doValidate(value);
        if(!isValid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(MESSAGE)
                    .addConstraintViolation();
        }
        return doValidate(value);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    @Override
    public void validate(Object o, Errors errors) {
        if( o!=null && supports(o.getClass())){
            if (!doValidate((String) o)){
                errors.reject(MESSAGE);
            }
        }
    }

    public boolean doValidate(String value) {
        VRGroupCondition<String> groupCondition =
                new VRGroupCondition<>("默认组", false, "(大写规则。)", value)
                    .init(true)

                    .add(new VRSysValueRuleCondition<>("[系统值规则]由26个英文字母的大写组成的字符串", false, "(大写规则。)", value))


                    .add(new VRSimpleCondition<>("[常规条件] 等于(=) (AAA)", false, "(大写规则。)", value)
                                        //操作类型，参数类型，参数值
                            .init(VRSimpleCondition.OpType.EQ,"","AAA"))

                ;
       return groupCondition.isValid();
    }
}

