package com.jy.business.listener;

import com.alibaba.fastjson2.JSON;
import com.jy.business.capital.model.dto.CapitalTransactionsDto;
import com.jy.business.capital.service.CapitalTransactionsService;
import com.jy.business.config.RabbitConfig;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class JyRabbitListener {

    @Resource
    private CapitalTransactionsService capitalTransactionsService;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(RabbitConfig.TRANSACTIONS_QUEUE),
                    exchange = @Exchange(RabbitConfig.JY_DIRECT_EXCHANGE)
            )
    })
    public void msgSend(String msg, Channel channel, Message message) throws IOException {
        log.info("消费者收到消息:【{}】", msg);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            CapitalTransactionsDto dto = JSON.parseObject(msg).to(CapitalTransactionsDto.class);
            dto.setTargetType(80);
            capitalTransactionsService.add(dto);

            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            channel.basicNack(deliveryTag, false, true);
            log.error("消息消费失败:【{}】", e.getMessage(), e);
        }

    }

}
