using dodohold.core;

namespace molilian.core
{

    public partial class ElePoolCore
    {
        private static string _end_point;
        private static Dictionary<string, decimal> _incomeAmt = new();
        private static Dictionary<string, int> _calls = new();
        static ElePoolCore()
        {
            _end_point = Environment.GetEnvironmentVariable("EndPoint");
        }

        private static readonly object _lockObj = new();
        private static IEnumerable<ElePoolDTO> _cached;
    
        public static ElePoolDTO? GetOne()
        {
            var list = List();
            if (!list.Any()) return null;
            return list.Where(IsNotExceedDailyIncomeLimit).OrderBy(l => Guid.NewGuid()).FirstOrDefault();
        }


        public static ElePoolDTO? GetOne(int id)
        {
            var list = List();
            if (!list.Any()) return null;
            return list.Where(e => e.id == id && IsNotExceedDailyIncomeLimit(e)).FirstOrDefault();
        }
        internal static void CallsIncrBy(int accountId)
        {
            CallsIncrBy(accountId, DateTime.Now.ToString("yyyyMMdd"));
            CallsIncrBy(accountId, DateTime.Now.ToString("yyyyMMddHH"));
        }

        internal static void CallsIncrBy(int accountId, string flag)
        {
            string key = $"{accountId}:{flag}";
            if (_calls.ContainsKey(key))
            {
                _calls[key] = _calls[key] + 1;
            }
            else
            {
                _calls[key] = 1;
            }
            string cache_key = $"cache:ele_pool:{key}:calls:{flag}";
            RedisHelper.IncrBy(cache_key);
            RedisHelper.Expire(cache_key, 3 * 86400);
        }

        public static int SaveCalls(int accountId, string flag)
        {
            string key = $"{accountId}:{flag}";
            var result = EndPointCore.ProcessEndPointNodes<int>(node =>
            {
                if (!node.is_public_api) return 0;
                if (string.IsNullOrEmpty(node.redis_server)) return 0;


#if DEBUG
                switch (node.name)
                {

                    case "bj":
                        node.redis_server = "101.200.46.46:6379,password=pKBiS4ka2IpXayIdcx00,defaultDatabase=0,idleTimeout=20000,preheat=3,tryit=2,ssl=false,prefix=webhook";
                        break;
                    case "gz":
                        node.redis_server = "8.138.110.158:6379,password=pKBiS4ka2IpXayIdcx00,defaultDatabase=0,idleTimeout=20000,preheat=3,tryit=2,ssl=false,prefix=webhook";
                        break;
                    case "coupon1":
                        node.redis_server = "c1api.molilian.com:6379,password=pKBiS4ka2IpXayIdcx00,defaultDatabase=0,idleTimeout=20000,preheat=3,tryit=2,ssl=false,prefix=coupon";
                        break;
                    default: return 0;
                }
#endif

                string cache_key = $"cache:ele_pool:{key}:calls:{flag}";
                var redis = RedisClientManager.GetRedisClient(node.redis_server);
                return redis.Get<int>(cache_key);
            });
            int num = result.Sum();
            _calls.TryAdd(key, num);
            return num;
        }

        public static int GetCalls(int accountId, string flag)
        {
            try
            {
                string key = $"{accountId}:{flag}";
                if (_calls.ContainsKey(key)) return _calls[key];

                string cache_key = $"cache:ele_pool:{key}:calls:{flag}";
                int num = RedisHelper.Get<int>(cache_key);
                _calls.TryAdd(key, num);
                return num;
            }
            catch (Exception ex) { return 0; }
        }

        private static bool IsNotExceedDailyIncomeLimit(ElePoolDTO item)
        {
            if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point))
            {
                if (item.end_point != _end_point) return false;
            }

            // 使用初始化参数创建工作时间表
            if (!new WorkSchedule(item.time_range).IsWorkHour()) return false;

            if (item.daily_calls_limit > 0)
            {
                int daily_num = GetCalls(item.id, DateTime.Now.ToString("yyyyMMdd"));
                if (daily_num >= item.daily_calls_limit) return false;
            }
            if (item.hourly_calls_limit > 0)
            {
                int hourly_num = GetCalls(item.id, DateTime.Now.ToString("yyyyMMddHH"));
                if (hourly_num >= item.hourly_calls_limit) return false;
            }
            return true;
        }

        public static IEnumerable<ElePoolDTO> List(bool force = false)
        {
            if (!force && _cached != null) return _cached;

            string cache_key = $"cache:ele_pool";
            var list = RedisHelper.Get<IEnumerable<ElePoolDTO>>(cache_key);
            if (force || list == null)
            {
                lock (_lockObj)
                {
                    list = new DBContext.Table("ele_pool")
                        .Where("status=@status", new { status = 1 })
                        .Select<ElePoolDTO>();
                    if (list == null) return default;


                    _calls = new Dictionary<string, int>();
                    foreach (var item in list)
                    {
                        string key = $"{item.id}:{DateTime.Now:yyyyMMddHH}";
                        _calls.TryAdd(key, item.current_hourly_calls);

                        key = $"{item.id}:{DateTime.Now:yyyyMMddHH}";
                        _calls.TryAdd(key, item.current_daily_calls);
                    }
                    RedisHelper.Set(cache_key, list, 30 * 86400);
                }
            }
            _cached = list;
            return list;
        }
        public static void Refresh()
        {
            _ = List(true);
        }
        
        internal static void AccountExhausted()
        {
            string cache_key = $"cache:tk_pool:account:exhausted";
            long count = RedisHelper.IncrBy(cache_key);
            if (count > 1) return;
            RedisHelper.Expire(cache_key, 3600);
            NotifyCore.Notify(new NifyMessage
            {
                message = $"【京东联盟】没有匹配账号",
                priority = NifyMessagePriority.high,
                tags = ["red_circle"]
            });
            NotifyCore.AnPushNotify("没账号", $"【京东联盟】没有匹配账号");
        }

    }


}
