using CommonEntity;
using CSRedis;
using Newtonsoft.Json;
using NLog;
using System.Net;
using System.Text.Json;

namespace BLWLogProduce.Models
{
    public class MyPublishRedis
    {
        public static CSRedisClient? redis4;
        public static CSRedisClient? redis6;
        public static CSRedisClient? redis7;

        public static Logger logger = LogManager.GetCurrentClassLogger();
        private const string ip = "127.0.0.1";
        private const string port = "6379";
        static MyPublishRedis()
        {
            var redisHostStr = string.Format("{0}:{1}", ip, port);
            if (!string.IsNullOrEmpty(redisHostStr))
            {
                redis4 = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=4");
                redis6 = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=6");
                redis7 = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=7");
                string channel = "__keyevent@6__:expired";
                var QQQ = new ValueTuple<string, Action<CSRedisClient.SubscribeMessageEventArgs>>(channel, (msg) =>
                {
                    string data = msg.Body;
                    try
                    {
                        var data_take =redis4.Get(data);
                        if (!string.IsNullOrEmpty(data_take))
                        {
                            var o = JsonConvert.DeserializeObject<OnOffLineData>(data_take);
                            o.CurrentStatus = "off";
                            o.CurrentTime = DateTime.Now;
                            o.UnixTime = DateTimeOffset.Now.ToUnixTimeSeconds();
                            string str = Newtonsoft.Json.JsonConvert.SerializeObject(o);

                            redis6.Publish("redis-on_off_line", str);
                            //redis7.Del(o.HostNumber);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error("定阅出错:"+data);
                    }
                });
                redis6.Subscribe(QQQ);
            }
        }
    }
}
