package com.sinosig.core.module.valuerule.validator.cid;

import lombok.extern.slf4j.Slf4j;
import com.sinosig.util.valuerule.DefaultValueRule;
import com.sinosig.util.valuerule.VRCondition;
import com.sinosig.util.valuerule.condition.*;
import com.sinosig.core.module.valuerule.anno.cid.CIDSyxdeCheckDBE;
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;


/**
 * 值规则注解解析类
 * 实体：CID
 * 属性：Syxde
 * 值规则：CheckDBE
 * 值规则信息：截止日期与生效日期相差不能超过一年！
 */
@Slf4j
@Component("CIDSyxdeCheckDBEValidator")
public class CIDSyxdeCheckDBEValidator implements ConstraintValidator<CIDSyxdeCheckDBE, Timestamp>,Validator {
    private static final String MESSAGE = "值规则校验失败：【截止日期与生效日期相差不能超过一年！】";

    @Override
    public boolean isValid(Timestamp 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((Timestamp) o)){
                errors.reject(MESSAGE);
            }
        }
    }

    public boolean doValidate(Timestamp value) {
        VRGroupCondition<Timestamp> groupCondition =
                new VRGroupCondition<>("默认组", false, "截止日期与生效日期相差不能超过一年！", value)
                    .init(true)
                ;
       return groupCondition.isValid();
    }
}

