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

namespace molilian.core
{
    public partial class TkLogCore
    {
        static string promotion_img_key = "queue:promotion:img";

        public static async Task<int> InsertPromotionImgAsync(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<PromotionQueryDTO>(promotion_img_key);
                    if (data == null) break;

                    if (data.success)
                    {
                        data.similarPromotion = string.Empty;
                        data.promotionImg = string.Empty;
                    }

                    //按日保存数据
                    string daily_table = $"tk_promotion_logs_{data.create_time:yyyyMMdd}";
                    save_tk_promotion_img_logs(data, daily_table, connection, transaction);

                    total++;
                }
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                new LoggerLibrary("TkLogCore_error", "task_insert_parse_pdd_logs")
                      .Info(ex.Message, ex.StackTrace)
                      .SaveAsync();
                throw;
            }
            finally
            {
                connection.Close();
            }
            return total;
        }

        public static int task_insert_promotion_img_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<PromotionQueryDTO>(promotion_img_key);
                    if (data == null) break;

                    if (data.success)
                    {
                        data.similarPromotion = string.Empty;
                        data.promotionImg = string.Empty;
                    }

                    //按日保存数据
                    string daily_table = $"tk_promotion_logs_{data.create_time:yyyyMMdd}";
                    save_tk_promotion_img_logs(data, daily_table, connection, transaction);

                    total++;
                }
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                new LoggerLibrary("TkLogCore_error", "task_insert_parse_pdd_logs")
                      .Info(ex.Message, ex.StackTrace)
                      .SaveAsync();
                throw;
            }
            finally
            {
                connection.Close();
            }
            return total;
        }
        private static int save_tk_promotion_img_logs(PromotionQueryDTO data, string tablename, IDbConnection connection, IDbTransaction transaction)
        {
            try
            {
                return new DBContext.Table(connection, tablename)
                    .Add("accountId", data.accountId)
                    .Add("accountName", data.accountName)
                    .Add("proxy_node", data.proxy_node)
                    .Add("proxy_nodename", data.proxy_nodename)
                    //.Add("img", data.img)
                    .Add("img", string.Empty)
                    .Add("ip", data.ip)
                    .Add("oaid", data.oaid)
                    .Add("scene", data.scene)
                    .Add("success", data.success)
                    .Add("message", data.message)
                    .Add("reason", data.reason)
                    .Add("url", data.url)
                    .Add("similarPromotion", data.similarPromotion)
                    .Add("promotionImg", data.promotionImg)

                    .Add("elapsedTime", data.elapsedTime)
                    .Add("elapsedTime2", data.elapsedTime2)
                    .Add("elapsedTime3", data.elapsedTime3)
                    .Add("elapsedTime4", data.elapsedTime4)
                    .Add("create_time", data.create_time)
                    .Add("end_point", data.end_point)
                    .Create(DBContext.InsertType.NORMAL, transaction);
            }
            catch (Exception ex) { return 0; }
        }

        public static async Task PromotionImgLogAsync(PromotionQueryDTO response)
        {
            try
            {
                var ts = DateTime.Now - response.create_time;
                response.elapsedTime = (int)ts.TotalMilliseconds;
                _ = RedisKit.RPushAsync(promotion_img_key, response);

                _ = savePromotionCacheAsync(response.accountId, response.accountName, response.scene, response.success, response.message, response.reason);
            }
            catch (Exception ex) { }
        }





        private static async Task savePromotionCacheAsync(int accountId, string accountName, string scene, bool success, string message, string reason)
        {
            await savePromotionAccountCacheAsync("all", success, message, reason);
            await savePromotionAccountCacheAsync($"{accountId}", success, message, reason);
            await savePromotionAccountCacheAsync($"all_scene_{scene}", success, message, reason);
            await savePromotionAccountCacheAsync($"{accountId}_{scene}", success, message, reason);
        }

        private static async Task savePromotionAccountCacheAsync(string accountName, bool success, string message, string reason)
        {
            await SaveStatsAccountCacheAsync("promotion_total", accountName, success, message, reason);
        }

    }

}
