package com.cnooc.expert.common.exception;

import com.cnooc.expert.common.response.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e,
                                                                   HttpServletRequest request) {
        log.error("参数校验失败: {}，请求URL: {}", e.getMessage(), request.getRequestURI());
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(error ->
                sb.append(error.getField()).append(": ").append(error.getDefaultMessage()).append("; ")
        );
        return ApiResult.error("参数校验失败" + sb);
    }

    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    public ApiResult<String> handleBindException(BindException e, HttpServletRequest request) {
        log.error("参数绑定失败: {}，请求URL: {}", e.getMessage(), request.getRequestURI());
        StringBuilder sb = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(error ->
                sb.append(error.getField()).append(": ").append(error.getDefaultMessage()).append("; ")
        );
        return ApiResult.error("参数绑定失败" + sb);
    }

    /**
     * 处理其他异常
     */


    @ExceptionHandler(BusinessException.class)
    public ApiResult<String> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.error("业务异常: {}，请求URL: {}", e.getMessage(), request.getRequestURI(), e);
        if(e.getErrorCode()==GlobalErrorCodeConstants.USER_LOCKED.getCode()){
            //这个需要特殊处理
            return ApiResult.errorWithResult(GlobalErrorCodeConstants.USER_LOCKED.getCode(),GlobalErrorCodeConstants.USER_LOCKED.getMsg(),String.valueOf(e.getErrorData().get("dueDate")));
        }
        return ApiResult.error(e.getErrorCode(), e.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    public ApiResult<String> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常: {}，请求URL: {}", e.getMessage(), request.getRequestURI(), e);
        return ApiResult.error(GlobalErrorCodeConstants.SYSTEM_ERROR.getCode(), GlobalErrorCodeConstants.SYSTEM_ERROR.getMsg());
    }

    /**
     * 处理 HTTP 方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ApiResult<String> handleHttpRequestMethodNotSupportedException(
            HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.warn("HTTP方法不支持: {}，请求URL: {}", e.getMessage(), request.getRequestURI());
        return ApiResult.error(HttpStatus.METHOD_NOT_ALLOWED.value(),
                "不支持 " + e.getMethod() + " 请求方法 ");
    }


    @ExceptionHandler(Exception.class)
    public ApiResult<String> handleException(Exception e, HttpServletRequest request) {
        log.error("系统异常: {}，请求URL: {}", e.getMessage(), request.getRequestURI(), e);
        return ApiResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), GlobalErrorCodeConstants.SYSTEM_ERROR.getMsg());
    }
}
