package cn.estsh.i3plus.core.apiservice.websocket;

import cn.estsh.i3plus.platform.common.util.CommonConstWords;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
import java.util.concurrent.ConcurrentMap;

/**
 * @Description : 消息
 * @Reference :
 * @Author : yunhao
 * @CreateDate : 2018-11-24 16:57
 * @Modify:
 **/
@ServerEndpoint(value= PlatformConstWords.WEBSOCKET_URL + "/message-websocket/{userId}")
@Component
public class MessageWebSocket {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageWebSocket.class);

    private long userId = 1L;
    //websocket会话
    private Session session;    //  当前对象会话
    private static int sendCount = 1;
    //concurrent线程安全集合，存放客户端websocket对象
    private static ConcurrentMap<Long,MessageWebSocket> webSocketSet = new ConcurrentHashMap<Long,MessageWebSocket>();

    @OnOpen
    public void onOpen(@PathParam("userId")long userId, Session session){
        this.userId = userId;
        this.session = session;

        webSocketSet.put(userId,this);           //在线人数添加
        LOGGER.info("{}加入！当前在线人数为{}",userId,getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        subOnlineUser(this.userId);
        LOGGER.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(@PathParam("userId")Long userId,String message) {
        // 心跳
        if("heartBit".equals(message)){
            this.sendMessage(userId,"heartBit");
        }else{
            LOGGER.info("来自客户端的消息:" , message);
        }
    }

    /**
     * 发生错误时调用
     * @OnError
     */
    @OnError
    public void onError(Session session, Throwable error) {
        LOGGER.info("发生错误");
        error.printStackTrace();
    }

    /**
     * 发送消息
     * @param message
     * @throws IOException
     */
    public static void sendMessage(Long userId, String message){
        try {
            MessageWebSocket websocket = webSocketSet.get(userId);
            if(websocket != null) {
                if (message.equals("heartBit")) {
                    websocket.session.getBasicRemote().sendText(message + "=" + sendCount);
                    sendCount++;
                } else {
                    websocket.session.getBasicRemote().sendText(message);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static synchronized int getOnlineCount() {
        return webSocketSet.size();
    }

    public synchronized void subOnlineUser(long userId) {
        webSocketSet.remove(userId);
    }
}
