package com.willalp.framework.websocket;

import com.willalp.common.core.domain.entity.SysUser;
import com.willalp.common.utils.StringUtils;
import com.willalp.common.websocket.ServerEncoder;
import com.willalp.framework.config.properties.CustomSpringConfigurator;
import com.willalp.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.concurrent.Semaphore;

/**
 * websocket 消息处理
 *
 * @author ruoyi
 */
@Component
@ServerEndpoint(value = "/websocket/message/{userCode}", encoders = {ServerEncoder.class}, configurator = CustomSpringConfigurator.class)
public class WebSocketServer {

    @Autowired
    private ISysUserService userService;

    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 默认最多允许同时在线人数100
     */
    public static int socketMaxOnlineCount = 100;

    private static final Semaphore SOCKET_SEMAPHORE = new Semaphore(socketMaxOnlineCount);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userCode") String userCode) throws Exception {
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(SOCKET_SEMAPHORE);
        if (!semaphoreFlag) {
            // 未获取到信号量
            LOGGER.error(" 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        } else {
            if (StringUtils.isNotBlank(userCode)) {
                SysUser sysUser = userService.selectUserByUserName(userCode);
                if (sysUser != null) {
                    // 添加用户
                    WebSocketUsers.put(userCode, session);
                    LOGGER.info("用户 [" + userCode + "] 建立连接");
                    LOGGER.info(" 当前人数 - " + WebSocketUsers.getUserSize());
                    WebSocketUsers.sendMessageToUserByText(session, "ping");
                }
            }
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session) {
        LOGGER.info(" 关闭连接 - " + session.getId());
        // 移除用户
        WebSocketUsers.remove(session.getId());
        // 获取到信号量则需释放
        SemaphoreUtils.release(SOCKET_SEMAPHORE);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        LOGGER.info(" 连接异常 - " + sessionId);
        LOGGER.info(" 异常信息 - " + exception);
        // 移出用户
        WebSocketUsers.remove(sessionId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(SOCKET_SEMAPHORE);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        WebSocketUsers.sendMessageToUserByText(session, message);
        LOGGER.info(" 收到客户端消息 - " + message);
    }
}
