package com.sckw.excel.utils;

import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.model.ValiList;
import com.sckw.core.web.response.HttpResult;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.HibernateValidator;
import java.util.List;
import java.util.Set;

/**
 * @author
 * @version 1.0.0
 * @ClassName ValidUtil.java
 * @Description 参数校验工具类
 * @createTime 2021年10月20日 13:35:00
 */
public class ValidUtil {

    private static Validator validator;

    static {
        //初始化检查器
        validator = Validation.byProvider(HibernateValidator.class)
                .configure()
                .failFast(false)
                .buildValidatorFactory()
                .getValidator();
    }
    /**
     * 功能详细描述: service 层参数校验工具类
     *
     * @param object 待校验参数
     * @methodName: serviceValid
     * @return: com.alibaba.fastjson.JSONObject
     * @Author:
     * @date: 2021/10/20 14:51
     */
    public static HttpResult serviceValid(Object object) {
        if (object instanceof List) {
            ValiList<Object> validateObj = new ValiList<>();
            validateObj.addAll((List) object);
            object = validateObj;
        }
        StringBuilder validMsg = new StringBuilder();
        //校验
        Set<ConstraintViolation<Object>> set = validator.validate(object);
        //获取检查结果
        for (ConstraintViolation<Object> voset : set) {
            validMsg.append(voset.getPropertyPath())
                    .append(":")
                    .append(voset.getMessage())
                    .append(";");
        }
        if (StringUtils.isNotBlank(validMsg)) {
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE,validMsg.toString());
        }
        return HttpResult.ok();
    }

    /**
     * 功能详细描述: service 层参数校验工具类
     *
     * @param object        待校验参数
     * @param validateGroup 校验规则分组
     * @methodName: serviceValid
     * @return:
     * @Author:
     * @date: 2021/12/22 10:47
     */
    public static HttpResult serviceValid(Object object, Class... validateGroup) {
        if (object instanceof List) {
            ValiList<Object> validateObj = new ValiList<>();
            validateObj.addAll((List) object);
            object = validateObj;
        }
        StringBuilder validMsg = new StringBuilder();
        //校验
        Set<ConstraintViolation<Object>> set = validator.validate(object, validateGroup);
        //获取检查结果
        for (ConstraintViolation<Object> voset : set) {
            validMsg.append(voset.getPropertyPath())
                    .append(":")
                    .append(voset.getMessage())
                    .append(";");
        }
        if (StringUtils.isNotBlank(validMsg)) {
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE,validMsg.toString());
        }
        return HttpResult.ok();
    }


}
