package cn.exploring.engine.server.core.config;

import cn.exploring.engine.server.core.util.ResponseUtil;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
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.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

@ControllerAdvice
@Order( value = Ordered.LOWEST_PRECEDENCE )
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public Object badArgumentHandler(HttpServletRequest request, IllegalArgumentException e) {
        e.printStackTrace();
        printExceptionInfo(request);
        return ResponseUtil.badArgumentValue();
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public Object badArgumentHandler(HttpServletRequest request, MethodArgumentTypeMismatchException e) {
        e.printStackTrace();
        printExceptionInfo(request);
        return ResponseUtil.badArgumentValue();
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public Object badArgumentHandler(HttpServletRequest request, MissingServletRequestParameterException e) {
        e.printStackTrace();
        printExceptionInfo(request);
        return ResponseUtil.badArgumentValue();
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Object badArgumentHandler(HttpServletRequest request, HttpMessageNotReadableException e) {
        e.printStackTrace();
        printExceptionInfo(request);
        return ResponseUtil.badArgumentValue();
    }

    @ExceptionHandler(ValidationException.class)
    @ResponseBody
    public Object badArgumentHandler(HttpServletRequest request, ValidationException e) {
        e.printStackTrace();
        printExceptionInfo(request);

        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage();
                return ResponseUtil.fail(402, message);
            }
        }
        return ResponseUtil.badArgumentValue();
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object seriousHandler(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        printExceptionInfo(request);

        return ResponseUtil.serious();
    }

    private void printExceptionInfo(HttpServletRequest request) {
        System.out.println();
        int id = request.hashCode();
        System.out.println("========================================== 请求出错啦 sessionId: " + id + " ==========================================");
        System.out.println("sessionId: " + id + " ======= 请求方式：" + request.getMethod());
        System.out.println("sessionId: " + id + " ======= 请求地址：" + request.getRequestURL().toString());
        System.out.println("sessionId: " + id + " ======= 请求参数：" + request.getQueryString());
        System.out.println("========================================== 错误打印结束 sessionId: " + id + " ==========================================");
        System.out.println();
    }
}
