package com.shr.handler;


import com.shr.common.response.ErrorResponseData;
import com.shr.common.response.RestResponse;
import com.shr.exception.ShrException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 全局的的异常拦截器
 *
 * @author Inori
 */
@Order(-1)
@ControllerAdvice
public class ShrExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(ShrExceptionHandler.class);


    /**
     * 参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public RestResponse handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();

        // 所有参数异常信息
        List<String> errorsMessageList = new ArrayList<>();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        allErrors.forEach(error -> {
            errorsMessageList.add(error.getDefaultMessage());
        });
        String errorMsg = String.join(";", errorsMessageList);
        return RestResponse.fail(errorMsg);
    }

    /**
     * 运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorResponseData notFount(HttpServletRequest request, RuntimeException e) {
        log.error("---------------->运行时异常: {}", e.getMessage());

        return new ErrorResponseData(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), request.getRequestURI());
    }

    /**
     * SHR返回异常
     */
    @ExceptionHandler(ShrException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public RestResponse blogExceptionHandler(HttpServletRequest request, ShrException e) {
        log.error("---------------->Request URI : {}, ErrorMassage : {}", request.getRequestURI(), e.getMessage());

        return RestResponse.error(e.getMessage());
    }


}
