using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dodohold.core;
using Dataoke;
using Google.Protobuf.WellKnownTypes;
using System.Xml.Linq;


namespace molilian.core
{

    public partial class KsPoolCore
    {
        public enum KsAction
        {
            all,
            parse,
            coupon,
            promotionQuery
        }
        private static string _end_point;
        private static Dictionary<string, decimal> _incomeAmt = new();
        static KsPoolCore()
        {
            _end_point = Environment.GetEnvironmentVariable("EndPoint");
        }

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

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


        public static KsPoolDTO? GetOne(int id, KsAction action)
        {
            var list = List();
            if (!list.Any()) return null;
            return list.Where(e => e.id == id && IsNotExceedDailyIncomeLimit(e, action)).FirstOrDefault();
        }
        private static bool IsNotExceedDailyIncomeLimit(KsPoolDTO item, KsAction action)
        {

            if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point))
            {
                if (item.end_point != _end_point) return false;
            }
            switch (action)
            {
                case KsAction.parse:
                    if (!item.enable_parse) return false;
                    break;
                case KsAction.coupon:
                    if (!item.enable_coupon) return false;
                    break;
            }

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

            if (item.daily_calls_limit > 0)
            {
                int daily_num = RiskControlCore.GetCalls(TkChannelEnum.ks, 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.ks, item.id, DateTime.Now.ToString("yyyyMMddHH"));
                if (hourly_num >= item.hourly_calls_limit) return false;
            }
            return true;
        }

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

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

                    foreach (var item in list)
                    {
                        RiskControlCore.SetCallsAsync(TkChannelEnum.ks, item.id, DateTime.Now.ToString("yyyyMMddHH"), item.current_hourly_calls);
                        RiskControlCore.SetCallsAsync(TkChannelEnum.ks, 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);
        }

        public static int Update(KsPoolDTO account)
        {
            return new DBContext.Table("ks_pool")
                .Add("current_hourly_calls", account.current_hourly_calls)
                .Add("current_daily_calls", account.current_daily_calls)

                .Add("today_clickNum", account.today_clickNum)
                .Add("today_cosFee", account.today_cosFee)
                .Add("today_cosPrice", account.today_cosPrice)
                .Add("today_finishCosFee", account.today_finishCosFee)
                .Add("today_finishCosPrice", account.today_finishCosPrice)
                .Add("today_finishOrderNum", account.today_finishOrderNum)
                .Add("today_orderNum", account.today_orderNum)

                .Where("id=@id", new { account.id })
                .Update();
        }



        public static int UpdateCookies(string cookies, string user_agent)
        {
            if (string.IsNullOrEmpty(cookies)) return 0;
            string pin = cookies.GetContentPart("pin=", ";");
            pin = pin.UrlDecode();

            string company = pin;
            int accountId = 0;
            if (string.IsNullOrEmpty(pin)) return 0;
            var exist = new DBContext.Table("ks_pool").Get<KsPoolDTO>("pin=@pin", new { pin });
            if (exist != null)
            {
                var status = exist.status;
                var work_mode = exist.work_mode;
                accountId = exist.id;
                if (work_mode == KsUnionWorkMode.Crawler) status = true;
                new DBContext.Table("ks_pool")
                   .Add("pin", pin)
                   .Add("cookies", cookies)
                   .Add("user_agent", user_agent)
                   .Add("status", status)
                   .Add("last_time", DateTime.Now)
                   .Add("login_time", DateTime.Now)
                   .Where("id=@id", new { exist.id })
                   .Update();
                if (status) _ = List(true);
            }
            else
            {
                accountId = new DBContext.Table("ks_pool")
                    .Add("pin", pin)
                    .Add("name", pin)
                    .Add("company", pin)
                    .Add("description", "由cookies上报创建此记录")
                    .Add("cookies", cookies)
                    .Add("user_agent", user_agent)
                    .Add("create_time", DateTime.Now)
                    .Add("last_time", DateTime.Now)
                    .Add("login_time", DateTime.Now)
                    .Add("status", 0)
                    .Create();
            }

            NotifyCore.Notify(new NifyMessage
            {
                message = $"【快手{accountId}:{company}】cookie 上线",
                tags = ["green_circle"]
            });
            EndPointCore.NotifyReload(true);
            //NotifyCore.QYWeixinPushNotifyAsync("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
            return accountId;
        }


        public static void Disabled(int accountId, string name, string content)
        {
            string cache_key = $"cache:ks_pool:{name}:disabled";
            long count = RedisHelper.IncrBy(cache_key);
            RedisHelper.Expire(cache_key, 10);
            if (count > 1) return;

            var update = new DBContext.Table("ks_pool").Add("status", 0);
            if (accountId > 0)
            {
                update.Where("id=@accountId", new { accountId }).Update();
            }
            else
            {
                update.Where("name=@name", new { name }).Update();
            }

            _ = List(true);

            NotifyCore.Notify(new NifyMessage
            {
                message = $"【快手联盟{accountId}:{name}】cookie 掉线\n\n{content}",
                priority = NifyMessagePriority.high,
                tags = ["red_circle"]
            });

            //NotifyCore.QYWeixinPushNotifyAsync("掉线", $"【快手{accountId}:{name}】cookie 掉线");
            EndPointCore.NotifyReload(true);
        }


        internal static void AccountExhausted()
        {
            string cache_key = $"cache:ks_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("没账号", $"【快手联盟】没有匹配账号");
        }


        internal static void NotifyInterfaceError(string reason)
        {
            string cache_key = $"cache:ks_pool:account:InterfaceError";
            long count = RedisHelper.IncrBy(cache_key);
            if (count > 1) return;
            RedisHelper.Expire(cache_key, 3600);
            NotifyCore.Notify(new NifyMessage
            {
                message = $"【快手联盟】{reason}",
                priority = NifyMessagePriority.high,
                tags = ["red_circle"]
            });
        }




    }


}
