package cn.ibizlab.core.message;

import cn.ibizlab.core.extensions.cql.ExecResultRepository;
import cn.ibizlab.core.extensions.domain.ResultsMQMsg;
import cn.ibizlab.core.extensions.domain.SqlResultsMQMsg;
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.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
@Component
@ConditionalOnExpression("'${rocketmq.consumer.namesrvAddr:}'!='' && ${rocketmq.consumer.enabled:false}")
@RocketMQMessageListener(nameServer = "${rocketmq.consumer.namesrvAddr:}",
        topic = "${rocketmq.producer.resultsTopic:DSTRESULTSMSG}",
        selectorExpression="*",
        consumerGroup = "${rocketmq.consumer.resultsGroupName:resultsCG}",
        consumeThreadMax = 20,
        consumeMode = ConsumeMode.CONCURRENTLY
)
public class ResultMQMsgListener implements RocketMQListener<MessageExt> {

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

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

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

    @Value("${cassandra.host:}")
    private String cassandraHost;

    @Autowired
    @Lazy
    protected IExecLogService ruExecLogService;

    @Override
    public void onMessage(MessageExt messageExt) {

        try {
            String body = new String(messageExt.getBody(), "utf-8");
            String tags = messageExt.getTags();
            String topic = messageExt.getTopic();
            log.info("MQ消息topic={}, tags={}, 消息内容={}", topic, tags, messageExt.getMsgId());
            if (StringUtils.isEmpty(cassandraHost)) {
                SqlResultsMQMsg resultsMQMsg = JSON.parseObject(body, new TypeReference<SqlResultsMQMsg>() {
                });
                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 {
                ResultsMQMsg resultsMQMsg = JSON.parseObject(body, new TypeReference<ResultsMQMsg>() {});
                if (!StringUtils.isEmpty(resultsMQMsg.getKeyValueField())) {
                    execResultRepository.saveResultsMQMsg(resultsMQMsg);
                }
            }
        } catch (Exception e) {
            log.error("获取MQ消息内容异常{}", e);
        }
    }

}