package org.jeecg.modules.mq;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.rabbitmq.core.BaseRabbiMqHandler;
import org.jeecg.boot.starter.rabbitmq.listenter.MqListener;
import org.jeecg.common.annotation.RabbitComponent;
import org.jeecg.modules.adweb.product.dto.ProductDTO;
import org.jeecg.modules.adweb.product.service.IAdwebProductService;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;

import java.util.List;

/**
 * Rabbit MQ - 产品消息接收
 *
 * @author chenpeiqing
 */
@Slf4j
@RabbitComponent(value = "productReceiver")
public class ProductReceiver extends BaseRabbiMqHandler<List<ProductDTO>> {

    @Autowired
    private IAdwebSiteService adwebSiteService;

    @Autowired
    private IAdwebProductService adwebProductService;

    @RabbitHandler
    // ackMode需要设置为MANUAL - BaseRabbiMqHandler.onMessage()有channel.basicAck()操作
    @RabbitListener(queues = "site_product", ackMode = "MANUAL")
    public void onMessage(List<ProductDTO> products, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        super.onMessage(products, deliveryTag, channel, new MqListener<List<ProductDTO>>() {
            @Override
            public void handler(List<ProductDTO> products, Channel channel) {
                // 业务处理
                log.info("收到产品MQ消息 {}", products);
                for (ProductDTO product : products) {
                    // 查看发布当前消息的站点是否是 adweb3 平台中绑定的是否是有效站点, 如果不是则直接确认消息，不做业务处理
                    List<AdwebSite> adwebSites = adwebSiteService.list(new LambdaQueryWrapper<AdwebSite>().like(AdwebSite::getDomain, product.getSiteHost()).ne(AdwebSite::getStatus, 0));

                    // 一个消息中的产品所属站点相同，一条不符合，则认为全部不符合
                    if (adwebSites.isEmpty()) {
                        log.error("站点：{} 不是adweb3的有效绑定站点,MQ消息确认失败", product.getSiteHost());
                        return;
                    }

                    // 产品入库
                    adwebProductService.addOrUpdateProduct(product, adwebSites.get(0));
                }
            }
        });
    }
}
