package com.tzy.listener.mq;

import com.rabbitmq.client.Channel;
import com.tzy.app.dto.mq.OrderSuccessParam;
import com.tzy.common.constant.Constants;
import com.tzy.common.constant.MqConstans;
import com.tzy.coupon.card.domain.AppUserCardRecord;
import com.tzy.coupon.card.domain.TzyCardBaseInfo;
import com.tzy.coupon.card.mapper.AppUserCardRecordMapper;
import com.tzy.coupon.card.mapper.TzyCardBaseInfoMapper;
import com.tzy.sportcard.api.service.AsyncAppService;
import com.tzy.sportcard.group.domain.CardGroupOrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
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.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Component
public class OrderSuccessConsumer {

    @Autowired
    private AsyncAppService asyncAppService;
    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Resource
    private AppUserCardRecordMapper appUserCardRecordMapper;


    private boolean orderPaySuccess(OrderSuccessParam param) {
        //1.获取事务定义
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        def.setIsolationLevel(2);
        TransactionStatus status = null;
        try {
            status = transactionManager.getTransaction(def);
            asyncAppService.orderPaySuccess(param.getOrderInfo(), param.getCardGroupInfo());
            transactionManager.commit(status);
            //expireUserFirstCoupon(param.getOrderInfo());
            return true;
        } catch (Exception e) {
            log.error("订单异步执行错误,参数:{}", param, e);
            if (status != null) {
                transactionManager.rollback(status);
            }
        }
        return false;
    }

    public void expireUserFirstCoupon(CardGroupOrderInfo cardGroupOrderInfo){
        // 如果有首单券，未使用
        Long userId = cardGroupOrderInfo.getUserId();
        List<AppUserCardRecord> appUserCardRecordList = appUserCardRecordMapper.getUserFirstCoupons(userId);
        if(CollectionUtils.isEmpty(appUserCardRecordList)) {
            String orderType = cardGroupOrderInfo.getOrderType();
            if (Constants.ORDER_TYPE_GROUP.equals(orderType)) {
                // 拼团首单券未使用自动过期
                List<Long> expireCardIds = appUserCardRecordList.stream()
                        .filter(record -> Constants.COUPON_TYPE_CARD.equals(record.getUseScope()))
                        .map(AppUserCardRecord::getId)
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(expireCardIds)) {
                    appUserCardRecordMapper.expireUserCardRecord(expireCardIds);
                }
            } else if (Constants.ORDER_TYPE_SHOP.equals(orderType)) {
                // 商城首单券未使用自动过期
                List<Long> expireGoodsIds = appUserCardRecordList.stream()
                        .filter(record -> Constants.COUPON_TYPE_GOODS.equals(record.getSourceType()))
                        .map(AppUserCardRecord::getId)
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(expireGoodsIds)) {
                    appUserCardRecordMapper.expireUserCardRecord(expireGoodsIds);
                }
            }
        }
    }
    @RabbitHandler
    @RabbitListener(queuesToDeclare = @Queue(MqConstans.QUEUE_ORDER_SUCCESS))
    public void orderPaySuccessConsumer(OrderSuccessParam param, Channel channel, Message message) throws IOException {
        orderPaySuccess(param);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
