package com.docus.server.common.util;

import com.docus.server.common.bean.Result;
import com.docus.server.common.exception.RabbitMQExceptionUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.util.List;

/**
 * Copyright © 2018 五月工作室. All rights reserved.
 *
 * @Project: rabbitmq
 * @ClassName: ValidateUtils
 * @Package: com.docus.viewtaskcollect.common.util
 * @author: amos
 * @Description: 校验工具类
 * @date: 2019/6/28 0028 下午 15:46
 * @Version: V1.0
 */
public class ValidateUtils {
    /**
     * 校验对象<p/>
     * 根据对象中的@NotNull注解来判断
     *
     * @param object
     * @return
     */
    public static Result validate(Object object) {
        if (StringUtils.isEmpty(object)) {
            RabbitMQExceptionUtils.throwRabbitMQException();
        }

        List<Field> fields = ClassUtils.getAllField(object.getClass());
        return validateFields(fields, object);
    }

    /**
     * 校验属性中是否存在空的数据
     *
     * @param list
     * @param data
     * @return
     */
    public static Result validateFields(List<Field> list, Object data) {
        if (CollectionUtils.isEmpty(list)) {
            RabbitMQExceptionUtils.throwRabbitMQException("获取不到对象的属性");
        }
        for (Field field : list) {
            if (!field.isAnnotationPresent(NotNull.class)) {
                continue;
            }
            NotNull notNull = field.getAnnotation(NotNull.class);
            boolean isAccessable = field.isAccessible();
            try {
                field.setAccessible(Boolean.TRUE);
                Object value = field.get(data);
                if (StringUtils.isEmpty(value)) {
                    return ResultWapper.fail(notNull.message());
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } finally {
                field.setAccessible(isAccessable);
            }
        }
        return ResultWapper.success();
    }
}
