package com.lutao.utils;


import com.lutao.annotate.Validation;
import lombok.extern.slf4j.Slf4j;

import javax.xml.bind.ValidationException;
import java.lang.reflect.Field;

@Slf4j
public class Validator {
    public static void validate(Object entity) throws ValidationException {
        Class<?> clazz = entity.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(Validation.class)) {
                field.setAccessible(true);

                Validation validation = field.getAnnotation(Validation.class);
                String message = validation.message();

                try {
                    Object value = field.get(entity);

                    // 进行字段校验逻辑，根据需要自定义校验规则
                    if (value == null || value.toString().isEmpty()) {
                        log.info(entity.toString());
                        log.error(message+"::字段"+field+"="+value);
                        throw new ValidationException(message);
                    }
                    // 其他校验规则...

                } catch (IllegalAccessException e) {
                    // 处理异常情况
                }
            }
        }
    }
}
