package com.emotion.exception;

import com.emotion.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 全局异常处理器
 * 
 * @author huazhongmin
 * @date 2025-07-23
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

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

    /**
     * 处理认证异常
     */
    @ExceptionHandler(AuthException.class)
    public Result<Void> handleAuthException(AuthException e, HttpServletRequest request) {
        log.warn("认证异常: {} {} - {}", request.getMethod(), request.getRequestURI(), e.getMessage());
        return Result.unauthorized(e.getMessage());
    }

    /**
     * 处理令牌异常
     */
    @ExceptionHandler(TokenException.class)
    public Result<Void> handleTokenException(TokenException e, HttpServletRequest request) {
        log.warn("令牌异常: {} {} - {}", request.getMethod(), request.getRequestURI(), e.getMessage());
        return Result.unauthorized(e.getMessage());
    }

    /**
     * 处理验证码异常
     */
    @ExceptionHandler(CaptchaException.class)
    public Result<Void> handleCaptchaException(CaptchaException e, HttpServletRequest request) {
        log.warn("验证码异常: {} {} - {}", request.getMethod(), request.getRequestURI(), e.getMessage());
        return Result.badRequest(e.getMessage());
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.warn("业务异常: {} {} - {}", request.getMethod(), request.getRequestURI(), e.getMessage());

        if (e.getCode() == 401) {
            return Result.unauthorized(e.getMessage());
        } else if (e.getCode() == 403) {
            return Result.forbidden(e.getMessage());
        } else if (e.getCode() == 400) {
            return Result.badRequest(e.getMessage());
        } else {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        log.warn("参数校验失败: {} {}", request.getMethod(), request.getRequestURI(), e);
        
        StringBuilder message = new StringBuilder("参数校验失败: ");
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            message.append(error.getField()).append(" ").append(error.getDefaultMessage()).append("; ");
        }
        
        return Result.badRequest(message.toString());
    }

    /**
     * 处理Bean校验异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleBindException(BindException e, HttpServletRequest request) {
        log.warn("参数绑定失败: {} {}", request.getMethod(), request.getRequestURI(), e);
        
        StringBuilder message = new StringBuilder("参数绑定失败: ");
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            message.append(error.getField()).append(" ").append(error.getDefaultMessage()).append("; ");
        }
        
        return Result.badRequest(message.toString());
    }

    /**
     * 处理约束校验异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
        log.warn("约束校验失败: {} {}", request.getMethod(), request.getRequestURI(), e);
        
        StringBuilder message = new StringBuilder("约束校验失败: ");
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            message.append(violation.getPropertyPath()).append(" ").append(violation.getMessage()).append("; ");
        }
        
        return Result.badRequest(message.toString());
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        log.warn("非法参数: {} {}", request.getMethod(), request.getRequestURI(), e);
        return Result.badRequest("参数错误: " + e.getMessage());
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常: {} {}", request.getMethod(), request.getRequestURI(), e);
        return Result.error("系统内部错误");
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("运行时异常: {} {}", request.getMethod(), request.getRequestURI(), e);
        return Result.error("系统运行异常: " + e.getMessage());
    }

    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("未知异常: {} {}", request.getMethod(), request.getRequestURI(), e);
        return Result.error("系统异常，请联系管理员");
    }


}
