package com.liquidnet.service.dragon.utils;

import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.dragon.bo.PayNotifyReqBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.LinkedList;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: MqHandleUtil
 * @Package com.liquidnet.service.dragon.utils
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/7/10 16:23
 */
@Component
public class MqHandleUtil {
    @Autowired
    RedisDataSourceUtil redisDataSourceUtil;

    /**
     * REDIS 队列发送消息 通知商户相关
     * @param payNotifyReqBo
     * @return
     */
    public boolean sendNotifyErrorQueue(PayNotifyReqBo payNotifyReqBo,String queueKey) {
        try {
            HashMap<String, String> map = ObjectUtilDragon.cloneHashMapStringAndString();
            map.put("message", payNotifyReqBo.toString());
            MapRecord<String, String, String> record = StreamRecords.mapBacked(map).withStreamKey(queueKey);
            redisDataSourceUtil.getRedisQueueUtil().getStringRedisTemplate().opsForStream().add(record);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 给 REDIS 队列发送消息 数据库相关
     *
     * @param sql  sql语句
     * @param data 需要操作的数据
     * @return
     */
    public boolean sendMySqlRedis(String sql, Object[] data , String redisKey) {
        try {
            LinkedList<String> sqls = ObjectUtilDragon.cloneLinkedListStr();
            sqls.add(sql);
            LinkedList<Object[]> sqlsData = ObjectUtilDragon.cloneLinkedListObj();
            sqlsData.add(data);
            String sqlData = SqlMapping.gets(sqls, sqlsData);

            HashMap<String, String> map = ObjectUtilDragon.cloneHashMapStringAndString();
            map.put("message", sqlData);
            MapRecord<String, String, String> record = StreamRecords.mapBacked(map).withStreamKey(redisKey);
            redisDataSourceUtil.getRedisQueueUtil().getStringRedisTemplate().opsForStream().add(record);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
