package org.xyzh.common.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @description ServletUtil.java文件描述 Servlet工具类
 * @filename ServletUtil.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-07
 */
public class ServletUtil {

    private static final String TOKEN_PREFIX = "Bearer ";

    /**
     * @description 获取当前请求对象
     * @return HttpServletRequest 当前请求对象，无当前请求时返回null
     * @author yslg
     * @since 2025-10-07
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = 
            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes != null ? requestAttributes.getRequest() : null;
    }

    /**
     * @description 获取当前响应对象
     * @return HttpServletResponse 当前响应对象，无当前请求时返回null
     * @author yslg
     * @since 2025-10-07
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = 
            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes != null ? requestAttributes.getResponse() : null;
    }

    /**
     * @description 从当前请求中获取token（无参方法）
     * @return String token值，未找到返回null
     * @author yslg
     * @since 2025-10-07
     */
    public static String getToken() {
        HttpServletRequest request = getRequest();
        return request != null ? extractTokenFromRequest(request) : null;
    }

    /**
     * @description 从当前请求中获取指定请求头
     * @param headerName 请求头名称
     * @return String 请求头值，未找到返回null
     * @author yslg
     * @since 2025-10-07
     */
    public static String getHeader(String headerName) {
        HttpServletRequest request = getRequest();
        return request != null ? request.getHeader(headerName) : null;
    }

    /**
     * @description 从当前请求中获取指定请求参数
     * @param paramName 参数名称
     * @return String 参数值，未找到返回null
     * @author yslg
     * @since 2025-10-07
     */
    public static String getParameter(String paramName) {
        HttpServletRequest request = getRequest();
        return request != null ? request.getParameter(paramName) : null;
    }

    /**
     * @description 获取当前请求的客户端IP地址
     * @return String IP地址，未找到返回null
     * @author yslg
     * @since 2025-10-07
     */
    public static String getClientIpAddress() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }

        String ip = request.getHeader("X-Forwarded-For");
        if (NonUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }

        ip = request.getHeader("X-Real-IP");
        if (NonUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getHeader("Proxy-Client-IP");
        if (NonUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getHeader("WL-Proxy-Client-IP");
        if (NonUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getHeader("HTTP_CLIENT_IP");
        if (NonUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        if (NonUtils.isNotEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }

        return request.getRemoteAddr();
    }

    /**
     * @description 获取当前请求的User-Agent
     * @return String User-Agent值，未找到返回null
     * @author yslg
     * @since 2025-10-07
     */
    public static String getUserAgent() {
        return getHeader("User-Agent");
    }

    /**
     * @description 获取当前请求的完整URL
     * @return String 完整URL，无当前请求时返回null
     * @author yslg
     * @since 2025-10-07
     */
    public static String getRequestUrl() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }

        StringBuffer url = request.getRequestURL();
        String queryString = request.getQueryString();
        if (NonUtils.isNotEmpty(queryString)) {
            url.append('?').append(queryString);
        }
        return url.toString();
    }

    /**
     * @description 从请求中提取token
     * @param request HTTP请求对象
     * @return String token
     * @author yslg
     * @since 2025-10-07
     */
    private static String extractTokenFromRequest(HttpServletRequest request) {
        // 优先从Authorization头获取
        String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (NonUtils.isNotEmpty(authHeader) && authHeader.startsWith(TOKEN_PREFIX)) {
            return authHeader.substring(TOKEN_PREFIX.length());
        }

        // 从请求参数中获取token
        String token = request.getParameter("token");
        if (NonUtils.isNotEmpty(token)) {
            return token;
        }

        // 从请求头中获取token
        token = request.getHeader("token");
        if (NonUtils.isNotEmpty(token)) {
            return token;
        }

        return null;
    }
}
