package com.nmgs.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nmgs.service.UserTableService;
import com.nmgs.service.impl.UserTableServiceImpl;
import com.nmgs.util.LogUtil;
import com.nmgs.util.WebsocketUtil;
import com.nmgs.util.WebsocketUtilRedis;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.List;
import java.util.Map;

@Component
@ServerEndpoint(value = "/webSocket/{userId}")
public class WebSocket {
    Log log= LogFactory.getLog(WebSocket.class);

    @OnOpen
    public void onOpen(Session session,@PathParam(value = "userId") String userId) throws IOException {
        LogUtil.WriteLog_Info("连接websocket的人员======" + userId, "WebSocket");
        WebsocketUtil.addSession(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) {
        LogUtil.WriteLog_Info("关闭连接的人员======" + userId, "WebSocket");
        String socketId = userId;
        WebsocketUtil.removeSession(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.removeSession(socketId);
            if (session.isOpen()) {
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        throwable.printStackTrace();
    }
}