
package com.tmerclub.cloud.order.listener;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.payment.feign.PaymentFeignClient;
import com.tmerclub.cloud.common.cache.constant.LockCacheNames;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.constant.ReturnProcessStatusEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.order.service.OrderRefundService;
import com.tmerclub.cloud.order.vo.OrderRefundVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 发放退款
 * @author TRACK
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.ORDER_REFUND_REQUEST_TOPIC, consumerGroup = RocketMqConstant.ORDER_REFUND_REQUEST_TOPIC)
public class OrderRefundRequestConsumer implements RocketMQListener<List<Long>> {

    @Autowired
    private OrderRefundService orderRefundService;
    @Autowired
    private RedissonClient redissonClient;
    @DubboReference
    private PaymentFeignClient paymentFeignClient;

    private static final Logger logger = LoggerFactory.getLogger(OrderRefundRequestConsumer.class);

    @Override
    public void onMessage(List<Long> refundIds) {
        if (CollUtil.isEmpty(refundIds)) {
            return;
        }
        logger.info("发放回调开始... message: {}", Json.toJsonString(refundIds));
        for (Long refundId : refundIds) {
            RLock lock = redissonClient.getLock(LockCacheNames.LOCK_REFUND_HANDLE_PREFIX + refundId);
            lock.lock();
            try {
                OrderRefundVO orderRefundVO = orderRefundService.getByRefundId(refundId);
                if (Objects.equals(orderRefundVO.getReturnMoneySts(), ReturnProcessStatusEnum.PROCESSING.value())) {
                    // 商家处理状态，查询退款是否成功
                    ServerResponseEntity<Boolean> serverResponse = paymentFeignClient.checkRefundStatus(refundId);
                    if (!serverResponse.isSuccess()) {
                        throw new LuckException(serverResponse.getMsg());
                    }
                    if (serverResponse.getData()) {
                        logger.info("退款订单{}已经退款完成并回调", refundId);
                        continue;
                    }
                    // 申请退款失败，重新申请
                    logger.info("退款单号为{}的订单开始进行发放退款", refundId);
                    // 提交退款请求
                    orderRefundService.refundRequest(refundId);
                }
            } catch (Exception e) {
                // 该mq不需要反复回调回来，反正定时任务会一直执行
                logger.info("退款单号:{}订单发放退款失败，原因为:{}", refundId, e.getMessage());
            } finally {
                lock.unlock();
            }
        }
    }
}
