package com.crunii.micro.common.utils;

import com.crunii.micro.common.exception.BusinessException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 实体类校验注解工具类
 *
 * @author xiangjunming
 * @date 2023/12/25
 */
public class ValidatorUtils {

    private static Validator validator;


    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    public static String validateMsg(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            return constraintViolations.stream().findFirst().get().getMessage();
        }
        return null;
    }
    public static String validateMsgs(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            return constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("; "));
        }
        return null;
    }


    public static void validateMsgException(Object object, Class<?>... groups) throws BusinessException {
        String errorMsg = validateMsg(object, groups);
        if(errorMsg != null){
            throw new BusinessException(errorMsg);
        }
    }

    public static void validateMsgsException(Object object, Class<?>... groups) throws BusinessException {
        String errorMsgs = validateMsgs(object, groups);
        if(errorMsgs != null){
            throw new BusinessException(errorMsgs);
        }
    }
}
