package cn.sikey.websocket.client.handler;

import cn.hutool.json.JSONUtil;
import cn.sikey.websocket.controller.app.message.vo.SaveMessageSendReqVO;
import cn.sikey.websocket.enums.MessageStatus;
import cn.sikey.websocket.enums.MessageType;
import cn.sikey.websocket.message.BasicMessage;
import cn.sikey.websocket.message.Message;
import cn.sikey.websocket.message.MessageId;
import cn.sikey.websocket.message.MessageReceivedLog;
import cn.sikey.websocket.service.MessageSendService;
import cn.sikey.websocket.service.MessagingSubscribeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @Author: nelson
 * @Date: 2025/5/30
 * @Description: 收到mq消息
 */
@Slf4j
@Component
@RabbitListener(queues = "publish_mcdisk_queue")
public class MessageQueueHandler {

    @Resource
    private MessagingSubscribeService messagingSubscribeService;

    @Resource
    private MessageSendService messageSendService;

    /**
     * 接收聊天文本消息
     *
     * @param chatTextMessage 聊天文本消息
     */
    @RabbitHandler
    public void receiveChatTextMessage(@Payload BasicMessage chatTextMessage) {
        log.info("收到mq消息: {}", JSONUtil.toJsonPrettyStr(chatTextMessage));
        Message message = convertMessage(chatTextMessage);
        messagingSubscribeService.consumeMessage(message);
    }

    /**
     * 转换消息
     *
     * @param basicMessage 基础消息
     * @return 消息
     */
    private Message convertMessage(BasicMessage basicMessage) {
        MessageId messageId = new MessageId(basicMessage.getMsgId());
        Message message = find(messageId);
        message.setReceiverId(List.of(basicMessage.getRecvId()));
        message.setReceivedLogs(
                List.of(new MessageReceivedLog().setReceiverId(basicMessage.getRecvId()).setStatus(MessageStatus.DEFAULT)));
        return message;
    }

    private Message find(MessageId messageId) {
        SaveMessageSendReqVO messageSendModel = messageSendService.findMessageSendById(messageId);
        return new Message()
                .setId(messageId)
                .setType(MessageType.valueOf(messageSendModel.getMsgType()))
                .setSenderId(messageSendModel.getSenderId())
                .setSendTime(messageSendModel.getSendTime())
                .setContent(messageSendModel.getContent());
    }
}
