package cn.freemud.interceptor;

import cn.freemud.base.constant.Version;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.enums.ResponseResult;
import cn.freemud.inteceptor.CommonServiceException;
import cn.freemud.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: BizExceptionHandler 拦截校验参数
 * @Package com.freemud.base.exception
 * @Description: 全局异常处理
 * @author: aiqi.gong
 * @date: 2017/5/8 11:27
 * @Copyright: 2017 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@RestControllerAdvice
@Slf4j
public class BizExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse bindException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMesssage = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage.append(fieldError.getDefaultMessage()).append(", ");
        }
        return ResponseUtil.error(ResponseResult.PARAMETER_MISSING.getCode(), errorMesssage.toString());
    }

    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse bindException(ServiceException e) {
        return ResponseUtil.error(e.getResult());
    }

    @ExceptionHandler(ParameterException.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse bindException(ParameterException e) {
        return ResponseUtil.error(e.getResult());
    }

    @ExceptionHandler(CommonServiceException.class)
    @ResponseStatus(HttpStatus.OK)
    public BaseResponse bindException(CommonServiceException e) {
        return new BaseResponse<>(Version.VERSION_1, e.getResult().getCode(), e.getResult().getMessage());
    }

//    @ExceptionHandler(Throwable.class)
//    @ResponseStatus(HttpStatus.OK)
//    public BaseResponse bindException(Throwable e) {
//        log.error("系统内部异常", e);
//        return ResponseUtil.error(ResponseResult.SYSTEM_ERROR);
//    }

}