package com.nokia.domainb.config;

import com.nokia.common.http.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 请求异常处理
 */
@Slf4j
@RestControllerAdvice
public class ControllerExceptionHandler
{
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<Object> httpMessageNotReadableExceptionValidatorHandler(HttpMessageNotReadableException e)
    {
        log.warn("╭( ′• o •′ )╭☞ 请求参数校验未通过: {}", e.getMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.error().message(e.getMessage()));
    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity<Object> bindExceptionValidatorHandler(BindException e)
    {
        FieldError fieldError = e.getBindingResult().getFieldError();
        String message = "";
        if (fieldError != null)
        {
            message = fieldError.getDefaultMessage();
            log.warn("╭( ′• o •′ )╭☞ 请求参数校验未通过: {}", message);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.error().message(message));
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Object> constraintViolationExceptionValidatorHandler(ConstraintViolationException e)
    {
        String message = e.getConstraintViolations().iterator().next().getMessage();
        log.warn("╭( ′• o •′ )╭☞ 请求参数校验未通过: {}", message);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.error().message(message));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> methodArgumentNotValidExceptionValidatorHandler(MethodArgumentNotValidException e)
    {
        FieldError fieldError = e.getBindingResult().getFieldError();
        String message = "";
        if (fieldError != null)
        {
            message = fieldError.getDefaultMessage();
            log.warn("╭( ′• o •′ )╭☞ 请求参数校验未通过: {}", message);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.error().message(message));
    }
    
    @ExceptionHandler({Exception.class})
    public ResponseEntity<Object> exceptionHandler(Exception e)
    {
        log.error("╭( ′• o •′ )╭☞ 发生错误了 {}", e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.error());
    }
}
