package com.ssyf.task.websocket;

import com.ssyf.plugs.cache.customs.CustomRedisMessageListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 *
 * @author huwei
 * @date 2025/6/26 16:02
 */
@Slf4j
@Component
public class WsMessageListener implements MessageListener , CustomRedisMessageListener {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private WsStatisticsService wsStatisticsService;
    /**
     * redis任务
     */
    public static final String TOPIC_PREFIX = "RobotWsMessageListener";

    @Override
    public List<String> topics() {
        return Collections.singletonList(TOPIC_PREFIX);
    }

    @Override
    public MessageListener listener() {
        return this;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.debug("收到任务消息:" + message);
        WsMessageTask wsMessageTask = (WsMessageTask) redisTemplate.getValueSerializer().deserialize(message.toString().getBytes());
        if(wsMessageTask == null || wsMessageTask.getRoomId() == null){
            log.warn("收到任务消息为空:" + message);
            return;
        }
        if(Objects.equals(wsMessageTask.getType(), "updateClientId")){
            wsStatisticsService.updateClientIdByListener(wsMessageTask.getRoomId());
        }
    }
}
