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

import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.consumer.dragon.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;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 支付商户通知消费
 */
@Slf4j
@Component
public class RedisPayNotifyReceiver implements StreamListener<String, MapRecord<String, String, String>> {

    @Resource
    IBaseDao baseDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void onMessage(MapRecord<String, String, String> message) {
        log.info("接受到来自redis pay notify 的消息");
        System.out.println("message id " + message.getId());
        System.out.println("stream " + message.getStream());
        System.out.println("body " + message.getValue());
        consumerSqlDaoHandler(message.getValue().get("message"));
    }

    private void consumerSqlDaoHandler(String msg) {
        try {
            SqlMapping.SqlMessage sqlMessage = JsonUtils.fromJson(msg, SqlMapping.SqlMessage.class);
            log.debug("CONSUMER SQL ==> Preparing:{}", JsonUtils.toJson(sqlMessage.getSqls()));
            log.debug("CONSUMER SQL ==> Parameters:{}", JsonUtils.toJson(sqlMessage.getArgs()));
            Boolean rstBatchSqls = baseDao.batchSqls(sqlMessage.getSqls(), sqlMessage.getArgs());
            log.debug("CONSUMER SQL result of execution:{}", rstBatchSqls);
            if (rstBatchSqls) {
                //应答
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
