package com.yonge.cooleshow.biz.dal.valid.impl;


import com.yonge.cooleshow.biz.dal.valid.EnumValid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author: cy
 * @date: 2022/4/2 14:53
 */
public class EnumValidtor implements ConstraintValidator<EnumValid, Object> {

    String vaildField;
    Class<?>[] cls; //枚举类

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        cls = constraintAnnotation.target();
        vaildField = constraintAnnotation.vaildField();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value != null && value.toString().length() > 0 && cls.length > 0) {
            for (Class<?> cl : cls) {
                try {
                    if (cl.isEnum()) {
                        //枚举类验证
                        Object[] objs = cl.getEnumConstants();
                        Method method = cl.getMethod("name");
                        for (Object obj : objs) {
                            Object code = method.invoke(obj, null);
                            if (value.equals(code.toString())) {
                                return true;
                            }
                        }
                        Method codeMethod = cl.getMethod(vaildField);
                        for (Object obj : objs) {
                            Object code = codeMethod.invoke(obj, null);
                            if (value.toString().equals(code.toString())) {
                                return true;
                            }
                        }
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return true;
        }
        return false;
    }

}

