package com.izouma.nineth.listener;

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.service.OrderService;
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.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

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

    @Override
    public void onMessage(CreateOrderEvent event) {
        log.info("收到订单创建消息: {}", event.getId());
        Map<String, Object> map = new HashMap<>();
        try {
            Order order = orderService.create(event.getUserId(), event.getCollectionId(), event.getQty(),
                    event.getAddressId(), event.getUserCouponId(), event.getInvitor(), event.getId(),
                    event.isVip(), event.getShowroomId());
            map.put("success", true);
            map.put("data", order);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                log.error("订单创建失败,id={},{}", event.getId(), e.getMessage());
            } else {
                log.error("订单创建失败", e);
            }
            map.put("success", false);
            map.put("data", e.getMessage());
        }
        redisTemplate.boundValueOps(RedisKeys.CREATE_ORDER + event.getId()).set(map, 1, TimeUnit.DAYS);
    }
}
