package com.education.business.message.mq;

import cn.hutool.json.JSONUtil;
import com.education.business.message.param.WebSocketMessage;
import com.education.business.webSocket.SystemWebSocketHandler;
import com.education.common.enums.SocketMessageTypeEnum;
import com.education.common.utils.ObjectUtils;
import com.education.model.dto.SocketMessageCommand;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import javax.annotation.Resource;
import java.util.List;

/**
 * webSocket消息监听
 * @author zjt
 * @version 1.0.7
 * @Description
 * @createTime 2025/2/25 9:56
 */

public abstract class WenSocketMessageListener<T extends WebSocketMessage> extends AbstractMqMessageListener<T> {


    private static final Logger logger = LoggerFactory.getLogger(WenSocketMessageListener.class);

    @Resource
    private List<WenSocketMessageListener> webSocketMessageListenerList;

    @Resource
    protected SystemWebSocketHandler systemWebSocketHandler;

    @Override
//    @RabbitListener(queues = "${rabbitmq.socket.queue}")
    public void onMessage(Message message, Channel channel) {
        super.onMessage(message, channel);
    }

    @Override
    void doBizMessage(T webSocketMessage) {
        if (ObjectUtils.isEmpty(webSocketMessageListenerList)) {
            return;
        }
        WenSocketMessageListener target = webSocketMessageListenerList.stream()
                .filter(wenSocketMessageListener -> wenSocketMessageListener.getSocketMessageTypeEnum().getCode()
                .equals(webSocketMessage.getSocketMessageTypeEnum().getCode()))
                .findAny()
                .orElse(null);
        if (target == null) {
            logger.warn("当前socket:{}枚举对象不存在", webSocketMessage.getSocketMessageTypeEnum());
            return;
        }
        SocketMessageCommand socketMessageCommand = target.getSocketMessageCommand(webSocketMessage);
        if (ObjectUtils.isNotEmpty(webSocketMessage.getHashToken())) {
            systemWebSocketHandler.sendMessageByHashToken(webSocketMessage.getHashToken(), JSONUtil.toJsonStr(socketMessageCommand));
            return;
        }

        if (ObjectUtils.isNotEmpty(webSocketMessage.getUserId())) {
            systemWebSocketHandler.sendMessageByUserId(webSocketMessage.getUserId(),
                    webSocketMessage.getPlatformEnum().getCode(), JSONUtil.toJsonStr(socketMessageCommand));
        }
    }


    /**
     * socket消息业务监听
     */
    abstract SocketMessageCommand getSocketMessageCommand(T webSocketMessage);


    /**
     * 获取类型枚举
     * @return
     */
    abstract SocketMessageTypeEnum getSocketMessageTypeEnum();
}
