package com.jianshui.common.utils;

import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.exception.jianshui.JianshuiParamErrorException;
import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import java.util.Set;

/**
 * @Description
 * @Author 巩权林
 * @Date 2022-01-10 10:54
 **/
public class ValidateUtils {

    /**
     * validate主动校验方式
     *
     * @param validateObject 进行校验的对象
     * @param <T>            传递的校验类型
     * @throws JianshuiParamErrorException 服务异常
     */
    public static <T> void validate(@Valid T validateObject, Companyservice companyservice, String serviceKey) throws RuntimeException {
        Set<ConstraintViolation<@Valid T>> validateSet = Validation
                .buildDefaultValidatorFactory()
                .getValidator()
                .validate(validateObject);
        if (CollectionUtils.isNotEmpty(validateSet)) {
            for (ConstraintViolation<@Valid T> i : validateSet) {
                throw new JianshuiParamErrorException(i.getPropertyPath() + i.getMessage(), companyservice, serviceKey);
            }
        }
    }


    /**
     * 单纯参数校验
     * @param validateObject
     * @param <T>
     * @throws RuntimeException
     */
    public static <T> void validate(@Valid T validateObject) throws RuntimeException {
        validate(validateObject, null);
    }

    /**
     * validate主动校验方式
     *
     * @param validateObject 进行校验的对象
     * @param <T>            传递的校验类型
     * @param preMsg         错误信息的前部分要追加的内容
     * @throws RuntimeException 服务异常
     */
    public static <T> void validate(@Valid T validateObject, String preMsg) throws RuntimeException {
        Set<ConstraintViolation<@Valid T>> validateSet = Validation
                .buildDefaultValidatorFactory()
                .getValidator()
                .validate(validateObject);
        if (CollectionUtils.isNotEmpty(validateSet)) {
            for (ConstraintViolation<@Valid T> i : validateSet) {
                String msg = i.getPropertyPath() + i.getMessage();
                if (preMsg != null) {
                    msg = preMsg + msg;
                }
                throw new RuntimeException(msg);
            }
        }
    }

}

