using dodohold.core;
using CSRedis;
using System.Data;

namespace molilian.core
{
    public partial class TkLogCore
    {
        static string queue_coupon_key = "queue:coupon_logs";


        public static async Task<int> InsertCouponLogAsync(int limit, YunhuiKit.RedisClient redis)
        {
            int total = 0;
            using var connection = DBContext.GetOpenConnection();
            connection.Open();
            using var transaction = connection.BeginTransaction();
            try
            {
                for (int i = 0; i < limit; i++)
                {
                    var data = await redis.LPopAsync<UnionCouponDTO>(queue_coupon_key);
                    if (data == null) break;


                    if (TestParseCore.InWhitelist(data.ip, data.oaid))
                    {
                        var test_data = data.Convert2Json().Convert2Object<TestUnionCouponDTO>();
                        connection.Insert(test_data);
                    }
                    else
                    {
                        connection.Insert(data);
                        if (data.success)
                        {
                            var success_data = data.Convert2Json().Convert2Object<SuccessUnionCouponDTO>();
                            connection.Insert(success_data);
                        }
                    }
                    total++;
                }
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                new LoggerLibrary("TkLogCore_error", "task_insert_parse_coupon_logs")
                      .Info(ex.Message, ex.StackTrace)
                      .SaveAsync();
                throw;
            }
            finally
            {
                connection.Close();
            }
            return total;
        }
        public static int task_insert_parse_coupon_logs(int limit, CSRedisClient redis)
        {
            int total = 0;
            using var connection = DBContext.GetOpenConnection();
            connection.Open();
            using var transaction = connection.BeginTransaction();
            try
            {
                for (int i = 0; i < limit; i++)
                {
                    var data = redis.LPop<UnionCouponDTO>(queue_coupon_key);
                    if (data == null) break;

                    if (TestParseCore.InWhitelist(data.ip, data.oaid))
                    {
                        var test_data = data.Convert2Json().Convert2Object<TestUnionCouponDTO>();
                        connection.Insert(test_data);
                    }
                    else
                    {
                        connection.Insert(data);
                        if (data.success)
                        {
                            var success_data = data.Convert2Json().Convert2Object<SuccessUnionCouponDTO>();
                            connection.Insert(success_data);
                        }
                    }
                    total++;
                }
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                new LoggerLibrary("TkLogCore_error", "task_insert_parse_coupon_logs")
                      .Info(ex.Message, ex.StackTrace)
                      .SaveAsync();
                throw;
            }
            finally
            {
                connection.Close();
            }
            return total;
        }
        public static async Task CouponLogAsync(UnionCouponDTO response, AlimamaPlus? alimamaPlus = null)
        {
            try
            {
                var ts = DateTime.Now - response.create_time;
                response.elapsedTime = (int)ts.TotalMilliseconds;
                _ = RedisHelper.RPushAsync(queue_coupon_key, response);


                if (!TestParseCore.InWhitelist(response.ip, response.oaid))
                {
                    saveCouponCache(response.channel.ToString(), response.accountId, response.accountName, response.success, response.message, response.reason);
                }

                if (response.success) await saveClientRequestTotalAsync(response.channel, response.ip, response.oaid);

                var account = await TkPoolCore.ALLGetOneAsync(response.accountId);
                bool is_hide = account.is_hide;

                if (!response.success && "nologin".Equals(response.message))
                {
                    switch (response.channel)
                    {
                        case TkChannelEnum.tb:
                            if (alimamaPlus != null)
                            {
                                (bool success, string message) = alimamaPlus.RenewCookie();
                                if (success) return;
                            }
                            TkPoolCore.Disabled(response.accountId, response.accountName, $"{response.rawContent}", is_hide);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                _ = new LoggerLibrary("unionCoupon", "database_error")
                .Info(response.rawContent)
                .Info(response.Convert2Json())
                .Info(ex.Message, ex.StackTrace)
                .SaveAsync();
            }
        }
        private static void saveCouponCache(string channel, int accountId, string accountName, bool success, string message, string reason)
        {
            saveAccountCouponCache("all", success, message, reason);
            saveAccountCouponCache($"{channel}", success, message, reason);
            if (accountId != 0)
            {
                saveAccountCouponCache($"{channel}_{accountId}", success, message, reason);
            }
        }

        private static void saveAccountCouponCache(string accountName, bool success, string message, string reason)
        {
            SaveStatsAccountCache("coupon_total", accountName, success, message, reason);
        }




    }

}
