package com.nmgs.controller;

import com.alibaba.fastjson.JSONObject;
import com.nmgs.util.WebsocketUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

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

/**
 * 给后端发送消息,利用redis  进行了订阅，此方法可屏蔽，此方法只支持单服务的
 */
@Component
@ServerEndpoint(value = "/webSocketCheckBak/{userId}")
public class WebSocketCheck {
    Log log= LogFactory.getLog(WebSocketCheck.class);

    @OnOpen
    public void onOpen(Session session,@PathParam(value = "userId") String userId) throws IOException {
        System.out.println("连接websocket的人员======"+userId);
        WebsocketUtil.addSessionCheck(userId, session);
        JSONObject retJo=new JSONObject();
        retJo.put("code",1);
        retJo.put("msg","连接成功");
        retJo.put("data","");
        WebsocketUtil.sendMessage(userId,JSONObject.toJSONString(retJo));
    }

    @OnClose
    public void onClose(Session session,@PathParam(value = "userId") String userId) {
        System.out.println("关闭连接的人员======"+userId);
        String socketId = userId;
        WebsocketUtil.removeSessionCheck(socketId);
    }
    @OnMessage
    public void onMessage(Session session,@PathParam(value = "userId") String userId, String message) {
        System.out.println("发送消息的人员======"+userId);
    }

    @OnError
    public void onError(Session session,@PathParam(value = "userId") String userId, Throwable throwable) {
        String socketId = session.getId();
        try {
            WebsocketUtil.removeSessionCheck(socketId);
            if (session.isOpen()) {
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        throwable.printStackTrace();
    }
}