package com.izouma.nineth.listener;

import com.gexin.fastjson.JSON;
import com.izouma.nineth.config.RedisKeys;
import com.izouma.nineth.domain.Order;
import com.izouma.nineth.event.CreateOrderEvent;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.OrderRepo;
import com.izouma.nineth.service.CollectionService;
import com.izouma.nineth.service.OrderService;
import com.izouma.nineth.service.pay.PayHelper;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

@Service
@Slf4j
//@AllArgsConstructor
@RocketMQMessageListener(
        consumerGroup = "${general.create-order-group}",
        topic = "${general.create-order-topic}",
        consumeMode = ConsumeMode.ORDERLY)
//@ConditionalOnProperty(value = "general.notify-server", havingValue = "false", matchIfMissing = true)
public class CreateOrderListener implements RocketMQListener<CreateOrderEvent> {
    @Autowired
    private OrderRepo orderRepo;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private CollectionService collectionService;

    @Autowired
    private PayHelper payHelper;

    //记录执行序号
    private AtomicLong sn = new AtomicLong(1000L);

    @Override
    public void onMessage(CreateOrderEvent event) {
        log.info("收到订单创建消息: {}, 序号：{}", JSON.toJSONString(event), sn.addAndGet(1));
        Map<String, Object> map = new HashMap<>();
        try {
            Long orderId = event.getId();//必须存在
            Order order = orderRepo.findById(orderId).orElse(null);
            if(order  == null){
                //防止同一个消息重复消费
                order = orderService.create(event);
            }

            LocalDateTime expireTime = payHelper.getExpireTime(order.getCreatedAt());
            order.setExpireTime(expireTime);

            map.put("success", true);
            map.put("data", order);
        } catch (Exception e) {
            //订单失败，可以恢复库存
            collectionService.increaseStockCache(event.getCollectionId(), event.getQty());
            if (e instanceof BusinessException) {
                log.error("订单创建失败,订单ID:{}, 失败原因：{}", event.getId(), e.getMessage());
            } else {
                log.error("订单创建失败,订单ID:{}, 失败原因：{}", event.getId(), e);
            }
            map.put("success", false);
            map.put("data", e.getMessage());
        }
        //返回结果
        redisTemplate.boundValueOps(RedisKeys.CREATE_ORDER + event.getId()).set(map, 1, TimeUnit.DAYS);
    }
}
