package com.ecep.contract.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
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;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器，捕获并处理所有Controller层抛出的异常，将错误信息以JSON格式返回给前端
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        logger.error("系统异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("message", "系统内部错误：" + e.getMessage());
        result.put("errorType", e.getClass().getName());
        result.put("stackTrace", getStackTraceAsString(e));
        result.put("success", false);
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
    /**
     * 将异常堆栈转换为字符串
     */
    private String getStackTraceAsString(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            throwable.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Map<String, Object>> handleRuntimeException(RuntimeException e) {
        logger.error("运行时异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("message", "运行时错误：" + e.getMessage());
        result.put("errorType", e.getClass().getName());
        result.put("stackTrace", getStackTraceAsString(e));
        result.put("success", false);
        return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 处理请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<Map<String, Object>> handleHttpRequestMethodNotSupportedException(
            HttpRequestMethodNotSupportedException e) {
        logger.warn("请求方法不支持", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 405);
        result.put("message", "请求方法不支持：" + e.getMessage());
        result.put("errorType", "MethodNotAllowed");
        result.put("success", false);
        return new ResponseEntity<>(result, HttpStatus.METHOD_NOT_ALLOWED);
    }

    /**
     * 处理资源未找到异常
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<Map<String, Object>> handleNoHandlerFoundException(NoHandlerFoundException e) {
        logger.warn("资源未找到", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 404);
        result.put("message", "请求的资源不存在：" + e.getRequestURL());
        result.put("errorType", "ResourceNotFound");
        result.put("success", false);
        return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public ResponseEntity<Map<String, Object>> handleBindException(BindException e) {
        logger.warn("参数绑定异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("message", "参数绑定错误：" + e.getAllErrors().get(0).getDefaultMessage());
        result.put("errorType", "ParameterBindingError");
        result.put("success", false);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理方法参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleMethodArgumentNotValidException(
            MethodArgumentNotValidException e) {
        logger.warn("方法参数验证异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("message", "参数验证错误：" + e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        result.put("errorType", "ParameterValidationError");
        result.put("success", false);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理缺少请求参数异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<Map<String, Object>> handleMissingServletRequestParameterException(
            MissingServletRequestParameterException e) {
        logger.warn("缺少请求参数异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("message", "缺少必要参数：" + e.getParameterName());
        result.put("errorType", "MissingParameter");
        result.put("success", false);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理方法参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<Map<String, Object>> handleMethodArgumentTypeMismatchException(
            MethodArgumentTypeMismatchException e) {
        logger.warn("方法参数类型不匹配异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("message", "参数类型错误：参数 '" + e.getName() + "' 应类型为 "
                + (e.getRequiredType() != null ? e.getRequiredType().getSimpleName() : "未知类型"));
        result.put("errorType", "ParameterTypeError");
        result.put("success", false);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理HTTP消息不可读异常（如JSON解析错误）
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<Map<String, Object>> handleHttpMessageNotReadableException(
            HttpMessageNotReadableException e) {
        logger.warn("HTTP消息不可读异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("message", "请求体格式错误：" + e.getMessage());
        result.put("errorType", "MessageFormatError");
        result.put("success", false);
        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }
}