package com.test.bijihoudaun.common.advice;

import com.test.bijihoudaun.common.exception.BaseException;

import com.test.bijihoudaun.common.response.R;
import com.test.bijihoudaun.common.response.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
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.multipart.MaxUploadSizeExceededException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 打印日志
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BaseException.class)
    public R<Void> handleBaseException(BaseException e, HttpServletRequest request) {
        return R.fail(e.getResultCode().getCode(), e.getMessage());
    }

    /**
     * 处理文件大小超出限制异常
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public R<String> handleFileSizeLimitExceeded() {
        log.error("文件大小超出限制");
        return R.fail("文件大小超过限制");
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<List<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<String> errors = e.getBindingResult().getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        log.error("参数校验异常：{}", errors.get(0));
        return R.fail(ResultCode.VALIDATE_FAILED.getCode(), errors.get(0));
    }

    /**
     * 处理绑定异常
     */
    @ExceptionHandler(BindException.class)
    public R<List<String>> handleBindException(BindException e) {
        List<String> errors = e.getBindingResult().getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        log.error("参数校验异常：{}", errors.get(0));
        return R.fail(ResultCode.VALIDATE_FAILED.getCode(), errors.get(0));
    }

    /**
     * 处理请求体格式错误异常 (例如JSON格式错误)
     */
    @ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class)
    public R<String> handleHttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException e) {
        log.error("请求参数格式不正确: {}", e.getMessage());
        return R.fail(ResultCode.VALIDATE_FAILED.getCode(), "请求参数格式不正确");
    }

    /**
     * 处理其他所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public R<Void> handleException(Exception e) {
        log.error("系统异常：", e); // 打印完整的堆栈信息
        return R.fail(ResultCode.FAILED.getCode(), "系统繁忙，请稍后再试");
    }
}
