package com.sckw.excel.utils;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;

import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * <p>
 *
 *
 * @author LengFaQiang
 * @version v1
 * @create 2021-04-26 16:31:11
 * @copyright
 */
public class ValidDataUtil {

    /**全属性验证器*/
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 检查数据格式
     * @param object 需要验证的带有{@link javax.validation.constraints}注解的实体
     * @param <T> the type of the object to validate
     * @return 是否验证通过 {@link Result} 不通过时{@code getMsg()}获取失败信息
     */
    @Nullable
    public static <T> String valid(@NonNull T object) {
        Set<ConstraintViolation<T>> validateSet = validator.validate(object);
        if (!CollectionUtils.isEmpty(validateSet)) {
            return validateSet.stream().map(validate -> validate.getMessage()).collect(Collectors.joining(","));
        }
        return null;
    }
}