package com.starry.admin.common.exception.handler;

import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.common.exception.ServiceException;
import com.starry.common.result.R;
import com.starry.common.utils.StringUtils;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 全局异常处理
 * @since 2023/3/9
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public R handleServiceException(ServiceException e, HttpServletRequest request) {
        if ("token异常".equals(e.getMessage()) || "token为空".equals(e.getMessage())) {
            log.error("用户token异常");
        } else if (log.isDebugEnabled()) {
            log.debug("业务异常", e);
        } else {
            log.warn("业务异常: {}", e.getMessage());
        }
        Integer code = e.getCode();
        return StringUtils.isNotNull(code) ? R.error(code, e.getMessage()) : R.error(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public R handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestUrl = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestUrl, e);
        return R.error(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e, HttpServletRequest request) {
        String requestUrl = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestUrl, e);
        return R.error("系统出现内部错误，请联系管理员");
    }

    /**
     * 请求方法异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R httpRequestMethodNotSupportedException() {
        return R.error("请求方法异常");
    }

    /**
     * 请求参数异常
     *
     * @param e
     *            HttpRequestMethodNotSupportedException
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMessageBuilder = new StringBuilder();
        for (FieldError error : bindingResult.getFieldErrors()) {
            errorMessageBuilder.append(error.getDefaultMessage());
        }
        return R.error("请求参数异常," + errorMessageBuilder);
    }

    @ExceptionHandler(MismatchedInputException.class)
    public R mismatchedInputException(MismatchedInputException e) {
        log.error("请求参数格式异常", e);
        return R.error("请求参数格式异常");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R httpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("请求参数格式异常", e);
        return R.error("请求参数格式异常");
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public R missingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("请求参数格式异常", e);
        return R.error("请求参数格式异常");
    }

    /**
     * 自定义异常
     *
     * @param e
     *            CustomException
     */
    @ExceptionHandler(CustomException.class)
    public R customException(CustomException e) {
        if ("token异常".equals(e.getMessage()) || "token为空".equals(e.getMessage())) {
            log.error("用户token异常");
        } else if (log.isDebugEnabled()) {
            log.debug("业务异常", e);
        } else {
            log.warn("业务异常: {}", e.getMessage());
        }
        return R.error(e.getMessage());
    }
}
