package com.kym.admin.mq.consumer;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.kym.entity.common.Queues;
import com.kym.entity.miniapp.UserCoupon;
import com.kym.service.miniapp.UserCouponService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;


/**
 * 用户优惠券消费者
 *
 * @author skyline
 */
@Slf4j
@Component
public class UserCouponConsumer {

    private final UserCouponService userCouponService;

    public UserCouponConsumer(UserCouponService userCouponService) {
        this.userCouponService = userCouponService;
    }

    @RabbitHandler
    @RabbitListener(queues = Queues.DELAY_USER_COUPON_QUEUE)
    @DS("db-miniapp")
    public void userCouponHandler(List<Message> messages, Channel channel) {
        try {
            List<UserCoupon> userCouponList = messages.stream()
                    .map(item -> JSONObject.parseObject(new String(item.getBody()), UserCoupon.class)).toList();

            // 存入 t_user_coupon
            userCouponService.saveBatch(userCouponList);

            // todo 推送用户收到优惠券

            // 消息逐个ack
            for (Message message : messages) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}