package com.bcxin.ars.rest.interceptor;
import com.bcxin.ars.dto.AjaxResult;
import com.bcxin.ars.exception.ValidateException;
import com.bcxin.ars.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Set;

/***
 * hibernate validator 拦截器
 */
@ControllerAdvice
@ResponseBody
public class ValidationExceptionAdvice {
    /***
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(ValidationExceptionAdvice.class);
    /***
     * 处理验证
     * @param ex 验证结果
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public AjaxResult processValidationError(BindException ex) {
        logger.info("进入处理验证方法………………………………");
        AjaxResult result = new AjaxResult();
        //请求失败
        result.setSuccessful(false);
        //设置请求失败编码
        result.setCode(Constants.REQUEST_CODE_FAIL);
        //定义验证结果信息
        StringBuffer validationResultString = new StringBuffer();
        //获取验证错误的字段列表并遍历
        for (ObjectError error : ex.getAllErrors()) {
            //字段名称
            String field = ((FieldError)error).getField();
            //字段提示信息
            String code = error.getDefaultMessage();
            //字段和信息拼接
            String message = String.format("%s:%s", field, code);
            validationResultString.append(message);
        }
        //设置验证结果信息
        result.setMsg(validationResultString.toString());
        logger.info("结束处理验证方法………………………………");
        return result;
    }


    @ExceptionHandler(ValidateException.class)
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public AjaxResult handleValidateException(ValidateException validateException) {
        Set<String> errorMessages = validateException.getErrorMessages();
        AjaxResult ajaxResult = new AjaxResult();
        //请求失败
        ajaxResult.setSuccessful(false);
        StringBuilder stringBuilder = new StringBuilder();
        //设置请求失败编码
        for (String errorMessage : errorMessages) {
            stringBuilder.append(errorMessage).append(";");
        }
        ajaxResult.setCode(Constants.REQUEST_CODE_FAIL);
        ajaxResult.setMsg(stringBuilder.toString());
        //定义验证结果信息
        return ajaxResult;
    }
}
