package com.microservices.wiki.refactoring.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.validation.Validation;
import javax.validation.Validator;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ValidatorUtils {
    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    private static final String ERROR_PARAMS = "错误参数:";

    private static final String ERROR_TIPS = ",错误提示:";

    public static String buildValidationdErrorMessage(BindingResult bindingResult) {
        StringBuilder sBuild = new StringBuilder();
        List<FieldError> errList = bindingResult.getFieldErrors();
        for (FieldError error : errList) {
            sBuild.append(ERROR_PARAMS).append(error.getField()).append(ERROR_TIPS).append(error.getDefaultMessage()).append("|");
        }

        return sBuild.toString();
    }

    public static String parseGBK(String sIn)
            throws UnsupportedEncodingException {
        return StringUtils.isEmpty(sIn) ? sIn : new String(sIn.getBytes("GBK"), "ISO-8859-1");
    }

    public static Map<String, String> buildValidationErrorMessageMap(BindingResult bindingResult) {
        Map<String, String> errorMessageMap = new HashMap<>();
        List<FieldError> errList = bindingResult.getFieldErrors();
        for (FieldError error : errList) {
            errorMessageMap.put(error.getField(), error.getDefaultMessage());
        }
        return errorMessageMap;
    }
}

