package com.ruoyi.jarvis.mq;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.jarvis.dto.GoofishNotifyMessage;
import com.ruoyi.jarvis.service.goofish.GoofishOrderPipeline;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 闲管家订单推送消费（需配置 rocketmq.name-server）。
 * <p>
 * 在此线程内同步执行 {@link GoofishOrderPipeline#runFullPipeline}，避免再投递 {@code @Async} 线程池造成
 * 「MQ 堆积 + goofishTaskExecutor 排队」的双重延迟；回调 HTTP 已在 {@link com.ruoyi.jarvis.service.impl.ErpGoofishOrderServiceImpl#publishOrProcessNotify} 中快速返回。
 */
@Component
@ConditionalOnProperty(name = "rocketmq.name-server")
@RocketMQMessageListener(
    nameServer = "${rocketmq.name-server}",
    topic = "${jarvis.goofish-order.mq-topic:jarvis-goofish-erp-order}",
    consumerGroup = "${jarvis.goofish-order.consumer-group:jarvis-goofish-order-consumer}"
)
public class GoofishOrderNotifyConsumer implements RocketMQListener<String> {

    @Resource
    private GoofishOrderPipeline goofishOrderPipeline;

    @Override
    public void onMessage(String message) {
        GoofishNotifyMessage m = JSON.parseObject(message, GoofishNotifyMessage.class);
        if (m == null || m.getAppid() == null) {
            return;
        }
        JSONObject body = m.getBody() == null ? new JSONObject() : JSON.parseObject(m.getBody());
        if (body == null) {
            body = new JSONObject();
        }
        goofishOrderPipeline.runFullPipeline(m.getAppid(), body);
    }
}
