package com.zanxiang.game.module.manage.websocket;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zanxiang.game.module.manage.enums.KfWebSocketMsgEnum;
import com.zanxiang.game.module.manage.pojo.dto.KfWebSocketMsgDTO;
import com.zanxiang.module.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;

/**
 * @author : lingfeng
 * @time : 2024-03-05
 * @description : Websocket心跳
 */
@Slf4j
@Component
public class KfMsgWebsocketHeartbeat {

    @Autowired
    private KfMsgWebSocketSessionRegistry kfMsgWebSocketSessionRegistry;

    /**
     * Websocket每20秒给客户端发送一次心跳
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void sessionHeartbeat() {
        List<WebSocketSession> sessionList = kfMsgWebSocketSessionRegistry.getAllSessions();
        if (CollectionUtils.isEmpty(sessionList)) {
            return;
        }
        sessionList.forEach(this::sendHeartbeat);
    }

    private void sendHeartbeat(WebSocketSession session) {
        //会话不存在或者未开启
        if (session == null || !session.isOpen()) {
            return;
        }
        Object kfUserId = session.getAttributes().get("kfUserId");
        KfWebSocketMsgDTO webSocketMsgDTO = KfWebSocketMsgDTO.builder()
                .webSocketMsgType(KfWebSocketMsgEnum.WEBSOCKET_MSG_CONNECT_HEART_BEAT)
                .kfUserId(kfUserId == null ? null : Long.valueOf(kfUserId.toString()))
                .build();
        try {
            session.sendMessage(new TextMessage(JsonUtil.toString(webSocketMsgDTO)));
        } catch (Exception e) {
            log.error("给客户端发送心跳消息异常, kfUserId : {}, e : {}", JsonUtil.toString(kfUserId), e.getMessage());
        }
    }
}
