package com.jy.business.listener;

import com.alibaba.fastjson2.JSON;
import com.jy.business.config.RabbitConfig;
import com.jy.business.contract.dao.ContractFundReceivedDao;
import com.jy.business.contract.model.entity.ContractFundReceived;
import com.jy.framework.model.constants.CommonConstant;
import com.rabbitmq.client.Channel;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Slf4j
@Component
public class ContractFundReceivedRabbitListener {

    @Autowired
    private ContractFundReceivedDao contractFundReceivedDao;

    @Transactional(rollbackFor = Exception.class)
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(RabbitConfig.CONTRACT_FUND_RECEIVED_QUEUE),
                    exchange = @Exchange(RabbitConfig.JY_DIRECT_EXCHANGE)
            )
    })
    public void msgSend(String msg, Channel channel, Message message) throws IOException {
        log.info("mq收到到账认领消息:【{}】", msg);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            ContractFundReceived dto = JSON.parseObject(msg).to(ContractFundReceived.class);
            handle(dto);

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

    private void handle(ContractFundReceived dto) {
        dto.setHasReceived(CommonConstant.NO);
        contractFundReceivedDao.save(dto);
    }

}
