package cn.ibizlab.core.extensions.util;

import cn.ibizlab.core.extensions.domain.LocalMsgEvent;
import cn.ibizlab.core.extensions.domain.SqlResultsMQMsg;
import com.alibaba.fastjson.JSON;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 构建结果（报表构建、规则构建）强制使用本地消息队列模式
 */
@Slf4j
@Service
public class LocalMsgResultProducerService {

    @Autowired
    protected Disruptor<LocalMsgEvent> resultDisruptor;

    /**
     * 规则构建结果发送
     * @param sqlResultsMQMsg
     * @throws Exception
     */
    public void sendEngineResultsMsg(SqlResultsMQMsg sqlResultsMQMsg) throws Exception {
        LocalMsgEvent localMsgEvent = new LocalMsgEvent();
        String msg = JSON.toJSONString(sqlResultsMQMsg);
        localMsgEvent.setBody(msg);
        localMsgEvent.setTags("EngineResult");
        if (log.isDebugEnabled()) {
            log.debug("EngineResultsMsg Event Send: {}", sqlResultsMQMsg.getMsgId());
        }
        resultDisruptor.publishEvent((event, sequence, bind) -> {event.setBody(bind.getBody());event.setTags(localMsgEvent.getTags());}, localMsgEvent);
    }

    /**
     * 报表构建结果单条发送
     * @param sqlResultsMQMsg
     * @throws Exception
     */
    public void sendBuildResultsMsg(SqlResultsMQMsg sqlResultsMQMsg) throws Exception {
        LocalMsgEvent localMsgEvent = new LocalMsgEvent();
        String msg = JSON.toJSONString(sqlResultsMQMsg);
        localMsgEvent.setBody(msg);
        localMsgEvent.setTags("BuildResult");
        if (log.isDebugEnabled()) {
            log.debug("BuildResultsMsg Event Send: {}", sqlResultsMQMsg.getMsgId());
        }
        resultDisruptor.publishEvent((event, sequence, bind) -> {event.setBody(bind.getBody());event.setTags(localMsgEvent.getTags());}, localMsgEvent);
    }

    /**
     * 报表构建结果批量发送
     * @param sqlResultsMQMsgList
     * @throws Exception
     */
    public void sendBuildResultsMsgList(List<SqlResultsMQMsg> sqlResultsMQMsgList) throws Exception {
        LocalMsgEvent localMsgEvent = new LocalMsgEvent();
        String msg = JSON.toJSONString(sqlResultsMQMsgList);
        localMsgEvent.setBody(msg);
        localMsgEvent.setTags("BuildResultList");
        if (log.isDebugEnabled()) {
            log.debug("BuildResultsMsgList Event Send: {}", sqlResultsMQMsgList.get(0).getMsgId());
        }
        resultDisruptor.publishEvent((event, sequence, bind) -> {event.setBody(bind.getBody());event.setTags(localMsgEvent.getTags());}, localMsgEvent);
    }

}
