package cn.ibizlab.core.extensions.util;

import cn.ibizlab.core.extensions.cql.ExecResultRepository;
import cn.ibizlab.core.extensions.domain.EngineMQMsg;
import cn.ibizlab.core.extensions.domain.LocalMsgEvent;
import cn.ibizlab.core.extensions.domain.ResultsMQMsg;
import cn.ibizlab.core.extensions.domain.SqlResultsMQMsg;
import cn.ibizlab.core.extensions.service.DABuildExService;
import cn.ibizlab.core.extensions.service.RuleEngineExService;
import cn.ibizlab.core.lite.extensions.service.LiteDataService;
import cn.ibizlab.core.rule.domain.ExecLog;
import cn.ibizlab.core.rule.domain.ExecResult;
import cn.ibizlab.core.rule.service.IExecLogService;
import cn.ibizlab.util.helper.DataObject;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.lmax.disruptor.EventHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class LocalMsgEventHandler implements EventHandler<LocalMsgEvent> {

    @Autowired
    @Lazy
    private RuleEngineExService ruleEngineExService;

    @Autowired
    @Lazy
    private DABuildExService daBuildExService;

    @Autowired(required = false)
    @Lazy
    private ExecResultRepository execResultRepository;

    @Autowired(required = false)
    @Lazy
    private cn.ibizlab.core.extensions.service.ExecResultExService execResultExService;

    @Autowired
    @Lazy
    protected IExecLogService ruExecLogService;

    @Value("${defaultResultDataSource:default}")
    private String Default_ResultDataSource;

    @Value("${defaultResultTableName:IBZRULERESULT}")
    private String Default_ResultTableName;

    @Value("${ibiz.saveResultBatchSize:2000}")
    private int saveResultBatchSize;
    @Value("${ibiz.deleteResultBatchBatchSize:20000}")
    private int deleteResultBatchSize;
    @Value("${ibiz.resultsBatchSend:true}")
    protected boolean resultsBatchSend;
    @Value("${cassandra.host:}")
    private String cassandraHost;

    @Override
    public void onEvent(LocalMsgEvent localMsgEvent, long sequence, boolean endOfBatch) throws Exception {
        if (localMsgEvent.getType()==1) {
            String tags = localMsgEvent.getTags();
            if("Engine".equalsIgnoreCase(tags)) {
                EngineMQMsg engineMQMsg = localMsgEvent.getMessage(EngineMQMsg.class);
                localMsgEvent.setBody(null);
                if (log.isDebugEnabled()) {
                    log.debug("EngineMQMsg Event Handler: {}", engineMQMsg.getBatch());
                }
                ruleEngineExService.processData(engineMQMsg);
            }else if("Build".equalsIgnoreCase(tags)){
                EngineMQMsg engineMQMsg = localMsgEvent.getMessage(EngineMQMsg.class);
                localMsgEvent.setBody(null);
                if (log.isDebugEnabled()) {
                    log.debug("BuildMQMsg Event Handler: {}", engineMQMsg.getBatch());
                }
                daBuildExService.processData(engineMQMsg);
            }else if("SqlResult".equalsIgnoreCase(tags)){
                // 报表sql模式，结果存储至非cassandra数据库
                SqlResultsMQMsg resultsMQMsg = localMsgEvent.getMessage(SqlResultsMQMsg.class);
                localMsgEvent.setBody(null);
                if (log.isDebugEnabled()) {
                    log.debug("SqlResultMsgProcess Event Handler: {}", resultsMQMsg.getMsgId());
                }
                saveSqlData(resultsMQMsg);
                //临时处理批次处理结果为10，表示数据插入完成
                ExecLog execlog=new ExecLog();
                execlog.setId(resultsMQMsg.getMsgId());
                execlog.setRetCode(10);
                ruExecLogService.updateById(execlog);
            }else if ("EngineResult".equalsIgnoreCase(tags)){
                // 规则结果存储至非cassandra数据库
                SqlResultsMQMsg sqlResultsMQMsg = localMsgEvent.getMessage(SqlResultsMQMsg.class);
                localMsgEvent.setBody(null);
                if (log.isDebugEnabled()) {
                    log.debug("EngineResultMsgProcess Event Handler: {}", sqlResultsMQMsg.getMsgId());
                }
                saveSqlData(sqlResultsMQMsg);
                if (resultsBatchSend){
                    //临时处理批次处理结果为10，表示数据插入完成
                    ExecLog execlog = new ExecLog();
                    execlog.setId(sqlResultsMQMsg.getMsgId());
                    execlog.setRetCode(10);
                    ruExecLogService.updateById(execlog);
                }
            }else if ("BuildResult".equalsIgnoreCase(tags)){
                // 报表all构建模式（cql和sql二合一），构建结果处理
                SqlResultsMQMsg sqlResultsMQMsg = localMsgEvent.getMessage(SqlResultsMQMsg.class);
                localMsgEvent.setBody(null);
                if (log.isDebugEnabled()) {
                    log.debug("BuildResultsMsgProcess Event Handler: {}", sqlResultsMQMsg.getMsgId());
                }
                List<SqlResultsMQMsg> lists = new ArrayList<>();
                lists.add(sqlResultsMQMsg);
                saveAllData(lists);
            }else if ("BuildResultList".equalsIgnoreCase(tags)){
                // 报表all构建模式（cql和sql二合一），构建结果批量处理
                String boby = localMsgEvent.getBody();
                localMsgEvent.setBody(null);
                List<SqlResultsMQMsg> lists = JSONObject.parseObject(boby, new TypeReference<List<SqlResultsMQMsg>>() {});
                if (log.isDebugEnabled()) {
                    log.debug("BuildResultsMsgListProcess Event Handler: {}", lists.get(0).getMsgId());
                }
                saveAllData(lists);
                //临时处理批次处理结果为10，表示数据插入完成
                ExecLog execlog = new ExecLog();
                execlog.setId(lists.get(0).getMsgId());
                execlog.setRetCode(10);
                ruExecLogService.updateById(execlog);
            }
        }
        else if (localMsgEvent.getType()==2) {
            // 报表结果存储至cassandra数据库

            ResultsMQMsg resultsMQMsg = localMsgEvent.getMessage(ResultsMQMsg.class);
            localMsgEvent.setBody(null);
            if (log.isDebugEnabled()) {
                log.debug("ResultsMQMsg Event Handler: {}", resultsMQMsg.getKeyValueField());
            }

            if(!StringUtils.isEmpty(resultsMQMsg.getKeyValueField()))
                execResultRepository.saveResultsMQMsg(resultsMQMsg);
        }
    }

    /**
     * 报表构建sql模式、规则引擎构建，构建结果保存至非cassandra数据库
     * @param sqlResultsMQMsg
     */
    private void saveSqlData(SqlResultsMQMsg sqlResultsMQMsg){
        String resultDataSource = DataObject.getStringValue(sqlResultsMQMsg.getResultDataSource(),Default_ResultDataSource);
        String resultTableName = DataObject.getStringValue(sqlResultsMQMsg.getResultTableName(),Default_ResultTableName);
        List<ExecResult> saveDatas =  sqlResultsMQMsg.getSaveDatas();
        if(saveDatas != null && saveDatas.size() > 0){
            List<List<ExecResult>> splist = LiteDataService.splitList(saveDatas, saveResultBatchSize);
            splist.forEach(array ->{
                execResultExService.saveResultBatch(array, resultDataSource, resultTableName);
            });
        }
        List<ExecResult> deleteDatas =  sqlResultsMQMsg.getDeleteDatas();
        if(deleteDatas != null && deleteDatas.size() > 0){
            List<List<ExecResult>> splist = LiteDataService.splitList(deleteDatas, deleteResultBatchSize);
            splist.forEach(array ->{
                execResultExService.clearResultBatch(array, resultDataSource, resultTableName);
            });
        }
    }

    /**
     * 报表all构建模式（cql和sql二合一），构建结果存储
     * @param lists
     */
    private void saveAllData(List<SqlResultsMQMsg> lists){
        if (!StringUtils.isEmpty(cassandraHost)){
            // 使用cassandra数据库
            ResultsMQMsg resultsMQMsg = null;
            for (SqlResultsMQMsg sqlResultsMQMsg : lists) {
                if(!StringUtils.isEmpty(sqlResultsMQMsg.getKeyValueField())) {
                    resultsMQMsg = new ResultsMQMsg();
                    resultsMQMsg.setDatas(cn.ibizlab.core.extensions.cql.ExecResult.fromSqlExecResultList(sqlResultsMQMsg.getSaveDatas()));
                    resultsMQMsg.setRules(sqlResultsMQMsg.getRules());
                    resultsMQMsg.setKeyValueField(sqlResultsMQMsg.getKeyValueField());
                    execResultRepository.saveResultsMQMsg(resultsMQMsg);
                }
            }
        }else {
            String resultDataSource = DataObject.getStringValue(lists.get(0).getResultDataSource(),Default_ResultDataSource);
            String resultTableName = DataObject.getStringValue(lists.get(0).getResultTableName(),Default_ResultTableName);
            for (SqlResultsMQMsg sqlResultsMQMsg : lists) {
                List<ExecResult> saveDatas =  sqlResultsMQMsg.getSaveDatas();
                if(saveDatas != null && saveDatas.size() > 0){
                    List<List<ExecResult>> splist = LiteDataService.splitList(saveDatas, saveResultBatchSize);
                    splist.forEach(array ->{
                        execResultExService.saveResultBatch(array, resultDataSource, resultTableName);
                    });
                }
                List<String> deleteDatas =  sqlResultsMQMsg.getDeleteIds();
                if(deleteDatas != null && deleteDatas.size() > 0){
                    List<List<String>> splist = LiteDataService.splitList(deleteDatas, deleteResultBatchSize);
                    splist.forEach(array ->{
                        execResultExService.clearResultBatchByIds(array, resultDataSource, resultTableName);
                    });
                }
            }
        }
    }
}
