package cn.van.business.mq;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.util.concurrent.RateLimiter;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import static cn.hutool.core.thread.ThreadUtil.sleep;
import static cn.van.business.util.WXUtil.WX_BASE_URL;

/**
 * @author Leo
 * @version 1.0
 * @create 2024/12/1 上午2:06
 * @description：
 */
@Service
@RocketMQMessageListener(topic = "wx-message", consumerGroup = "${rocketmq.consumer.group}",nameServer = "${rocketmq.name-server}")
public class MessageConsumerService implements RocketMQListener<JSONObject> {

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

    // create a rate limiter of 1 qps
    RateLimiter rateLimiter = RateLimiter.create(0.5);
    @Override
    public void onMessage(JSONObject jsonObject) {
        // 处理消息
        try {
            rateLimiter.acquire(); // 请求许可。如果超过速率，则此方法会阻塞
            //logger.info("消费到消息：{}", jsonObject);
            String body = jsonObject.getString("body");
            byte[] decodedBody = Base64.getDecoder().decode(body);
            String decodedBodyStr = new String(decodedBody, StandardCharsets.UTF_8);
            JSONObject decodedBodyJson = JSONObject.parseObject(decodedBodyStr);
            String responseStr = HttpRequest.post(WX_BASE_URL)
                    .body(JSONUtil.toJsonStr(decodedBodyJson))
                    .execute()
                    .body();

            if (ObjectUtil.isNotEmpty(responseStr)) {
                JSONObject response = JSONObject.parseObject(responseStr);
                if (response.getInteger("code") != 200) {
                    // TODO: 如果需要处理错误，您可以在这里添加逻辑
                    throw new RuntimeException("消息发送失败: " + responseStr);
                }
                //logger.info("消息成功发送并得到响应：{}", response);
            } else {
                throw new RuntimeException("消息发送失败，没有收到响应");
            }
        } catch (Exception e) {
            //logger.error("处理消息时发生错误", e);
            throw e; // 重抛异常使得 RocketMQ 可以捕获到这个异常
        }

    }
}
