
package com.tmerclub.cloud.user.listener;

import com.tmerclub.cloud.api.payment.constant.PaySysType;
import com.tmerclub.cloud.common.constant.PayType;
import com.tmerclub.cloud.common.order.bo.PayNotifyBO;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.user.bo.mongo.MongoUserBalanceLogBO;
import com.tmerclub.cloud.user.constant.RechargeTypeEnum;
import com.tmerclub.cloud.user.service.UserBalanceLogService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author tmerclub
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.ALLINPAY_BALANCE_ORDER_SUCCESS_TOPIC, consumerGroup = RocketMqConstant.ALLINPAY_BALANCE_ORDER_SUCCESS_TOPIC)
public class AllinpayBalancePaySuccessConsumer implements RocketMQListener<PayNotifyBO> {

    private static final Logger LOG = LoggerFactory.getLogger(AllinpayBalancePaySuccessConsumer.class);


    @Autowired
    private UserBalanceLogService userBalanceLogService;


    /**
     * 订单支付成功
     */
    @Override
    public void onMessage(PayNotifyBO message) {
        // 订单支付成功,如果是默认的or不是余额支付的，就直接退出就好
        if (!Objects.equals(message.getPayType(), PayType.BALANCE.value()) || Objects.equals(message.getPaySysType(), PaySysType.DEFAULT.value())) {
            return;
        }
        Long payId = message.getPayId();
        MongoUserBalanceLogBO userBalanceLog = userBalanceLogService.getByPayIdAndType(payId, RechargeTypeEnum.PAY.value());
        if (Objects.isNull(userBalanceLog)) {
            return;
        }
        // 扣减余额，并将余额记录的支付状态变为已支付
        userBalanceLogService.updateToOrderPaySuccess(payId, userBalanceLog);
    }
}
