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 Spire.Pdf.Exporting.XPS.Schema;
using System.Xml.Linq;
using System.Net;
using TencentCloud.Mrs.V20200910.Models;


namespace molilian.core
{
    public partial class TkPoolCore
    {
        public enum TkAction
        {
            all,
            parse,
            coupon,
            promotionQuery
        }

        private static string _end_point;
        static TkPoolCore()
        {
            _end_point = Environment.GetEnvironmentVariable("EndPoint");
        }

        private static readonly object _lockObj = new();
        private static IEnumerable<TkPoolDTO> _cached;
        private static Dictionary<string, decimal> _incomeAmt = new();
        public static TkPoolDTO? GetOne(TkAction action)
        {
            var list = List();
            if (!list.Any()) return null;
            return list.Where(e => FilterNodes(e, action)).OrderBy(l => Guid.NewGuid()).FirstOrDefault();
        }
        public static TkPoolDTO? GetOne(int id)
        {
            var list = List();
            if (!list.Any()) return null;
            return list.Where(e => e.id == id).FirstOrDefault();
        }

        internal static void SaveIncomeAmt(string accountName, decimal income_amt)
        {
            string key = $"{accountName}:{DateTime.Now:yyyyMMdd}";
            if (_incomeAmt.ContainsKey(key))
            {
                _incomeAmt[key] = income_amt;
            }
            else
            {
                _incomeAmt.Add(key, income_amt);
            }
            string cache_key = $"cache:tk_pool:{key}:income_amt";

            var result = EndPointCore.ProcessEndPointNodes<bool>(node =>
            {
                if (!node.is_public_api) return true;
                if (string.IsNullOrEmpty(node.redis_server)) return true;

                var redis = RedisClientManager.GetRedisClient(node.redis_server);
                return redis.Set(cache_key, income_amt, 3 * 86400);
            });
        }
        public static decimal GetIncomeAmt(string accountName)
        {
            try
            {
                string key = $"{accountName}:{DateTime.Now:yyyyMMdd}";
                if (_incomeAmt.ContainsKey(key)) return _incomeAmt[key];

                string cache_key = $"cache:tk_pool:{key}:income_amt";
                return RedisHelper.Get<decimal>(cache_key);
            }
            catch (Exception ex) { return 0; }
        }
        private static bool FilterNodes(TkPoolDTO item, TkAction action)
        {
            if (!string.IsNullOrEmpty(item.suspended_endpoint) && item.suspended_endpoint.Contains($"{_end_point}|")) return false;

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

            if (item.daily_income_limit == 0) return true;
            decimal income_amt = GetIncomeAmt($"{item.id}");
            return income_amt < item.daily_income_limit;
        }

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

            string cache_key = $"cache:tk_pool";
            var list = RedisHelper.Get<IEnumerable<TkPoolDTO>>(cache_key);
            if (force || list == null)
            {
                lock (_lockObj)
                {
                    list = new DBContext.Table("tk_pool")
                        .Where("status=@status", new { status = 1 })
                        .Select<TkPoolDTO>();
                    if (list == null) return default;
                    RedisHelper.Set(cache_key, list, 30 * 86400);
                }
            }
            _cached = list;
            return list;
        }
        public static void Refresh()
        {
            _incomeAmt = [];
            _ = List(true);
        }
        public static void UpdateDrawBalance(string name, decimal amout)
        {
            new DBContext.Table("tk_pool")
                .Add("draw_balance", amout)
                .Where("name=@name", new { name })
                .Update();
            _ = List(true);
        }

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

            var update = new DBContext.Table("tk_pool").Add("suspended_endpoint:", $"CONCAT(suspended_endpoint, '{endpoint},')");

            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}】{endpoint} 暂停",
                priority = NifyMessagePriority.high,
                tags = ["red_circle"]
            });
            NotifyCore.AnPushNotify("暂停", $"【淘客{accountId}:{name}】{endpoint} 暂停");
            EndPointCore.NotifyReload(true);
        }

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

            var update = new DBContext.Table("tk_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.AnPushNotify("掉线", $"【淘客{accountId}:{name}】cookie 掉线");
            EndPointCore.NotifyReload(true);
        }

        public static int UpdateCookies(string cookies, string user_agent)
        {
            if (string.IsNullOrEmpty(cookies)) return 0;
            cookies += ";";
            string dnk = cookies.GetContentPart("dnk=", ";");
            string company = dnk;
            int accountId = 0;
            string tb_token = cookies.GetContentPart("_tb_token_=", ";");
            if (string.IsNullOrEmpty(dnk) || string.IsNullOrEmpty(tb_token)) return 0;
            var exist = new DBContext.Table("tk_pool").Fields("id, name, company, refpid, status").Get<dynamic>("name=@dnk", new { dnk });
            if (exist != null)
            {
                int status = exist.status;
                string refpid = exist.refpid;
                company = exist.company;
                accountId = exist.id;
                if (!string.IsNullOrEmpty(refpid)) status = 1;
                new DBContext.Table("tk_pool")
                   .Add("name", dnk)
                   .Add("tb_token", tb_token)
                   .Add("cookies", cookies)
                   .Add("user_agent", user_agent)
                   .Add("status", status)
                   .Add("suspended_endpoint", string.Empty)
                   .Add("last_time", DateTime.Now)
                   .Add("login_time", DateTime.Now)
                   .Where("id=@id", new { exist.id })
                   .Update();
                if (status == 1) _ = List(true);
            }
            else
            {
                accountId = new DBContext.Table("tk_pool")
                    .Add("name", dnk)
                    .Add("description", "由cookies上报创建此记录")
                    .Add("tb_token", tb_token)
                    .Add("refpid", string.Empty)
                    .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.AnPushNotify("上线", $"【淘宝联盟:{dnk}】cookie 上报更新");
            return accountId;
        }

        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("没账号", $"【淘客】没有匹配账号");
        }
    }

}
