package com.seer.teach.mall.app.order.mq;

import cn.hutool.json.JSONUtil;
import com.seer.teach.common.constants.CommonConstant;
import com.seer.teach.mall.app.order.service.IAppOrderExpireService;
import com.seer.teach.mall.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.util.List;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "mall.order", name = "delay.enabled", havingValue = "true", matchIfMissing = true)
public class OrderExpireConsumerMqService {

    @Value("${rocketmq.name-server:}")
    private String nameServer;

    @Value("${rocketmq.consumer.group:}")
    private String consumerGroup;

    private DefaultMQPushConsumer consumer;

    @Autowired
    private IAppOrderExpireService appOrderExpireService;

    @PostConstruct
    public void consumer() throws MQClientException {
        consumer = new DefaultMQPushConsumer(consumerGroup);
        consumer.setNamesrvAddr(nameServer);

        // 订阅主题
        consumer.subscribe(CommonConstant.ORDER_CREATE_DELAY_TOPIC, "*");

        // 设置消息监听器（这里只是一个示例）
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    try {
                        String msgBody = new String(msg.getBody(), "UTF-8");
                        log.info("Received Message - Topic: {}, MsgId: {}, Body: {}",
                                msg.getTopic(), msg.getMsgId(), msgBody);

                        OrderEntity order = JSONUtil.toBean(msgBody, OrderEntity.class);
                        appOrderExpireService.processExpiredOrder(order);
                    } catch (Exception e) {
                        log.error("Error processing message", e);
                        // 返回 RECONSUME_LATER 表示稍后重试
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                }
                // 返回 CONSUME_SUCCESS 表示消费成功
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        try {
            consumer.start();
            log.info("RocketMQ Consumer Started. Group: {}, Topic: {}, NameServer: {}",
                    consumerGroup, CommonConstant.ORDER_CREATE_DELAY_TOPIC, nameServer);
        } catch (MQClientException e) {
            log.error("Failed to start RocketMQ Consumer", e);
        }
    }

    @PreDestroy
    public void destroy() {
        if (consumer != null) {
            consumer.shutdown();
        }
        log.info("RocketMQ Consumer shutdown.");
    }
}