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.common.util.AdwebRedisUtil;
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 static org.jeecg.modules.adweb.enquiry.service.impl.AdwebEnquiryServiceImpl.EnquiryUniqueKey;

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

    @Autowired
    private IAdwebSiteService adwebSiteService;

    @Autowired
    private IAdwebEnquiryService adwebEnquiryService;

    @Autowired
    private AdwebRedisUtil adwebRedisUtil;

    @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) {
        super.onMessage(
                enquiryDTO,
                deliveryTag,
                channel,
                new MqListener<EnquiryDTO>() {
                    @Override
                    public void handler(EnquiryDTO enquiry, Channel channel) {
                        // 业务处理
                        log.info("收到MQ消息 {}", enquiry);

                        if (adwebRedisUtil.hasKey(EnquiryUniqueKey + enquiry.getSiteHost())) {
                            // 消息内容唯一性判断
                            List<String> enquiryUniqueIds = (List<String>) adwebRedisUtil.get(EnquiryUniqueKey + enquiry.getSiteHost());
                            // 如果该消息内容原数据中已存在，则将该重复消息踢出队列
                            if (enquiryUniqueIds.contains(enquiry.getSiteHost() + enquiry.getRecordId())) {
                                log.info("该询盘已经消费过，从队列中清除：{}", enquiry.getRecordId());
                                try {
                                    channel.basicAck(deliveryTag, false);
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }


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

                        if (adwebSites.isEmpty()) {
                            log.error(
                                    "站点：{} 不是adweb3的有效绑定站点,MQ消息确认失败",
                                    enquiry.getSiteHost());
                            return;
                        }

                        try {
                            // 询盘入库
                            adwebEnquiryService.addEnquiry(
                                    enquiry, enquiry.getPluginName(), adwebSites);
                        } catch (Exception e) {
                            log.error("询盘入库异常：{}", e.getMessage());
                        }
                    }
                });
    }
}
