package org.dromara.common.mq.utils;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultLitePullConsumer;
import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.consumer.LitePullConsumer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.mq.config.RocketMQConfig;
import org.dromara.common.mq.domain.MQMessage;
import org.dromara.common.mq.enums.MQMessageType;
import org.dromara.common.mq.enums.MessageActionEnum;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Member;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static org.dromara.common.mq.enums.MQMessageType.COMMENT;

@Slf4j
@Component
public class MqUtil implements ApplicationContextAware {
    private static final String NAME_SERVER_ADDR = "localhost:9876";
    private static final String CONSUMER_GROUP = "TEST_PULL_GROUP";
    private static final String TOPIC = "TEST_TOPIC";
    private static RocketMQTemplate template;
    private static Map<String, LitePullConsumer> consumerMap = new ConcurrentHashMap<>();
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        template = applicationContext.getBean(RocketMQTemplate.class);
    }

    public void init() throws Exception {
        // 1. 创建消费者实例，指定消费者组
        DefaultLitePullConsumer  consumer = new DefaultLitePullConsumer("YOUR_PULL_CONSUMER_GROUP");

        consumer.setNamesrvAddr("localhost:9876"); // 替换为您的NameServer地址
        consumer.subscribe("YOUR_TOPIC", "*");
        consumer.start();
        // 3. 设置从何处开始消费（首次启动时）
        //consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        // 4. 订阅主题和Tag
        consumer.subscribe("YOUR_TOPIC", "*"); // 使用*消费所有Tag
        // 5. 启动消费者
        consumer.start();
        System.out.println("LitePullConsumer 启动成功");
    }

    //
    public static void sendMessage(String destination, MQMessage message) {
        if (template == null) {
            log.error("RocketMQTemplate未初始化，无法发送消息");
            return;
        }

        try {
            String jsonMessage = JsonUtils.toJsonString(message);
            template.convertAndSend(destination, jsonMessage);
            log.info("发送消息到RocketMQ成功，topic: {}, message: {}", destination, jsonMessage);
        } catch (Exception e) {
            log.error("发送消息到RocketMQ失败，topic: {}, message: {}", destination, message, e);
        }
    }
    public static void sendIMMessage( MQMessage message) {
        if (template == null) {
            log.error("RocketMQTemplate未初始化，无法发送消息");
            return;
        }

        try {
            String jsonMessage = JsonUtils.toJsonString(message);
            template.convertAndSend(RocketMQConfig.TOPIC_IM_MSG, jsonMessage);
            log.info("发送消息到RocketMQ成功，topic: {}, message: {}", RocketMQConfig.TOPIC_IM_MSG, jsonMessage);
        } catch (Exception e) {
            log.error("发送消息到RocketMQ失败，topic: {}, message: {}", RocketMQConfig.TOPIC_IM_MSG, message, e);
        }
    }


    public static void sendMessage(String topic, String tag, MQMessage message) {
        if (template == null) {
            log.error("RocketMQTemplate未初始化，无法发送消息");
            return;
        }

        try {
            String destination = topic + ":" + tag;
            String jsonMessage = JsonUtils.toJsonString(message);
            template.convertAndSend(destination, jsonMessage);
            log.info("发送消息到RocketMQ成功，destination: {}, message: {}", destination, jsonMessage);
        } catch (Exception e) {
            log.error("发送消息到RocketMQ失败，topic: {}, tag: {}, message: {}", topic, tag, message, e);
        }
    }
    public static void sendDelayMessage(String topic, String tag, MQMessage message, int delayTimeLevel) {
        if (template == null) {
            log.error("RocketMQTemplate未初始化，无法发送延迟消息");
            return;
        }

        try {
            String destination = topic + ":" + tag;
            String jsonMessage = JsonUtils.toJsonString(message);
            template.asyncSend(destination, MessageBuilder.withPayload(jsonMessage).build(),
                new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        log.info("发送延迟消息到RocketMQ成功，destination: {}, message: {}, result: {}",
                            destination, jsonMessage, sendResult);
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        log.error("发送延迟消息到RocketMQ异常，destination: {}, message: {}",
                            destination, jsonMessage, throwable);
                    }
                }, 3000, delayTimeLevel);
        } catch (Exception e) {
            log.error("发送延迟消息到RocketMQ失败，topic: {}, tag: {}, message: {}", topic, tag, message, e);
        }
    }



}
