package com.haha.admin.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.stp.StpUtil;
import com.haha.common.exception.BusinessException;
import com.haha.common.utils.TraceIdUtils;
import com.haha.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
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.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import jakarta.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 统一处理各类异常，返回规范的响应格式
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e, HttpServletRequest request) {
        String traceId = TraceIdUtils.getTraceId();
        String requestPath = request.getRequestURI();
        
        log.warn("[TraceId: {}] 业务异常 - 路径: {}, 异常代码: {}, 异常消息: {}", 
                traceId, requestPath, e.getCode(), e.getMessage());
        
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理 Sa-Token 未登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<Void> handleNotLoginException(NotLoginException e, HttpServletRequest request) {
        String traceId = TraceIdUtils.getTraceId();
        String requestPath = request.getRequestURI();
        
        log.warn("[TraceId: {}] 未登录异常 - 路径: {}, 异常类型: {}", 
                traceId, requestPath, e.getType());
        
        String message;
        if (e.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未提供token";
        } else if (e.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "token无效";
        } else if (e.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "token已过期";
        } else {
            message = "未登录";
        }
        return Result.error(401, message);
    }

    /**
     * 处理 Sa-Token 无权限异常
     */
    @ExceptionHandler(NotPermissionException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Result<Void> handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
        String traceId = TraceIdUtils.getTraceId();
        String requestPath = request.getRequestURI();
        
        log.warn("[TraceId: {}] 无权限异常 - 路径: {}, 需要权限: {}", 
                traceId, requestPath, e.getPermission());
        
        return Result.error(403, "无访问权限");
    }

    /**
     * 处理参数校验异常（@Valid）
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        String traceId = TraceIdUtils.getTraceId();
        String requestPath = request.getRequestURI();
        
        String fieldErrors = e.getBindingResult().getFieldErrors().stream()
                .map(error -> String.format("%s: %s", error.getField(), error.getDefaultMessage()))
                .collect(Collectors.joining("; "));
        
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        
        log.warn("[TraceId: {}] 参数校验失败 - 路径: {}, 校验失败字段: {}", 
                traceId, requestPath, fieldErrors);
        
        return Result.error(400, message);
    }

    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleBindException(BindException e, HttpServletRequest request) {
        String traceId = TraceIdUtils.getTraceId();
        String requestPath = request.getRequestURI();
        
        String fieldErrors = e.getBindingResult().getFieldErrors().stream()
                .map(error -> String.format("%s: %s", error.getField(), error.getDefaultMessage()))
                .collect(Collectors.joining("; "));
        
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        
        log.warn("[TraceId: {}] 参数绑定失败 - 路径: {}, 绑定失败字段: {}", 
                traceId, requestPath, fieldErrors);
        
        return Result.error(400, message);
    }

    /**
     * 处理缺少必需参数异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleMissingServletRequestParameterException(MissingServletRequestParameterException e, HttpServletRequest request) {
        String traceId = TraceIdUtils.getTraceId();
        String requestPath = request.getRequestURI();
        
        log.warn("[TraceId: {}] 缺少必需参数 - 路径: {}, 参数名: {}, 参数类型: {}", 
                traceId, requestPath, e.getParameterName(), e.getParameterType());
        
        return Result.error(400, "缺少必需参数: " + e.getParameterName());
    }

    /**
     * 处理参数类型不匹配异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String traceId = TraceIdUtils.getTraceId();
        String requestPath = request.getRequestURI();
        
        log.warn("[TraceId: {}] 参数类型不匹配 - 路径: {}, 参数名: {}, 参数值: {}, 需要类型: {}", 
                traceId, requestPath, e.getName(), e.getValue(), 
                e.getRequiredType() != null ? e.getRequiredType().getSimpleName() : "未知");
        
        return Result.error(400, "参数类型错误: " + e.getName());
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        String traceId = TraceIdUtils.getTraceId();
        String requestPath = request.getRequestURI();
        
        log.warn("[TraceId: {}] 非法参数 - 路径: {}, 异常消息: {}", 
                traceId, requestPath, e.getMessage());
        
        return Result.error(400, e.getMessage());
    }

    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        String traceId = TraceIdUtils.getTraceId();
        String requestPath = request.getRequestURI();
        
        // 尝试获取当前登录用户信息
        String userInfo = "未登录";
        try {
            if (StpUtil.isLogin()) {
                userInfo = "用户ID: " + StpUtil.getLoginIdAsString();
            }
        } catch (Exception ex) {
            // 忽略获取用户信息时的异常
        }
        
        log.error("[TraceId: {}] 系统异常 - 路径: {}, 用户信息: {}, 异常消息: {}", 
                traceId, requestPath, userInfo, e.getMessage(), e);
        
        return Result.error(500, "系统繁忙，请稍后重试");
    }
}
