package com.fs.app.websocket.service;

import com.alibaba.fastjson.JSONObject;
import com.fs.aiChat.param.Message;
import com.fs.common.utils.spring.SpringUtils;
import com.fs.his.service.IHisDoctorAiChatSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

@ServerEndpoint("/app/webSocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {
    IHisDoctorAiChatSessionService aiChatSessionService= SpringUtils.getBean(IHisDoctorAiChatSessionService.class);

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public static void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                log.info("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }
    //给指定用户发送信息
    public static void sendInfo(String id, String message){
        Session session = sessionPools.get(id);
        try {
            log.info("指定用户:"+session);
             sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId){
        sessionPools.put(userId, session);
        log.info(userId + "加入webSocket！当前人数为" + sessionPools.size());

    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "userId") String userId){
        sessionPools.remove(userId);
        log.info(userId + "断开webSocket连接！当前人数为" + sessionPools.size());
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String json) throws IOException{
        log.info( "收到数据" + json);
        Message message = JSONObject.parseObject(json, Message.class);
        if (message!=null){
            String aiMessage = aiChatSessionService.chatByUser(message);
            sendInfo(message.getUserId().toString(),aiMessage);
        }

    }


    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }


}
