package org.gyk.modules.websocket;


import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@RestController
@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")
@Mapper
@Service

public class webSocket {
    private Session session;

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

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            this.session = session;
            webSockets.add(this);
            sessionPool.put(userId, session);
            log.info("【websocket消息】有新的连接，总数为:" + webSockets.size());
        } catch (Exception e) {
        }
    }

    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            log.info("【websocket消息】连接断开，总数为:" + webSockets.size());
        } catch (Exception e) {
        }
    }

    @OnMessage
    public void onMessage(String message) {
        log.debug("【websocket消息】收到客户端消息:" + message);

        //心跳检测响应
        if (StringUtils.equalsIgnoreCase("天王盖地虎", message)) {
            JSONObject pingWebSocket = new JSONObject();
            pingWebSocket.put("cmd","ping");
            pingWebSocket.put("msgId", "6666");//消息id
            pingWebSocket.put("msgTxt", "宝塔镇河妖");//消息内容

//            webSocket.sendAllMessage(pingWebSocket.toJSONString());
            session.getAsyncRemote().sendText(pingWebSocket.toJSONString());
            log.debug("[WebSocket]服务端 已回复客户端{} 的心跳检测: 宝塔镇河妖", session.getId());
        }
    }

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

    // 此为单点消息
    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                log.info("【websocket消息】 单点消息:" + message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息(多人)
    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    log.info("【websocket消息】 单点消息:" + message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @OnError
    public void onError(Session session, Throwable t) {
        log.info("发生错误");
        t.printStackTrace();
    }

}
