package com.tmerclub.cloud.supplier.listener;

import com.tmerclub.cloud.common.leaf.manager.SegmentManager;
import com.tmerclub.cloud.common.order.bo.PurchaseAmountLogBO;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.constant.DistributedIdKey;
import com.tmerclub.cloud.supplier.mongo.MongoPurchaseAmountLogBO;
import com.tmerclub.cloud.supplier.service.PurchaseAmountLogService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author gaozijie
 * @date 2023-08-28
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.ADD_PURCHASE_AMOUNT_LOG_TOPIC, consumerGroup = RocketMqConstant.ADD_PURCHASE_AMOUNT_LOG_TOPIC)
public class AddPurchaseLogConsumer implements RocketMQListener<PurchaseAmountLogBO> {

    private static final Logger LOG = LoggerFactory.getLogger(AddPurchaseLogConsumer.class);

    @Autowired
    private PurchaseAmountLogService purchaseAmountLogService;

    @Autowired
    private SegmentManager segmentManager;

    @Override
    public void onMessage(PurchaseAmountLogBO purchaseAmountLogBO) {
        LOG.info("通知添加采购金额日志至MongoDB开始... message: {}", Json.toJsonString(purchaseAmountLogBO));
        MongoPurchaseAmountLogBO mongoPurchaseAmountLogBO = new MongoPurchaseAmountLogBO();
        BeanUtils.copyProperties(purchaseAmountLogBO, mongoPurchaseAmountLogBO);
        mongoPurchaseAmountLogBO.setCreateTime(LocalDateTime.now());
        mongoPurchaseAmountLogBO.setPurchaseLogId(segmentManager.getSegmentId(DistributedIdKey.PURCHASE_AMOUNT_LOG));
        purchaseAmountLogService.savePurchaseLog(mongoPurchaseAmountLogBO);
        LOG.info("添加采购金额日志结束");
    }
}
