
package com.tmerclub.cloud.order.listener;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.group.bo.GroupOrderNotifyBO;
import com.tmerclub.cloud.api.order.feign.OrderFeignClient;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.leaf.manager.SegmentManager;
import com.tmerclub.cloud.common.order.bo.OrderStatusBO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.order.mapper.OrderInvoiceMapper;
import com.tmerclub.cloud.order.mapper.OrderMapper;
import com.tmerclub.cloud.order.service.OrderService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
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.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author tmerclub
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.GROUP_ORDER_SUCCESS_TOPIC, consumerGroup = RocketMqConstant.GROUP_ORDER_SUCCESS_GROUP)
public class GroupOrderSuccessConsumer implements RocketMQListener<GroupOrderNotifyBO> {

    private final Logger LOGGER = LoggerFactory.getLogger(GroupOrderSuccessConsumer.class);
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedissonClient redissonClient;
    @DubboReference
    private OrderFeignClient orderFeignClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderInvoiceMapper orderInvoiceMapper;
    @Autowired
    private RocketMQTemplate orderPurchaseNotifyShopTemplate;
    @Autowired
    private SegmentManager segmentManager;

    /**
     * 团购订单成团了，将订单状态变为待发货
     *
     * @param orderIds
     */
    @Override
    public void onMessage(GroupOrderNotifyBO groupOrderNotifyBO) {
        List<Long> orderIds = groupOrderNotifyBO.getOrderIds();
        if (CollUtil.isEmpty(orderIds)) {
            LOGGER.info("团购订单成团了，将订单状态变为待发货, orderIds is empty");
            return;
        }
        ServerResponseEntity<List<OrderStatusBO>> ordersStatusResponse = orderFeignClient.getOrdersStatus(orderIds);
        if (!ordersStatusResponse.isSuccess()) {
            LOGGER.error("团购订单成团了，将订单状态变为待发货, 获取订单状态失败, orderIds: {}, msg: {}", orderIds, ordersStatusResponse.getMsg());
            throw new LuckException(ordersStatusResponse.getMsg());
        }
        orderMapper.updateGroupOrderSuccessStatus(ordersStatusResponse.getData().get(0).getOrderMold(), orderIds);
    }

}
