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

namespace molilian.core
{
    public partial class TkLogCore
    {
        static string queue_tb_key = "queue:logs:tb";
        static string queue_jd_key = "queue:logs:jd";

        public static int task_insert_tk_logs(IDbConnection connection, IDbTransaction transaction, int limit, CSRedisClient redis)
        {
            int total = 0;
            for (int i = 0; i < limit; i++)
            {
                var data = redis.LPop<TkDataDTO>(queue_tb_key);
                if (data == null) break;

                if (_test_oaid.Equals(data.oaid) ||
                     data.ip.Contains("127.0.0"))
                {
                    save_tk_log(data, "tk_logs_test", connection, transaction);
                }
                else
                {
                    data.id = save_tk_log(data, "tk_logs", connection, transaction);
                    if (data.elapsedTime > 1000)
                    {
                        save_tk_log(data, "tk_logs_test", connection, transaction);
                    }
                    if (data.success)
                    {
                        save_tk_log(data, "tk_success_logs", connection, transaction);
                    }
                    if (!string.IsNullOrEmpty(data.itemId)) TkOrderTrackingCore.SaveLinkSummary(data);
                }
                total++;
            }

            for (int i = 0; i < limit; i++)
            {
                var data = redis.LPop<JdDataDTO>(queue_jd_key);
                if (data == null) break;
                new DBContext.Table(connection, "tk_logs")
                    .Add("end_point", data.end_point)
                    .Add("channel", (int)data.channel)
                    .Add("accountId", data.accountId)
                    .Add("accountName", data.accountName)
                    .Add("rawContent", data.rawContent)
                    .Add("rawContent2", data.rawContent2)
                    .Add("success", data.success)
                    .Add("message", data.message)
                    .Add("reason", data.reason)
                    .Add("shortLinkurl", data.shortLinkurl)
                    .Add("deeplink_url", data.deeplink_url)
                    .Add("elapsedTime", data.elapsedTime)
                    .Add("ip", data.ip)
                    .Add("oaid", data.oaid)
                    .Add("create_time", data.create_time)
                    .Create(DBContext.InsertType.NORMAL, transaction);
                total++;
            }
            return total;
        }
        public static async Task LogAsync(JdDataDTO response)
        {
            try
            {
                var ts = DateTime.Now - response.create_time;
                response.elapsedTime = (int)ts.TotalMilliseconds;
                _ = RedisHelper.RPushAsync(queue_jd_key, response);

                if (!response.ip.Contains("127.0.0"))
                {
                    saveCache(response.channel.ToString(), response.accountId, response.accountName, response.success, response.message, response.reason);
                }
            }
            catch (Exception ex) { }
        }
        public static async Task LogAsync(TkDataDTO response, AlimamaPlus? alimamaPlus = null)
        {
            try
            {
                var ts = DateTime.Now - response.create_time;
                response.elapsedTime = (int)ts.TotalMilliseconds;
                _ = RedisHelper.RPushAsync(queue_tb_key, response);

                if (!response.ip.Contains("127.0.0"))
                {
                    saveCache(response.channel.ToString(), response.accountId, response.accountName, response.success, response.message, response.reason);
                }

                if (!response.success && "nologin".Equals(response.message))
                {
                    switch (response.channel)
                    {
                        case TkChannelEnum.tb:

                            await Task.Run(() =>
                            {
                                if (alimamaPlus != null)
                                {
                                    (bool success, string message) = alimamaPlus.RenewCookie();
                                    if (success) return;
                                }
                                TkPoolCore.Disabled(response.accountId, response.accountName, $"{response.rawContent}\n{response.rawContent2}");
                            });
                            break;
                    }
                }
                if ("没有匹配账号".Equals(response.reason))
                {
                    TkPoolCore.AccountExhausted();
                }
            }
            catch (Exception ex)
            {
                _ = new LoggerLibrary("unionParse", "database_error")
                .Info(response.rawContent, response.rawContent2)
                .Info(response.Convert2Json())
                .Info(ex.Message, ex.StackTrace)
                .SaveAsync();
            }
        }

        private static int save_tk_log(TkDataDTO data, string tablename, IDbConnection connection, IDbTransaction transaction)
        {
            return new DBContext.Table(connection, tablename)
                  .Add("end_point", data.end_point)
                  .Add("channel", (int)data.channel)
                  .Add("accountId", data.accountId)
                  .Add("accountName", data.accountName)
                  .Add("rawContent", data.rawContent)
                  .Add("rawContent2", data.rawContent2)
                  .Add("success", data.success)
                  .Add("message", data.message)
                  .Add("reason", data.reason)
                  .Add("content", data.content)
                  .Add("couponAmount", data.couponAmount)
                  .Add("itemId", data.itemId)
                  .Add("itemName", data.itemName)
                  .Add("pic", data.pic)
                  .Add("promotionPrice", data.promotionPrice)
                  .Add("taoToken", data.taoToken)
                  .Add("shortLinkurl", data.shortLinkurl)
                  .Add("deeplink_url", data.deeplink_url)
                  .Add("num_iid", data.num_iid)
                  .Add("elapsedTime", data.elapsedTime)
                  .Add("subCode", data.subCode)
                  .Add("ip", data.ip)
                  .Add("oaid", data.oaid)
                  .Add("create_time", data.create_time)
                  .Create(DBContext.InsertType.NORMAL, transaction);
        }

    }

}
