
package com.tmerclub.cloud.payment.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.tmerclub.cloud.common.order.bo.OrderIdWithRefundIdBO;
import com.tmerclub.cloud.common.order.bo.PayRefundBO;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.payment.model.PayInfo;
import com.tmerclub.cloud.payment.service.PayInfoService;
import com.tmerclub.cloud.payment.service.RefundInfoService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 拼团订单成团失败通知
 *
 * @author tmerclub
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.GROUP_ORDER_UN_SUCCESS_REFUND_TOPIC, consumerGroup = RocketMqConstant.GROUP_ORDER_UN_SUCCESS_REFUND_TOPIC)
public class GroupOrderUnSuccessRefundConsumer implements RocketMQListener<List<OrderIdWithRefundIdBO>> {

    @Autowired
    private RefundInfoService refundInfoService;
    @Autowired
    private PayInfoService payInfoService;

    /**
     * 拼团订单成团失败通知
     */
    @Override
    public void onMessage(List<OrderIdWithRefundIdBO> orderIdWithRefundIds) {
        List<Long> orderIds = orderIdWithRefundIds.stream().map(OrderIdWithRefundIdBO::getOrderId).collect(Collectors.toList());

        List<PayInfo> payInfos = payInfoService.listByOrderIds(orderIds);
        if (CollectionUtil.isEmpty(payInfos)) {
            return;
        }
        Map<Long, Long> orderIdWithRefundIdMap = orderIdWithRefundIds.stream().collect(Collectors.toMap(OrderIdWithRefundIdBO::getOrderId, OrderIdWithRefundIdBO::getRefundId));
        for (PayInfo payInfo : payInfos) {
            PayRefundBO payRefundBO = new PayRefundBO();
            payRefundBO.setRefundId(orderIdWithRefundIdMap.get(Long.valueOf(payInfo.getOrderIds())));
            payRefundBO.setRefundAmount(payInfo.getPayAmount());
            payRefundBO.setOrderId(Long.valueOf(payInfo.getOrderIds()));
            payRefundBO.setPayId(payInfo.getPayId());
            payRefundBO.setUnSuccessGroupOrder(1);
            refundInfoService.doRefund(payRefundBO);
        }
    }
}
