package com.liquidnet.service.consumer.kylin.receiver;

import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.consumer.service.IBaseDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.stream.StreamListener;

@Slf4j
public abstract class AbstractSqlRedisReceiver implements StreamListener<String, MapRecord<String, String, String>> {
    @Autowired
    private IBaseDao baseDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void onMessage(MapRecord<String, String, String> message) {
        log.info("CONSUMER SQL[streamKey:{},messageId:{},stream:{},body:{}]",
                this.getRedisStreamKey(), message.getId(), message.getStream(), message.getValue());

        boolean result = this.consumerSqlDaoHandler(message.getValue().get("message"));

        log.debug("CONSUMER SQL RESULT:{}", result);

        // 消费成功确认，消息删除和消息确认是一个事务
        if (result) {
            log.info("CONSUMER SMS SUCC ==> MESSAGE_ID:{}", message.getId());
            try {
                stringRedisTemplate.opsForStream().delete(this.getRedisStreamKey(), message.getId());
            } catch (Exception e) {
                log.error("CONSUMER SMS SUCC ==> DEL_REDIS_QUEUE_MSG_EXCEPTION[MESSAGE_ID:{}]", message.getId(), e);
            }
        }
    }

    private boolean consumerSqlDaoHandler(String msg) {
        try {
            SqlMapping.SqlMessage sqlMessage = JsonUtils.fromJson(msg, SqlMapping.SqlMessage.class);
            return baseDao.batchSqls(sqlMessage.getSqls(), sqlMessage.getArgs());
        } catch (Exception e) {
            log.error("CONSUMER SMS FAIL ==> {}", e.getMessage(), e);
            return false;
        }
    }

    protected abstract String getRedisStreamKey();
}