package com.backendsys.modules.common.config.security.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com.backendsys.utils.CommonUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

@Component
public class HttpRequestUtil {

    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 获取 HttpServletRequest 对象
     */
    public HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes != null ? attributes.getRequest() : null;
        return request;
    }

    /**
     * 获得请求头 request headers
     */
    public JSONObject getHeaders() {
        HttpServletRequest request = getRequest();
        JSONObject headers = new JSONObject();
        request.getHeaderNames()
            .asIterator()
            .forEachRemaining(name -> {
                headers.put(name, request.getHeader(name));
            });
        return headers;
    }

    public String getBrowserWindowUUID() {
        // 获取当前请求的上下文
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            return request.getHeader("Browser-Window-Uuid");
        }
        return null; // 如果没有请求上下文，返回 null
    }

    /**
     * 从 Token 中获得 user_id
     */
    public Long getUserId() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            Claims tokenInfo = tokenUtil.getTokenInfo(request);
            if (tokenInfo != null) {
                Map<String, Object> userInfo = (Map<String, Object>) tokenInfo.get("userInfo");
                return Convert.toLong(userInfo.get("user_id"));
            }
        }
        return null;
    }
    public String getUserName() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            Claims tokenInfo = tokenUtil.getTokenInfo(request);
            if (tokenInfo != null) {
                Map<String, Object> userInfo = (Map<String, Object>) tokenInfo.get("userInfo");
                return Convert.toStr(userInfo.get("username"));
            }
        }
        return null;
    }

    /**
     * 从 Token 中获得 member_id
     */
    public Long getMemberId() {
        HttpServletRequest request = getRequest();
        if (request != null) {
            Claims tokenInfo = tokenUtil.getTokenInfo(request);
            if (tokenInfo != null) {
                Map<String, Object> userInfo = (Map<String, Object>) tokenInfo.get("userInfo");
                return Convert.toLong(userInfo.get("member_id"));
            }
        }
        return null;
    }

    public String getIpAddr() {
        HttpServletRequest request = getRequest();
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) {
                // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
            System.out.println(e.getMessage());
        }
        return ipAddress;
    }

    /**
     * 获得验证码 RedisKey (ua + ip)
     */
    public String getKaptchaKey() {
        String ip = getIpAddr();
        String userAgent = getUa();
        return "captcha:ua:ip:" + CommonUtil.MD5(ip + userAgent);
    }
    public String getKaptchaKey(String key) {
        String ip = getIpAddr();
        String userAgent = getUa();
        return "captcha:ua:ip:" + CommonUtil.MD5(ip + userAgent + key);
    }

    public String getUa() {
        HttpServletRequest request = getRequest();
        return request.getHeader("User-Agent");
    }

}
