using dodohold.core;
using System.Threading.Channels;

namespace molilian.core
{

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

        private static readonly object _lockObj = new();
        private static IEnumerable<CpsLinksDTO> _links_cached;
        private static IEnumerable<CpsPoolDTO> _cached;

        public static CpsLinksDTO? GetOne(string channel)
        {
            var list = List();
            if (!list.Any()) return null;

            var pool = list.Where(e => e.channel_code == channel && e.status).FirstOrDefault();
            if (pool == null) return null;

            var links = LinksList();
            if (!links.Any()) return null;

            return links.Where(e => IsEligible(e, channel)).OrderByDescending(e => e.priority_weight).FirstOrDefault();
        }


        private static bool IsEligible(CpsLinksDTO item, string channel)
        {
            if (item.channel_code != channel) return false;

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

            var now = DateTime.Now;
            if (item.start_time > now || now > item.end_time) return false;
            return true;
        }

        public static IEnumerable<CpsPoolDTO> List(bool force = false)
        {
#if DEBUG
            return new DBContext.Table("cps_pool")
                .Where("status=@status", new { status = 1 })
                .Select<CpsPoolDTO>();
#else

            if (!force && _cached != null) return _cached;

            string cache_key = $"cache:cps_pool";
            var list = RedisHelper.Get<IEnumerable<CpsPoolDTO>>(cache_key);
            if (force || list == null)
            {
                lock (_lockObj)
                {
                    list = new DBContext.Table("cps_pool")
                        .Where("status=@status", new { status = 1 })
                        .Select<CpsPoolDTO>();
                    if (list == null) return default;
                    RedisHelper.Set(cache_key, list, 30 * 86400);
                }
            }
            _cached = list;
            return list;
#endif
        }

        public static IEnumerable<CpsLinksDTO> LinksList(bool force = false)
        {
#if DEBUG
            return new DBContext.Table("cps_links")
                        .Where("status=@status", new { status = 1 })
                        .Select<CpsLinksDTO>();
#else
            if (!force && _links_cached != null) return _links_cached;

            string cache_key = $"cache:cps_links";
            var list = RedisHelper.Get<IEnumerable<CpsLinksDTO>>(cache_key);
            if (force || list == null)
            {
                lock (_lockObj)
                {
                    list = new DBContext.Table("cps_links")
                        .Where("status=@status", new { status = 1 })
                        .Select<CpsLinksDTO>();
                    if (list == null) return default;
                    RedisHelper.Set(cache_key, list, 30 * 86400);
                }
            }
            _links_cached = list;
            return list;
#endif
        }

        public static void Refresh()
        {
            _ = List(true);
            _ = LinksList(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 = $"【CPS优惠券】没有匹配账号",
                priority = NifyMessagePriority.high,
                tags = ["red_circle"]
            });
            NotifyCore.AnPushNotify("没账号", $"【CPS优惠券】没有匹配账号");
        }

    }


}
