package org.xyzh.workcase.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;

import org.xyzh.api.workcase.constant.WorkcaseConstant;
import org.xyzh.api.workcase.dto.TbChatRoomMessageDTO;
import org.xyzh.api.workcase.vo.ChatRoomMessageVO;
import org.xyzh.workcase.mapper.TbChatMessageMapper;

/**
 * @description    聊天消息Redis监听器，接收Pub/Sub消息并通过STOMP转发到WebSocket客户端
 * @filename    ChatMessageListener.java
 * @author    cascade
 * @copyright xyzh
 * @since 2025-12-22
 */
@Component
public class ChatMessageListener implements MessageListener {
    private static final Logger logger = LoggerFactory.getLogger(ChatMessageListener.class);

    @Autowired(required = false)
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private TbChatMessageMapper chatMessageMapper;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            String channel = new String(message.getChannel());
            String body = new String(message.getBody());

            logger.debug("收到Redis消息: channel={}", channel);

            // 反序列化消息
            TbChatRoomMessageDTO chatMessage = JSON.parseObject(body, TbChatRoomMessageDTO.class);

            if (messagingTemplate == null) {
                logger.warn("SimpMessagingTemplate未初始化，无法转发消息");
                return;
            }

            // 处理聊天室消息频道: chat:room:{roomId}
            if (channel.startsWith(WorkcaseConstant.REDIS_CHAT_PREFIX)) {
                String roomId = channel.substring(WorkcaseConstant.REDIS_CHAT_PREFIX.length());
                
                // 查询完整的VO数据（包含senderAvatar等额外字段）
                ChatRoomMessageVO messageVO = chatMessageMapper.selectChatMessageVOById(chatMessage.getMessageId());
                if (messageVO != null) {
                    // 转发完整VO到聊天窗口订阅者
                    messagingTemplate.convertAndSend("/topic/chat/" + roomId, messageVO);
                    logger.debug("消息已转发到STOMP: /topic/chat/{}", roomId);
                } else {
                    logger.warn("未找到消息VO: messageId={}", chatMessage.getMessageId());
                }
            }
            // 处理列表更新频道: chat:list:update
            else if (WorkcaseConstant.REDIS_CHAT_LIST_UPDATE.equals(channel)) {
                // 转发到聊天室列表订阅者，前端刷新列表状态
                messagingTemplate.convertAndSend("/topic/chat/list-update", chatMessage);
                logger.debug("列表更新已转发到STOMP: /topic/chat/list-update");

                // 同时转发到对应聊天室频道，确保聊天窗口也能收到消息
                String roomId = chatMessage.getRoomId();
                if (roomId != null && !roomId.isEmpty()) {
                    // 查询完整的VO数据
                    ChatRoomMessageVO messageVO = chatMessageMapper.selectChatMessageVOById(chatMessage.getMessageId());
                    if (messageVO != null) {
                        messagingTemplate.convertAndSend("/topic/chat/" + roomId, messageVO);
                        logger.debug("列表更新消息同时转发到聊天室: /topic/chat/{}", roomId);
                    } else {
                        // 如果查不到VO（可能事务未提交），直接用DTO转发
                        logger.warn("未找到消息VO，使用DTO转发: messageId={}", chatMessage.getMessageId());
                        messagingTemplate.convertAndSend("/topic/chat/" + roomId, chatMessage);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("处理Redis消息失败", e);
        }
    }
}
