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

namespace molilian.core
{
    public partial class TkLogCore
    {
        static string queue_parse_jd_key = "queue:parse_logs:jd";

        public static int task_insert_parse_jd_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<JdDataDTO>(queue_parse_jd_key);
                    if (data == null) break;


                    if (_test_oaid.Equals(data.oaid) ||
                         data.ip.Contains("127.0.0"))
                    {
                        save_jd_parse_logs(data, "jd_parse_logs_test", connection, transaction);
                    }
                    else
                    {
                        //save_jd_parse_logs(data, "jd_parse_logs", connection, transaction);

                        if (save_dailys_log)
                        {
                            string daily_table = $"jd_parse_logs_{data.create_time:yyyyMMdd}";
                            save_jd_parse_logs(data, daily_table, connection, transaction);
                        }

                        if (data.elapsedTime > 1000)
                        {
                            save_jd_parse_logs(data, "jd_parse_logs_test", connection, transaction);
                        }
                        if (data.success)
                        {
                            save_jd_parse_logs(data, "jd_parse_logs_success", connection, transaction);
                        }
                    }
                    total++;
                }
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                new LoggerLibrary("TkLogCore_error", "task_insert_parse_jd_logs")
                      .Info(ex.Message, ex.StackTrace)
                      .SaveAsync();
                throw;
            }
            finally
            {
                connection.Close();
            }
            return total;
        }

        public static async Task ParseLogAsync(JdDataDTO response)
        {
            try
            {
                var ts = DateTime.Now - response.create_time;
                response.elapsedTime = (int)ts.TotalMilliseconds;
                _ = RedisHelper.RPushAsync(queue_parse_jd_key, response);

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

                if (response.success || response.message.Equals("转链失败"))
                {
                    JdPoolCore.CallsIncrBy(response.accountId);
                }
                //CallsIncrBy

                if (response.success) saveClientRequestTotal(response.channel, response.ip, response.oaid);

                if (!response.success && ("nologin".Equals(response.reason) ||
                    "方法不存在".Equals(response.reason) ||
                    "未登录".Equals(response.reason)))
                {
                    await Task.Run(() =>
                    {
                        JdPoolCore.Disabled(response.accountId, response.accountName, $"{response.rawContent}\n{response.rawContent2}");
                    });
                    //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))
                {
                    JdPoolCore.AccountExhausted();
                }
            }
            catch (Exception ex) { }
        }
        private static int save_jd_parse_logs(JdDataDTO 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("success", data.success)
                .Add("message", data.message)
                .Add("reason", data.reason)
                .Add("content", data.content)
                .Add("itemId", data.itemId)
                .Add("itemName", data.itemName)
                .Add("pic", data.pic)
                .Add("couponAmount", data.couponAmount)
                .Add("promotionPrice", data.promotionPrice)
                .Add("taoToken", data.taoToken)
                .Add("shortLinkurl", data.shortLinkurl)
                .Add("deeplink_url", data.deeplink_url)
                .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);
        }

    }

}
