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

namespace molilian.core
{
    public partial class TkLogCore
    {

        static string queue_activity_key = "queue:activity_logs";

        public static async Task<int> InsertActivityLogAsync(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<TkActivityDTO>(queue_activity_key);
                    if (data == null) break;

                    if (TestParseCore.InWhitelist(data.ip, data.oaid))
                    {
                        // For test environment, could create a test version if needed
                        string daily_table = $"tk_activity_logs_test";
                        save_activity_logs(data, daily_table, connection, transaction);
                    }
                    else
                    {
                        string daily_table = $"tk_activity_logs_{data.create_time:yyyyMMdd}";
                        save_activity_logs(data, daily_table, connection, transaction);
                    }
                    total++;
                }
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                new LoggerLibrary("TkLogCore_error", "task_insert_activity_logs")
                      .Info(ex.Message, ex.StackTrace)
                      .SaveAsync();
                throw;
            }
            finally
            {
                connection.Close();
            }
            return total;
        }

        public static async Task TkActivityLogAsync(TkActivityDTO response)
        {
            try
            {
                if (response.create_time == null)
                {
                    response.create_time = DateTime.Now;
                }

                var ts = DateTime.Now - response.create_time.Value;
                response.elapsedTime = (int)ts.TotalMilliseconds;

                _ = RedisHelper.RPushAsync(queue_activity_key, response);

                if (!TestParseCore.InWhitelist(response.ip, response.oaid))
                {
                    saveActivityCache(response.page_id, 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 == null ? false : account.is_hide;

                if (!response.success && "nologin".Equals(response.message))
                {
                    switch (response.channel)
                    {
                        case TkChannelEnum.tb:
                            TkPoolCore.Disabled(response.accountId, response.accountName, $"{response.reason}", is_hide);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                _ = new LoggerLibrary("tkActivity", "database_error")
                .Info(response.Convert2Json())
                .Info(ex.Message, ex.StackTrace)
                .SaveAsync();
            }
        }

        private static void saveActivityCache(string channel, int accountId, string accountName, bool success, string message, string reason)
        {
            saveAccountActivityCache("all", success, message, reason);
            saveAccountActivityCache($"{channel}", success, message, reason);
            if (accountId != 0)
            {
                saveAccountActivityCache($"{channel}_{accountId}", success, message, reason);
            }
        }

        private static int save_activity_logs(TkActivityDTO data, string tablename, IDbConnection connection, IDbTransaction transaction)
        {
            return new DBContext.Table(connection, tablename)
                .Add("end_point", data.end_point)
                .Add("channel", data.channel)
                .Add("accountId", data.accountId)
                .Add("accountName", data.accountName)
                .Add("proxy_node", data.proxy_node)
                .Add("page_id", data.page_id)
                .Add("item_id", data.item_id)
                .Add("success", data.success)
                .Add("reason", data.reason)
                .Add("message", data.message)
                .Add("deeplink_url", data.deeplink_url)
                .Add("create_time", data.create_time)
                .Add("elapsedTime", data.elapsedTime)
                .Add("elapsedTime2", data.elapsedTime2)
                .Add("ip", data.ip)
                .Add("oaid", data.oaid)
                .Add("estimatedCommission", data.estimatedCommission)
                .Add("maxCommission", data.maxCommission)
                .Add("zkFinalPrice", data.zkFinalPrice)
                .Add("reservePrice", data.reservePrice)
                .Add("title", data.title)
                .Add("picUrl", data.picUrl)
                .Add("shortTitle", data.shortTitle)
                .Add("priceAfterCoupon", data.priceAfterCoupon)
                .Add("commissionRate", data.commissionRate)
                .Add("couponAmount", data.couponAmount)
                .Create(DBContext.InsertType.NORMAL, transaction);
        }

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


    }

}
