package com.liquidnet.service.galaxy.utils;

import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.service.base.SqlMapping;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.StringRedisTemplate;

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

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: QueueUtil
 * @Package com.liquidnet.service.galaxy.utils
 * @Copyright: LightNet @ Copyright (c) 2022
 * @date 2022/3/25 15:35
 */

public abstract class AbstractQueueUtil {

    abstract StringRedisTemplate getStringRedisTemplate();

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

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

    /**
     * 发送消息 - REDIS
     *
     * @param streamKey Redis消费Key
     * @param jsonMsg   Json字符串
     */
    public void sendMsgByRedis(String streamKey, String jsonMsg) {
        HashMap<String, String> map = CollectionUtil.mapStringString();
        map.put("message", jsonMsg);
        this.getStringRedisTemplate().opsForStream().add(StreamRecords.mapBacked(map).withStreamKey(streamKey));
    }
}
