package com.changhu.support.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.changhu.common.enums.ResultCode;
import com.changhu.common.exception.MessageException;
import com.changhu.common.pojo.model.JsonResult;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
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.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.stream.Collectors;

/**
 * author: luozhun
 * desc: GlobalExceptionHandler
 * createTime: 2023/8/16 18:47
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public JsonResult<String> throwableHandler(Throwable throwable) {
        String errorLabel = "系统错误：" + ExceptionUtil.getMessage(throwable);
        log.error("系统错误:", throwable);
        return JsonResult.custom(ResultCode.ERROR.getCode(), errorLabel);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public JsonResult<String> handlerNoFoundException(NoHandlerFoundException e) {
        log.error("找不到资源:{}", e.getMessage());
        return JsonResult.custom(ResultCode.NOT_FOUND_404);
    }

    @ExceptionHandler(HttpMessageNotWritableException.class)
    public void HttpMessageNotWritableException(HttpMessageNotWritableException e) {
        log.error("HttpMessageNotWritableException", e);
    }

    /**
     * 空指针错误
     */
    @ExceptionHandler(NullPointerException.class)
    public JsonResult<String> nullPointerException(NullPointerException exception) {
        String errorLabel = "空指针错误：" + ExceptionUtil.getMessage(exception);
        log.error("空指针错误:", exception);
        return JsonResult.custom(ResultCode.ERROR.getCode(), errorLabel);
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(MessageException.class)
    public JsonResult<String> messageExceptionHandler(MessageException exception) {
        String errorLabel = "业务异常：" + exception.getMessage();
        log.error("业务异常:", exception);
        return JsonResult.custom(exception.getCode(), errorLabel);
    }

    @ExceptionHandler(ResponseStatusException.class)
    public JsonResult<String> responseExceptionHandler(ResponseStatusException exception) {
        int code = exception.getStatusCode().value();
        String message = "响应异常：" + exception.getReason();
        log.error("响应异常:{}", ExceptionUtil.stacktraceToString(exception));
        return JsonResult.custom(code, message);
    }

    /**
     * httpMessage
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public JsonResult<String> httpMessageNotReadableException(HttpMessageNotReadableException exception) {
        String message = exception.getMessage();
        log.error(message);
        if (StrUtil.contains(message, "Required request body is missing")) {
            return JsonResult.custom(ResultCode.REQUIRED_PARAM_MISSING);
        }
        return JsonResult.custom(ResultCode.PARAM_ERROR);
    }

    /**
     * 处理请求参数格式错误 @RequestBody上使用@Valid 实体上使用@NotNull等，验证失败后抛出的异常是MethodArgumentNotValidException异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JsonResult<String> exceptionHandler(MethodArgumentNotValidException exception) {
        String message = exception.getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining("，", ResultCode.PARAM_ERROR.getMessage() + ": 【", "】"));
        log.error(message);
        return JsonResult.custom(ResultCode.PARAM_ERROR.getCode(), message);
    }

    /**
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
     */
    @ExceptionHandler(value = BindException.class)
    public JsonResult<String> validExceptionHandler(BindException exception) {
        String message = exception.getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining("，", ResultCode.PARAM_ERROR.getMessage() + ": 【", "】"));
        log.error(message);
        return JsonResult.custom(ResultCode.PARAM_ERROR.getCode(), message);
    }

    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult<String> ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining("，", ResultCode.PARAM_ERROR.getMessage() + ": 【", "】"));
        log.error(message);
        return JsonResult.custom(ResultCode.PARAM_ERROR.getCode(), message);
    }

    /**
     * 全局参数校验错误，处理返回
     */
    @ExceptionHandler(WebExchangeBindException.class)
    public JsonResult<String> handleValidationException(WebExchangeBindException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMessage = new StringBuilder(ResultCode.PARAM_ERROR.getMessage() + ": 【");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append(fieldError.getDefaultMessage()).append("，");
        }
        log.error("{}】", errorMessage.substring(0, errorMessage.length() - 1));
        return JsonResult.custom(ResultCode.PARAM_ERROR.getCode(), errorMessage.substring(0, errorMessage.length() - 1) + "】");
    }

    @ExceptionHandler(NotLoginException.class)
    public JsonResult<String> handlerNotLoginException(NotLoginException nle) {
        log.error(nle.getMessage());
        // 判断场景值，定制化异常信息
        ResultCode resultCode;
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            resultCode = ResultCode.NOT_TOKEN;
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            resultCode = ResultCode.INVALID_TOKEN;
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            resultCode = ResultCode.TOKEN_TIMEOUT;
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            resultCode = ResultCode.BE_REPLACED;
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            resultCode = ResultCode.KICK_OUT;
        } else if (nle.getType().equals(NotLoginException.TOKEN_FREEZE)) {
            resultCode = ResultCode.TOKEN_FREEZE;
        } else if (nle.getType().equals(NotLoginException.NO_PREFIX)) {
            resultCode = ResultCode.NO_PREFIX;
        } else {
            resultCode = ResultCode.OTHER_TOKEN_ERROR;
        }
        return JsonResult.custom(resultCode);
    }

}
