package com.tzy.listener.mq;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.tzy.common.constant.MqConstans;
import com.tzy.sportcard.api.dto.ResourceData;
import com.tzy.sportcard.api.service.AsyncAppService;
import com.tzy.sportcard.api.service.GroupApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;


@Slf4j
@Component
public class PayPreCallBackConsumer {
    @Autowired
    private GroupApiService groupApiService;
    @Resource
    private AsyncAppService asyncAppService;


    /**
     * 回调前置消费
     * @param data
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queuesToDeclare=@Queue(MqConstans.QUEUE_PRE_PAY_CALLBACK))
    public void payPreCallBack(String data, Channel channel, Message message) throws IOException {
        payCallBackConsumer(data, channel, message);
    }

    private void payCallBackConsumer(String param, Channel channel, Message message) throws IOException {
        try {
            ResourceData data=JSON.parseObject(param,ResourceData.class);
            groupApiService.prePayByMQ(data);
            asyncAppService.sendPayNotice(data.getOut_trade_no());
            //发送 mq 推送到 订单来源
            asyncAppService.sendPromotionOrderMq(data.getOrderId());
            //todo 后续消费达标的任务要加在这里和拼团成团和退款的消息处理器上面
        } catch (Exception e) {
            log.error("卡密分配消费失败,{}", param, e);
        }
        channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
    }


}
