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

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


        public static async Task<int> InsertParsePddLogAsync(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<PddDataDTO>(queue_parse_pdd_key);
                    if (data == null) break;

                    if (TestParseCore.InWhitelist(data.ip, data.oaid))
                    {
                        save_pdd_parse_logs(data, "pdd_parse_logs_test", connection, transaction);

                    }
                    else
                    {
                        string daily_table;
                        if ("dp".Equals(data.parse_type))
                        {
                            daily_table = $"pdd_dp_logs_{data.create_time:yyyyMMdd}";
                            save_pdd_parse_logs(data, daily_table, connection, transaction);
                        }

                        daily_table = $"pdd_parse_logs_{data.create_time:yyyyMMdd}";
                        save_pdd_parse_logs(data, daily_table, connection, transaction);

                        //if (!data.success)
                        //{
                        //    save_pdd_parse_logs(data, "pdd_parse_logs_fail", 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_parse_pdd_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<PddDataDTO>(queue_parse_pdd_key);
                    if (data == null) break;


                    if (TestParseCore.InWhitelist(data.ip, data.oaid))
                    {
                        save_pdd_parse_logs(data, "pdd_parse_logs_test", connection, transaction);
                    }
                    else
                    {
                        //save_pdd_parse_logs(data, "pdd_parse_logs", connection, transaction);
                        //if (save_dailys_log)
                        {
                            string daily_table = $"pdd_parse_logs_{data.create_time:yyyyMMdd}";
                            save_pdd_parse_logs(data, daily_table, connection, transaction);
                        }
                        //if (!data.success)
                        //{
                        //    save_pdd_parse_logs(data, "pdd_parse_logs_fail", 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 async Task ParseLogAsync(PddDataDTO response)
        {
            try
            {
                var ts = DateTime.Now - response.create_time;
                response.elapsedTime = (int)ts.TotalMilliseconds;
                _ = RedisKit.RPushAsync(queue_parse_pdd_key, response);

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

                //if (response.success) saveClientRequestTotal(response.channel, response.ip, response.oaid);
                if (response.success || response.message.Equals("转链失败"))
                {
                    await RiskControlCore.CallsIncrByAsync(response.channel, response.accountId);
                    await saveClientRequestTotalAsync(response.channel, response.ip, response.oaid);
                }
                //30007:检测到您推广行为异常，链接生成失败
                if (response.reason.Equals("您的调用次数过高"))
                {
                    PddPoolCore.TempSuspend(response.accountId);
                }

                if (!response.success && ("nologin".Equals(response.reason) ||
                    "方法不存在".Equals(response.reason) ||
                    "43001:会话已过期".Equals(response.reason) ||
                    "未登录".Equals(response.reason)))
                {
                    PddPoolCore.Disabled(response.accountId, response.accountName, $"{response.rawContent}\n{response.rawContent2}");
                }
                if (response.reason.Contains("当前账号被禁止使用转链功能"))
                {
                    PddPoolCore.Disabled(response.accountId, response.accountName, response.reason);
                }
                if (response.reason.Contains("没有匹配账号"))
                {
                    PddPoolCore.AccountExhausted();
                }
            }
            catch (Exception ex) { }
        }
        private static int save_pdd_parse_logs(PddDataDTO 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("proxy_node", data.proxy_node)
                .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("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("elapsedTime2", data.elapsedTime2)
                .Add("elapsedTime3", data.elapsedTime3)
                .Add("subCode", data.subCode)
                .Add("ip", data.ip)
                .Add("oaid", data.oaid)
                .Add("riskStrategy", data.riskStrategy)
                .Add("launchScene", data.launchScene)
                .Add("create_time", data.create_time)
                .Add("parse_type", data.parse_type)
                .Create(DBContext.InsertType.NORMAL, transaction);

        }

    }

}
