package com.zg.framework.websocket.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zg.project.Inventory.AutoInventory.service.IRfidService;
import com.zg.project.Inventory.AutoInventory.utils.SpringContextUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/ws/socket")
@Component
public class WebSocketServer {

    public static final ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<Session, String> sessionToDeviceMap = new ConcurrentHashMap<>();

    // rfidService 不在构造方法中注入！
    private IRfidService rfidService;

    @OnOpen
    public void onOpen(Session session) {
        // 延迟注入，解决 NPE 问题
        if (rfidService == null) {
            rfidService = SpringContextUtils.getBean(IRfidService.class);
        }

        System.out.println("🟡 建立WebSocket连接，等待设备发送连接信息 JSON...");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            if (rfidService == null) {
                rfidService = SpringContextUtils.getBean(IRfidService.class);
            }

            JSONObject json = JSON.parseObject(message);
            String deviceId = json.getString("deviceId");
            String ip = json.getString("ip");
            int port = json.getIntValue("port");

            sessionMap.put(deviceId, session);
            sessionToDeviceMap.put(session, deviceId);

            boolean connected = rfidService.connect(deviceId, ip, port);
            if (connected) {
                sendMessage(session, "设备[" + deviceId + "]连接成功！");
            } else {
                sendMessage(session, "设备[" + deviceId + "]连接失败！");
            }

        } catch (Exception e) {
            sendMessage(session, "参数解析失败：" + e.getMessage());
        }
    }

    @OnClose
    public void onClose(Session session) {
        if (rfidService == null) {
            rfidService = SpringContextUtils.getBean(IRfidService.class);
        }

        String deviceId = sessionToDeviceMap.remove(session);
        if (deviceId != null) {
            // 移除 WebSocket 映射
            sessionMap.remove(deviceId);

            // 断开设备连接（包含 deviceIdToConnIdMap / connIdToDeviceMap / deviceConnectState 清理）
            rfidService.disconnect(deviceId);

            System.out.println("WebSocket连接断开，已清理资源 -> deviceId = " + deviceId);
        } else {
            System.out.println("WebSocket断开，但未能获取到 deviceId");
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.err.println("WebSocket连接错误: " + throwable.getMessage());
    }

    public static void sendMessage(Session session, String message) {
        try {
            if (session != null && session.isOpen()) {
                session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            System.err.println("消息发送失败: " + e.getMessage());
        }
    }

    public static void sendMessageToDevice(String deviceId, String message) {
        Session session = sessionMap.get(deviceId);
        sendMessage(session, message);
    }
}

