package com.ltgk.boat.handler;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.ltgk.boat.config.websocket.WebSocketSessionMap;
import com.ltgk.boat.service.BoatAlarmInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * 业务板块首页滚动告警 websocket handler
 *
 * @author Qi ChengBin
 * @date 2025/03/11
 */
@Slf4j
@Component
public class IndexAlarmInfoWebsocketHandler extends AbstractWebSocketHandler {

    @Resource
    private BoatAlarmInfoService boatAlarmInfoService;

    private final Map<String, WebSocketSession> webSocketSessionMap = new WebSocketSessionMap().sharedMap();

    /**
     * websocket 连接
     *
     * @param session:
     * @author Qi ChengBin
     * @date 2025/3/12
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("websocket连接成功，接收到session：{}", session);
        boatAlarmInfoService.saveWebsocketSession(session);
    }

    /**
     * websocket 接收数据
     *
     * @param session:
     * @param message:
     * @author Qi ChengBin
     * @date 2025/3/12
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        log.info("websocket接收到消息：{}", message);
        log.info("websocket接收到message：{}", JSON.toJSON(message.getPayload()));
        Map<String, Object> resMap =  boatAlarmInfoService.assembledSendData();
        session.sendMessage(new TextMessage(JSONUtil.toJsonStr(resMap)));
    }

    /**
     * 监控断开链接 删除redis缓存
     *
     * @param session:
     * @param closeStatus:
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
        log.info("websocket断开链接，接收到session：{}", session);
        // 删除 session 对象
        if (this.webSocketSessionMap.containsKey(session.getId())) {
            this.webSocketSessionMap.remove(session.getId());
        }
    }

}
