using FreeRedis;
using ServiceCenter.Logs;

namespace ServiceCenter.Redis
{
    /// <summary>
    /// Redis
    /// </summary>
    public class RedisHub
    {
        /// <summary>
        /// 连接集合
        /// </summary>
        private static List<RedisClientList> RedisClients = new List<RedisClientList>();

        /// <summary>
        /// 默认上下文类类型
        /// </summary>
        public static string DefaultContextType { get; private set; } = null!;

        /// <summary>
        /// 默认监控上下文类类型
        /// </summary>
        public static string MonitorContextType { get; private set; } = null!;

        /// <summary>
        /// 默认调试上下文类类型
        /// </summary>
        public static string DebugContextType { get; private set; } = null!;

        /// <summary>
        /// 默认WMS上下文类类型
        /// </summary>
        public static string WMSContextType { get; private set; } = null!;

        public static object redisLock = new object();

        /// <summary>
        /// 设置默认链接
        /// </summary>
        /// <param name="key"></param>
        public static void SetDefaultContextType(string key)
        {
            DefaultContextType = key;
        }

        /// <summary>
        /// 设置监控链接
        /// </summary>
        /// <param name="key"></param>
        public static void SetMonitorContextType(string key)
        {
            MonitorContextType = key;
        }

        /// <summary>
        /// 设置调试链接
        /// </summary>
        /// <param name="key"></param>
        public static void SetDebugContextType(string key)
        {
            DebugContextType = key;
        }

        /// <summary>
        /// 设置WMS链接
        /// </summary>
        /// <param name="key"></param>
        public static void SetWMSContextType(string key)
        {
            WMSContextType = key;
        }

        /// <summary>
        /// 默认链接
        /// </summary>
        public static RedisClient Default
        {
            get
            {
                {
                    if (DefaultContextType == null)
                        throw new Exception("请先设置默认RedisDB库,调用静态方法SetDefaultDbContextType()");
                    return Context(DefaultContextType);
                }
            }
        }

        /// <summary>
        /// 监控连接
        /// </summary>
        public static RedisClient Monitor
        {
            get
            {
                {
                    if (MonitorContextType == null) throw new Exception("请先设置监控RedisDB库,调用静态方法SetMonitorContextType()");
                    return Context(MonitorContextType);
                }
            }
        }

        /// <summary>
        ///调试连接
        /// </summary>
        public static RedisClient Debug
        {
            get
            {
                {
                    if (MonitorContextType == null)
                        throw new Exception("请先设置DebugRedisDB库,调用静态方法SetDebugContextType()");
                    return Context(MonitorContextType);
                }
            }
        }

        /// <summary>
        ///调试连接
        /// </summary>
        public static RedisClient WMS
        {
            get
            {
                {
                    if (WMSContextType == null) throw new Exception("请先设置WMSRedisDB库,调用静态方法SetWMSContextTypee()");
                    return Context(WMSContextType);
                }
            }
        }

        /// <summary>
        /// 创建一个连接
        /// </summary>
        /// <param name="connectionString"> 连接字符串</param>
        /// <param name="key">标识</param>
        /// <param name="defaultClient"> 是否为默认连接，默认为false</param>
        /// <returns></returns>
        public static RedisClient CreateContext(string connectionString, string key, bool defaultClient = false)
        {
            var ctx = RedisClients.FirstOrDefault(v => v.Key == key);
            if (ctx != null) return ctx.Client;
            ctx = new RedisClientList(key, new RedisClient(connectionString), connectionString);
            RedisClients.Add(ctx);
            if (defaultClient)
            {
                SetDefaultContextType(key);
            }
            return ctx.Client;
        }

        /// <summary>
        /// 获取指定的连接
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static RedisClient Context(string key)
        {
            var ctx = RedisClients.FirstOrDefault(v => v.Key == key);
            if (ctx == null) throw new Exception("没有对应的链接，请先调用创建");
            return ctx.Client;
        }

        /// <summary>
        ///  执行并发锁
        ///  使用默认连接
        /// </summary>
        /// <param name="lockKey">并发锁key</param>
        /// <param name="act">执行内容</param>
        /// <exception cref="Exception"></exception>
        public static void Do(string lockKey, Action<RedisClient> act) => Do(DefaultContextType, lockKey, act);

        /// <summary>
        ///  执行并发锁
        ///  指定redis
        /// </summary>
        /// <param name="key">连接key</param>
        /// <param name="lockKey">并发锁key</param>
        /// <param name="act">执行内容</param>
        /// <exception cref="Exception"></exception>
        public static void Do(string key, string lockKey, Action<RedisClient> act)
        {
            if (!RedisClients.Any()) throw new Exception($"请调用{nameof(CreateContext)}方法设置设置数据库连接");
            var redis = Context(key);
            lockKey = "ConcurrentLock:" + lockKey;
            try
            {
                if (redis.Exists(lockKey)) throw new Exception($"重复调用:{lockKey}");
                redis.Set(lockKey, lockKey);
                redis.Expire(lockKey, 60);
                act(redis);
            }
            catch (Exception ex)
            {
                throw new KnownException($"{ex.Message}", LogLevelEnum.Mid);
            }
            finally
            {
                redis.Del(lockKey);
            }
        }
    }
}
