package com.zd.common.core.valid;

import com.zd.common.core.exception.ServiceException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * @Author: zhoupan
 * @Date: 2021/09/03/9:27
 * @Description:
 */
public class EnumStringValidator implements ConstraintValidator<EnumString, Object> {
    private String[] codes;

    @Override
    public boolean isValid(Object s, ConstraintValidatorContext constraintValidatorContext) {
        if (s == null) return true;
        //不为null再验证，空交给notNull去验证
        if (s instanceof Integer) {
            return Arrays.stream(codes).filter(a -> (String.valueOf(s)).equals(a)).map(a -> Boolean.TRUE).findFirst().orElse(Boolean.FALSE);
        } else {
            return Arrays.stream(codes).filter(a -> ((String) s).equals(a)).map(a -> Boolean.TRUE).findFirst().orElse(Boolean.FALSE);
        }

    }

    @Override
    public void initialize(EnumString constraintAnnotation) {

        Class<?> enumClass = constraintAnnotation.value();
        if (enumClass != null) {
            try {
                Method method = enumClass.getMethod("values");
//                Method method = enumClass.getMethod("codes");
                ValidEunm[] validEunms = (ValidEunm[]) method.invoke(null);
                codes = Stream.of(validEunms).map(a -> a.codes()).toArray(String[]::new);
            } catch (Exception e) {
                throw new ServiceException("枚举验证参数" + enumClass.getName() + "不是一个可验证的枚举类型！");
            }
        } else {
            codes = constraintAnnotation.stringValue();

        }

    }
}
