package shop.alien.dining.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * WebSocketConfig
 *
 * @author ssk
 * @version 1.0
 * @date 2024/2/29 14:40
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
    
    /**
     * WebSocket配置器，用于在握手时获取IP地址和User-Agent
     */
    public static class WebSocketConfigurator extends ServerEndpointConfig.Configurator {
        @Override
        public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
            Map<String, Object> userProperties = sec.getUserProperties();
            Map<String, List<String>> headers = request.getHeaders();
            
            // 获取User-Agent
            List<String> userAgentList = headers.get("User-Agent");
            String userAgent = (userAgentList != null && !userAgentList.isEmpty()) ? userAgentList.get(0) : null;
            userProperties.put("userAgent", userAgent);
            
            // 获取IP地址（从请求头中获取）
            String ipAddress = getIpAddress(headers);
            userProperties.put("ipAddress", ipAddress);
        }
        
        /**
         * 从请求头中获取客户端IP地址
         */
        private String getIpAddress(Map<String, List<String>> headers) {
            String ip = null;
            
            // 尝试从各种请求头中获取IP
            if (headers.containsKey("X-Forwarded-For")) {
                List<String> xffList = headers.get("X-Forwarded-For");
                if (xffList != null && !xffList.isEmpty()) {
                    ip = xffList.get(0);
                }
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                if (headers.containsKey("Proxy-Client-IP")) {
                    List<String> proxyList = headers.get("Proxy-Client-IP");
                    if (proxyList != null && !proxyList.isEmpty()) {
                        ip = proxyList.get(0);
                    }
                }
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                if (headers.containsKey("WL-Proxy-Client-IP")) {
                    List<String> wlProxyList = headers.get("WL-Proxy-Client-IP");
                    if (wlProxyList != null && !wlProxyList.isEmpty()) {
                        ip = wlProxyList.get(0);
                    }
                }
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                if (headers.containsKey("HTTP_CLIENT_IP")) {
                    List<String> httpClientList = headers.get("HTTP_CLIENT_IP");
                    if (httpClientList != null && !httpClientList.isEmpty()) {
                        ip = httpClientList.get(0);
                    }
                }
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                if (headers.containsKey("HTTP_X_FORWARDED_FOR")) {
                    List<String> httpXffList = headers.get("HTTP_X_FORWARDED_FOR");
                    if (httpXffList != null && !httpXffList.isEmpty()) {
                        ip = httpXffList.get(0);
                    }
                }
            }
            
            // 如果是多级代理，取第一个IP
            if (ip != null && ip.contains(",")) {
                ip = ip.split(",")[0].trim();
            }
            
            return ip;
        }
    }
}
