package com.tzy.listener.mq;

import com.rabbitmq.client.Channel;
import com.tzy.app.dto.mq.OrderGoodsParam;
import com.tzy.common.constant.MqConstans;
import com.tzy.framework.util.RedisUtils;
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.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * 放弃执行
 * @author po'yi
 */
@Slf4j
//@Component
public class OrderPayConsumer {
    @Autowired
    private GroupApiService groupApiService;
    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Autowired
    private RedisUtils redisUtils;

    private boolean assignCardGoods(OrderGoodsParam goodsParam){
        String lockKey = "order_goods_lock_key" + goodsParam.getGroupInfoId();
        boolean isLock=false;
        //1.获取事务定义
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        def.setIsolationLevel(2);
        TransactionStatus status=null;
        try {
            isLock = redisUtils.tryLock(lockKey, TimeUnit.SECONDS, 10L, 31L);
            if (isLock) {
                status = transactionManager.getTransaction(def);
                //groupApiService.assignCardGoods(goodsParam);
                //groupApiService.updateInfoData(goodsParam);
                transactionManager.commit(status);
                redisUtils.unlock(lockKey);
                return true;
            }
        } catch (Exception e) {
            log.error("卡密分配异常,参数:{}",goodsParam, e);
            if(status!=null){
                transactionManager.rollback(status);
            }
        } finally {
            try {
                if(isLock){
                    redisUtils.unlock(lockKey);
                }
            } catch (Exception e) {
                log.error("卡密分配锁释放异常:{}", goodsParam, e);
            }
        }
        log.info("卡密分配提前结束,获取锁状态:{},参数:{}",isLock,goodsParam);
        return false;
    }

    /**
     * 支付回调消费
     * @param data
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    @RabbitListener(queuesToDeclare=@Queue(MqConstans.QUEUE_ORDER_PAY_CALLBACK))
    public void orderPayCallBack(OrderGoodsParam data, Channel channel, Message message) throws IOException {
        try {
            if(assignCardGoods(data)){
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
        } catch (Exception e) {
            log.error("卡密分配消费失败,{}",data.toString(),e);
        }
        //失败后消息放回
        channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
    }
}
