package com.izouma.nineth.listener;

import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.domain.ErrorOrder;
import com.izouma.nineth.domain.Order;
import com.izouma.nineth.event.OrderNotifyEvent;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.lock.RedisLockException;
import com.izouma.nineth.repo.ErrorOrderRepo;
import com.izouma.nineth.service.OrderService;
import com.izouma.nineth.service.PaymentInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@AllArgsConstructor
@RocketMQMessageListener(
        consumerGroup = "${general.order-notify-group}",
        topic = "${general.order-notify-topic}",
        consumeThreadMax = 1,
        consumeMode = ConsumeMode.ORDERLY)
//@ConditionalOnProperty(value = "general.notify-server", havingValue = "true")
public class OrderNotifyListener implements RocketMQListener<OrderNotifyEvent> {
    private OrderService orderService;

    private RocketMQTemplate rocketMQTemplate;

    private GeneralProperties generalProperties;

    private ErrorOrderRepo errorOrderRepo;

    private PaymentInfoService paymentInfoService;

    @Override
    public void onMessage(OrderNotifyEvent event) {
        try {
            log.info("收到通知回调消息 {} ", JSONObject.toJSONString(event));
            orderService.notifyOrder(event.getOrderId(), event.getPayMethod(), event.getTransactionId());
        }catch(RedisLockException rdException){
            log.info("订单回调失败 orderId: {} redis锁定, 重新发送到队列", event.getOrderId());
            rocketMQTemplate.syncSend(generalProperties.getOrderNotifyTopic(),
                    new OrderNotifyEvent(event.getOrderId(), event.getOrderNo(), event.getPayMethod(),
                            event.getTransactionId(), System.currentTimeMillis()));
        }catch(Exception err){
            ErrorOrder errorOrder = ErrorOrder.builder()
                    .orderId(event.getOrderId())
                    .transactionId(event.getTransactionId())
                    .payMethod(event.getPayMethod())
                    .build();
            if (err instanceof BusinessException) {
                log.error("订单回调出错 orderId: {} , 错误信息：{}", event.getOrderId(), err.getMessage());
            } else {
                log.error("订单回调出错 orderId: " +  event.getOrderId(), err);
            }
            errorOrder.setErrorMessage(err.getMessage());
            errorOrderRepo.save(errorOrder);
        }

        //检查订单是否需要自动退款
        orderService.checkAndAutoRefund(event.getOrderId());

    }
}
