//package com.mcwl.communityCenter.webSocket;
//
//import com.mcwl.communityCenter.service.AIService;
//import com.mcwl.communityCenter.service.HumanService;
//import lombok.NoArgsConstructor;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.socket.CloseStatus;
//import org.springframework.web.socket.TextMessage;
//import org.springframework.web.socket.WebSocketSession;
//import org.springframework.web.socket.handler.AbstractWebSocketHandler;
//import reactor.core.Disposable;
//import reactor.core.publisher.Flux;
//
//import javax.websocket.server.ServerEndpoint;
//import java.io.IOException;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//
//@ServerEndpoint("/chat")
//@NoArgsConstructor
//public class ChatWebSocket extends AbstractWebSocketHandler {
//    private final Map<String, Boolean> userModes = new ConcurrentHashMap<>();
//
//    // 存储会话与订阅的映射关系
//    private final Map<String, Disposable> sessionSubscriptions = new ConcurrentHashMap<>();
//
//    @Autowired
//    private AIService aiService;
//
//    // 构造函数注入服务...
//
//    @Override
//    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//        String userId = session.getId();
//        String userMessage = message.getPayload();
//
//        // AI 流式响应模式
//        Flux<String> responseStream = aiService.getDeepSeekResponseStream(userMessage);
//
//        // 订阅响应流并存储 Disposable
//        Disposable disposable = responseStream
//                .doOnNext(chunk -> sendText(session, chunk)) // 发送每个数据块到客户端
//                .doOnComplete(() -> sendText(session, "[END]")) // 当流处理完成时，发送结束标记
//                .doOnError(e -> sendText(session, "[ERROR] " + e.getMessage()))
//                .subscribe();
//
//        sessionSubscriptions.put(userId, disposable);
//
//    }
//
//    @Override
//    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//        super.afterConnectionEstablished(session);
////        userModes.put(session.getId(), false);
//        session.sendMessage(new TextMessage("[AI] 您好，请问有什么问题？"));
//    }
//
//    @Override
//    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
//        // 清理订阅资源
//        String sessionId = session.getId();
//        Disposable disposable = sessionSubscriptions.remove(sessionId);
//        if (disposable != null && disposable.isDisposed()) {
//            disposable.dispose();
//        }
//    }
//
//
//
//    // 线程安全的发送方法
//    private void sendText(WebSocketSession session, String text) {
//        try {
//            if (session.isOpen()) {
//                synchronized (session) { // WebSocketSession 非线程安全
//                    session.sendMessage(new TextMessage(text));
//                }
//            }
//        } catch (IOException e) {
//            System.out.println("WebSocket 发送失败: " + e.getMessage());
//        }
//    }
//}
