package cn.ysk.cashier.rabbit;

import cn.hutool.core.util.StrUtil;
import cn.ysk.cashier.config.RabbitConfig;
import cn.ysk.cashier.dto.rabbit.StockRecordMsg;
import cn.ysk.cashier.pojo.product.TbProductStockDetail;
import cn.ysk.cashier.service.TbProductStockOperateService;
import cn.ysk.cashier.service.product.TbProductStockDetailService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class StockListener {

    private final TbProductStockDetailService productStockDetailService;

    private final TbProductStockOperateService productStockOperateService;

    public StockListener(TbProductStockDetailService productStockDetailService, TbProductStockOperateService productStockOperateService) {
        this.productStockDetailService = productStockDetailService;
        this.productStockOperateService = productStockOperateService;
    }

    @RabbitListener(queues = RabbitConfig.QUEUE_STOCK_RECORD_SALE)
    public void recordSaleHandler(String message) {
        log.info("接收到下单保存库存信息mq消息，消息内容: {}", message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        if (!jsonObject.containsKey("orderId")) {
            log.info("mq消息体有误，确实orderId");
            return;
        }
        try {
            productStockDetailService.addSaleRecord(jsonObject.getInteger("orderId"));
        }catch (Exception e) {
            log.error("执行保存库存mq失败", e);
        }
    }

    @RabbitListener(queues = RabbitConfig.QUEUE_STOCK_RECORD)
    public void recordStockHandler(String message) {
        log.info("接收到下单保存库存信息mq消息，消息内容: {}", message);
        if (StrUtil.isBlank(message)) {
            log.warn("错误消息体");
            return;
        }
        StockRecordMsg stockRecordMsg = JSONObject.parseObject(message, StockRecordMsg.class);
        try {
            productStockOperateService.addStockRecord(stockRecordMsg);
        }catch (Exception e) {
            log.error("执行保存库存mq失败", e);
        }
    }
}
