package com.ruoyi.framework.webSocket;

import com.alibaba.fastjson2.JSONObject;
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.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    /**
     * 线程安全list，用来存放 在线客户端账号
     */
    public static List<String> userList = new CopyOnWriteArrayList<>();


    /**
     * 连接成功
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        sessionPools.put(userId, session);
        if (!userList.contains(userId)) {
            addOnlineCount();
            userList.add(userId);
        }
        log.debug("ID为【" + userId + "】的用户加入websocket！当前在线人数为：" + onlineNum);
        log.debug("当前在线：" + userList);
    }

    /**
     * 关闭连接
     * @param userId
     */
    @OnClose
    public void onClose(@PathParam(value = "userId") String userId) {
        sessionPools.remove(userId);
        if (userList.contains(userId)) {
            userList.remove(userId);
            subOnlineCount();
        }
        log.debug(userId + "断开webSocket连接！当前人数为" + onlineNum);

    }

    /**
     * 消息监听
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject(message);
        String userId = jsonObject.getString("userId");
        String type = jsonObject.getString("type");
        if (type.equals(MessageType.CHAT.getType())) {
            sendToUser(userId, JSONObject.toJSONString(jsonObject));
        }
    }

    /**
     * 连接错误
     * @param session
     * @param throwable
     * @throws IOException
     */
    @OnError
    public void onError(Session session, Throwable throwable) throws IOException {
        log.error("websocket连接错误！");
        throwable.printStackTrace();
    }

    /**
     * 发送消息
     */
    public void sendMessage(Session session, String message) throws IOException, EncodeException {
        if (session != null) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 给指定用户发送信息
     */
    public void sendToUser(String userId, String message) {
        Session session = sessionPools.get(userId);
        try {
            if (session != null) {
                sendMessage(session, message);
            }else {
                log.debug("推送用户不在线");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();

    }
}