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.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.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;

    @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)){
                SqlResultsMQMsg resultsMQMsg = localMsgEvent.getMessage(SqlResultsMQMsg.class);
                localMsgEvent.setBody(null);
                if (log.isDebugEnabled()) {
                    log.debug("SqlResultMsgProcess Event Handler: {}", resultsMQMsg.getMsgId());
                }
                String resultDataSource = DataObject.getStringValue(resultsMQMsg.getResultDataSource(),Default_ResultDataSource);
                String resultTableName = DataObject.getStringValue(resultsMQMsg.getResultTableName(),Default_ResultTableName);
                List<ExecResult> saveDatas =  resultsMQMsg.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 =  resultsMQMsg.getDeleteDatas();
                if(deleteDatas != null && deleteDatas.size() > 0){
                    List<List<ExecResult>> splist = LiteDataService.splitList(deleteDatas, deleteResultBatchSize);
                    splist.forEach(array ->{
                        execResultExService.clearResultBatch(array, resultDataSource, resultTableName);
                    });
                }

                //临时处理批次处理结果为10，表示数据插入完成
                ExecLog execlog=new ExecLog();
                execlog.setId(resultsMQMsg.getMsgId());
                execlog.setRetCode(10);
                ruExecLogService.updateById(execlog);
            }
        }
        else if (localMsgEvent.getType()==2) {

            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);
        }
    }
}
