package com.ruoyi.framework.websocket;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket 消息处理
 *
 * @author ruoyi
 */
@Component
@ServerEndpoint("/websocket/message/{userId}")
@Slf4j
public class WebSocketServer {

    private static CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();
    private Session session;
    private static Map<String, Session> sessionPool = new HashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            this.session = session;
            webSockets.add(this);
            // 添加用户
            sessionPool.put(userId, session);
            log.info("\n 建立连接 - {}", session);
            log.info("\n 当前人数 - {}", webSockets.size());
            sendMessageToUserByText(session, "连接成功");
        } catch (Exception e) {
            log.error("\n websocket建立连接异常");
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session) {
        log.info("\n 关闭连接 - {}", session);
        // 移除用户
        webSockets.remove(this);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        log.info("\n 连接异常 - {}\n异常信息 - {}", sessionId, exception);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("\n websocket消息 收到客户端消息:{}", message);
        JSONObject obj = new JSONObject();
        obj.set(WebsocketConst.MSG_CMD, WebsocketConst.CMD_CHECK);//业务类型
        obj.set(WebsocketConst.MSG_TXT, "心跳响应");//消息内容
        sendMessageToUserByText(session, obj.toString());
    }

    // 此为广播消息
    public void sendAllMessage(String message) {
        log.info("\n websocket消息 广播消息:" + message);
        for (WebSocketServer webSocket : webSockets) {
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(String userId, String message) {
        sendMessageToSingleUserByText(userId, message);
    }

    // 此为单点消息(多人)
    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            sendMessageToSingleUserByText(userId, message);
        }
    }

    /**
     * 发送文本消息
     *
     * @param session 自己的用户名
     * @param message 消息内容
     */
    public static void sendMessageToUserByText(Session session, String message) {
        if (session != null) {
            session.getAsyncRemote().sendText(message);
        } else {
            log.info("\n[你已离线]");
        }
    }

    public void sendMessageToSingleUserByText(String userId, String message) {
        log.info("\n websocket消息 发送给:{}, 单点消息:{}", userId, message);
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                synchronized (session) {
                    session.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            log.info("\n[你已离线]");
        }
    }
}
