using dodohold.core;

namespace molilian.core
{

    public partial class MeituanPoolCore
    {
        private static string _end_point;
        static MeituanPoolCore()
        {
            _end_point = Environment.GetEnvironmentVariable("EndPoint");
        }
        private static readonly object _lockObj = new();
        private static IEnumerable<MeituanPoolDTO> _cached;

        public static MeituanPoolDTO? GetOne()
        {
            var list = List();
            if (!list.Any()) return null;
            return list.Where(IsNotExceedDailyIncomeLimit).OrderBy(l => Guid.NewGuid()).FirstOrDefault();
        }


        public static MeituanPoolDTO? GetOne(int id)
        {
            var list = List();
            if (!list.Any()) return null;
            return list.Where(e => e.id == id && IsNotExceedDailyIncomeLimit(e)).FirstOrDefault();
        }
        private static bool IsNotExceedDailyIncomeLimit(MeituanPoolDTO 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 = RiskControlCore.GetCalls(TkChannelEnum.meituan, item.id, DateTime.Now.ToString("yyyyMMdd"));
                if (daily_num >= item.daily_calls_limit) return false;
            }
            if (item.hourly_calls_limit > 0)
            {
                int hourly_num = RiskControlCore.GetCalls(TkChannelEnum.meituan, item.id, DateTime.Now.ToString("yyyyMMddHH"));
                if (hourly_num >= item.hourly_calls_limit) return false;
            }
            return true;
        }

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

            string cache_key = $"cache:meituan_pool";
            var list = RedisHelper.Get<IEnumerable<MeituanPoolDTO>>(cache_key);
            if (force || list == null)
            {
                lock (_lockObj)
                {
                    list = new DBContext.Table("meituan_pool")
                        .Where("status=@status", new { status = 1 })
                        .Select<MeituanPoolDTO>();
                    if (list == null) return default;
                    foreach (var item in list)
                    {
                        RiskControlCore.SetCallsAsync(TkChannelEnum.meituan, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
                        RiskControlCore.SetCallsAsync(TkChannelEnum.meituan, item.id, DateTime.Now.ToString("yyyyMMdd"), 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.QYWeixinPushNotifyAsync("没账号", $"【美团联盟】没有匹配账号");
        }

    }


}
