package com.securitycontrol.common.security.utils;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;

/**
 * @description: <br/>
 * 通用Server validation方法
 * <p>
 * <br/>
 * @author: Qz1997
 * @create 2021/2/9 14:41
 */
@SuppressWarnings("unused")
@Component(value = "ValidatorsUtils")
public final class ValidatorsUtils {
    @Resource
    private Validator validator;

    /**
     * 验证实体
     *
     * @param obj 实体
     * @param <T> 实体类类型
     * @return 结果
     */
    public <T> String valid(T obj) {
        return this.valid(obj, new Class<?>[]{});
    }

    /**
     * 验证实体
     *
     * @param obj   实体
     * @param group 实体组
     * @param <T>   实体类类型
     * @return 结果
     */
    public <T> String valid(T obj, Class<?>... group) {
        Set<ConstraintViolation<T>> violations;
        if (ArrayUtils.isEmpty(group)) {
            violations = validator.validate(obj);
        } else {
            violations = validator.validate(obj, group);
        }
        if (CollectionUtils.isNotEmpty(violations)) {
            for (ConstraintViolation<T> constraintViolation : violations) {
                return constraintViolation.getMessage();
            }
        }
        return null;
    }

    /**
     * 校验list
     *
     * @param objList list
     * @param <T>     实体类类型
     * @return 结果
     */
    public <T> String validList(List<T> objList) {
        return this.validList(objList, new Class<?>[]{});
    }

    /**
     * 校验list
     *
     * @param objList list
     * @param group   组
     * @param <T>     实体类类型
     * @return 结果
     */
    public <T> String validList(List<T> objList, Class<?>... group) {
        if (CollectionUtils.isEmpty(objList)) {
            return "对象空";
        }
        String result;
        for (T t : objList) {
            if (ArrayUtils.isEmpty(group)) {
                result = this.valid(t);
            } else {
                result = this.valid(t, group);
            }
            if (!StringUtils.isBlank(result)) {
                return result;
            }
        }
        return null;
    }
}


