package com.ruoyi.ext.api.validate;

import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Date;

/**
 * 自定义时间字符串校验注解实现
 * 
 * @author ruoyi
 */
public class DateValidator implements ConstraintValidator<DateV, String>
{

    private String pattern;
    private String[] rules = {
            "before",
            "after",
            "beforeAndNow",
            "afterAndNow",
    };
    private String rule;
    private DateV dateV;

    @Override
    public void initialize(DateV constraintAnnotation) {
        dateV = constraintAnnotation;
        pattern = constraintAnnotation.pattern();
        rule = constraintAnnotation.rule();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isBlank(value)){
            return true;
        }
        boolean isHasRule = false;
        if (!StringUtils.isBlank(rule)){
            for (String r : rules) {
                if (r.equals(rule)){
                    isHasRule = true;
                }
            }
        }
        try {
            Date date = DateUtil.parse(value, pattern);
            if (!isHasRule){
                long diff = date.getTime() - new Date().getTime();
                switch (rule){
                    case "before":
                        if (diff >= 0){
                            context.disableDefaultConstraintViolation();
                            context.buildConstraintViolationWithTemplate("日期必须在现在之前");
                            return false;
                        }
                        break;
                    case "after":
                        if (diff <= 0){
                            context.disableDefaultConstraintViolation();
                            context.buildConstraintViolationWithTemplate("日期必须在现在之后");
                            return false;
                        }
                        break;
                    case "beforeAndNow":
                        if (diff > 0){
                            context.disableDefaultConstraintViolation();
                            context.buildConstraintViolationWithTemplate("日期必须在现在或者现在之前");
                            return false;
                        }
                        break;
                    case "afterAndNow":
                        if (diff < 0){
                            context.disableDefaultConstraintViolation();
                            context.buildConstraintViolationWithTemplate("日期必须在现在或者现在之后");
                            return false;
                        }
                        break;
                }

                return true;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}