package com.jiayue.ssi.service;

import com.alibaba.fastjson2.JSON;
import com.jiayue.ssi.config.WebSocketConfigurator;
import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.dto.ActiveUserDto;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.util.LocalCache;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;

/**
*
*
* @author xsl
* @since 2023/08/21
*/
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/testsocket",configurator = WebSocketConfigurator.class)
public class WebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

//    public WebSocketServer() {
//        log.info("Websocket创建" + new Date().getTime());
//    }

        /**
         * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        try {
            Map<String, Object> userProperties = session.getUserProperties();
            ActiveUserDto activeUserDto = (ActiveUserDto) userProperties.get("ActiveUserDto");
            SysUser sysUser = activeUserDto.getSysUser();
            CacheConstants.SESSIONID_USER_MAP.put(session.getId(),sysUser.getUsername());
            addOnlineCount();
//            log.info("连接成功，当前系统心跳连接数："+getOnlineCount());
//            if (getOnlineCount()>3){
//                log.info("超出连接数，关闭本次连接");
//                onClose(session);
//            }
            sendMessage("连接成功");
        } catch (Exception e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        try {
            subOnlineCount();
//            log.info("断开连接，当前系统心跳连接数："+getOnlineCount());
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) throws Exception{
        Map<String, Object> userProperties = session.getUserProperties();
        ActiveUserDto activeUserDto = (ActiveUserDto) userProperties.get("ActiveUserDto");
        SysUser sysUser = activeUserDto.getSysUser();
        // 如果某个用户被踢掉，则不接收此用户的sessionid的心跳
        if (CacheConstants.SESSIONID_USER_MAP.get(session.getId())!=null){
            LocalCache.set(CacheConstants.HEART_KEY+sysUser.getUsername(),"在线",7000);
            this.session.getBasicRemote().sendText((JSON.toJSONString(session.getId())));
        }
        else{
            onClose(session);
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
//        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(Object obj)  {
        try {
            synchronized (this.session) {
                this.session.getBasicRemote().sendText((JSON.toJSONString(obj)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


//    /**
//     * 群发自定义消息
//     * */
//    public static void sendInfo(Object obj) {
//        for (WebSocketServer item : webSocketSet) {
//            try {
//                item.sendMessage(obj);
//            } catch (Exception e) {
//                continue;
//            }
//        }
//    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }


}
