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.domain.entity.BoatAlarmInfo;
import com.ltgk.boat.service.IThreeNoBoatWebsocketService;
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.List;
import java.util.Map;

/**
 * 疑似三无船只websocket
 *
 * @author Qi ChengBin
 * @date 2025/07/04
 */
@Slf4j
@Component
public class ThreeNoBoatWebsocketHandler extends AbstractWebSocketHandler {

    @Resource
    private IThreeNoBoatWebsocketService threeNoBoatWebsocketService;

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

    /**
     * websocket 连接
     *
     * @param session:
     * @author Qi ChengBin
     * @date 2025/3/12
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("疑似三无船只websocket连接成功，接收到session：{}", session);
        threeNoBoatWebsocketService.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()));
        List<BoatAlarmInfo> resList = threeNoBoatWebsocketService.pushThreeNoBoatData();
        session.sendMessage(new TextMessage(JSONUtil.toJsonStr(resList)));
    }

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