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.enquiry.dto.EnquiryDTO;
import org.jeecg.modules.adweb.enquiry.service.IAdwebEnquiryService;
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.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * Rabbit MQ - 询盘消息接收
 *
 * @author wfansh
 */
@Slf4j
@RabbitComponent(value = "enquiryReceiver")
public class EnquiryReceiver extends BaseRabbiMqHandler<EnquiryDTO> {

    @Autowired
    private IAdwebSiteService adwebSiteService;

    @Autowired
    private IAdwebEnquiryService adwebEnquiryService;

    @RabbitHandler
    // ackMode需要设置为MANUAL - BaseRabbiMqHandler.onMessage()有channel.basicAck()操作
    @RabbitListener(queues = "site_enquiry", ackMode = "MANUAL")
    public void onMessage(
            EnquiryDTO enquiryDTO,
            Channel channel,
            @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException, TimeoutException {
        super.onMessage(
                enquiryDTO,
                deliveryTag,
                channel,
                new MqListener<EnquiryDTO>() {
                    @Override
                    public void handler(EnquiryDTO enquiry, Channel channel) {
                        // 业务处理
                        log.info("收到MQ消息 {}", enquiry);

                        // 查看发布当前消息的站点是否是 adweb3 平台中绑定的是否是有效站点, 如果不是则直接确认消息，不做业务处理
                        List<AdwebSite> adwebSites = adwebSiteService.list(new LambdaQueryWrapper<AdwebSite>()
                                .like(AdwebSite::getDomain, enquiry.getSiteHost())
                                .ne(AdwebSite::getStatus, 0));

                        if (adwebSites.isEmpty()) {
                            try {
                                channel.basicAck(deliveryTag, false);
                            } catch (IOException e) {
                                log.error(String.format("站点：%s 不是adweb3的有效绑定站点,MQ消息确认失败: %s", enquiry.getSiteHost(), e.getMessage()), e);
                            }
                        }
                        // 询盘入库
                        adwebEnquiryService.addEnquiry(enquiry, enquiry.getPluginName(), adwebSites);

                    }
                });
    }
}
