package com.yuchen.saas.park.service.util;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.stereotype.Component;

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

/**
 * 手动校验参数
 */
@Slf4j
@Component
public class ManualValidUtil<T> {

    /**
     * 手动校验参数
     * @param paramObj
     * @param groupList
     */
    public void valid(T paramObj, List<Class> groupList) {
        String validResult = "";
        Class[] groupArray = groupList.toArray(new Class[groupList.size()]);

        Set<ConstraintViolation<T>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(paramObj, groupArray);

        validResult = getResultFromValidate(violations);

        if (Func.isNotEmpty(validResult)) {
            throw new ServiceException(validResult);
        }
    }


    private <T> String getResultFromValidate(Set<ConstraintViolation<T>> violations) {
        if (CollUtil.isEmpty(violations)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation<T> violation : violations) {
            sb.append(violation.getPropertyPath()).append(": ").append(violation.getMessage()).append("\n");
        }
        return sb.toString();
    }


}
