using System;
using System.Collections.Generic;
using Library;
using LitJson;
using System.Linq;
using System.Data;
using System.Threading;
using MySystem.PxcModels;

namespace MySystem
{
    public class StatHelpProfitService
    {
        public readonly static StatHelpProfitService Instance = new StatHelpProfitService();
        private StatHelpProfitService()
        { }






        // 统计交易额V2
        public void StartEverDayV2()
        {
            Thread th = new Thread(StartEverDayV2Do);
            th.IsBackground = true;
            th.Start();
        }
        public void StartEverDayV2Do()
        {
            while (true)
            {
                if (RedisDbconn.Instance.Get<string>("StatServerStatus") == "1" && DateTime.Now.Hour >= 3)
                {
                    StatTradeAmountEverDayV2();
                }
                Thread.Sleep(30000);
            }
        }
        public void StatTradeAmountEverDayV2()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时执行助利宝交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    string startId = function.ReadInstance("/TradeRecord/Id3.txt");
                    if (string.IsNullOrEmpty(startId))
                    {
                        startId = "2750000";
                    }
                    DataTable idsDt = OtherMySqlConn.dtable("select Id from TradeRecord where Id>=" + startId + " and ActStatus=1 and CreateDate>='2022-09-05 00:00:00' and MerchantId in (select MerchantId from HelpProfitMerIds) and SeoTitle='HelpProfit' and QueryCount>0 and QueryCount<3 order by Id limit 50");
                    if (idsDt.Rows.Count > 0)
                    {
                        string ids = "";
                        foreach (DataRow idsDr in idsDt.Rows)
                        {
                            ids += idsDr["Id"].ToString() + ",";
                            startId = idsDr["Id"].ToString();
                        }
                        DataTable selfDt = OtherMySqlConn.dtable("select MerchantId,DATE_FORMAT(CreateDate,'%Y%m%d'),sum(TradeAmount) from TradeRecord where Id in (" + ids.TrimEnd(',') + ") group by MerchantId,DATE_FORMAT(CreateDate,'%Y%m%d')");
                        if (selfDt.Rows.Count > 0)
                        {
                            function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "实时执行助利宝交易额日志");
                            foreach (DataRow selfDr in selfDt.Rows)
                            {
                                int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                                string TradeDate = selfDr[1].ToString();
                                string TradeMonth = TradeDate.Substring(0, 6);
                                decimal TradeAmount = decimal.Parse(selfDr[2].ToString());
                                HelpProfitMerIds merIds = db.HelpProfitMerIds.FirstOrDefault(m => m.MerchantId == MerchantId) ?? new HelpProfitMerIds();
                                bool Check = CheckAmount(db, MerchantId, merIds.UserId, TradeMonth);
                                if (Check)
                                {
                                    decimal MoreAmount = TradeAmount * 0.01M;
                                    int random = function.get_Random(0, 10000);
                                    // if(MoreAmount > 1 && random < 5000)
                                    // {
                                    MoreAmount = decimal.Parse(function.CheckInt(MoreAmount.ToString().Split(".")[0]));
                                    // }
                                    HelpProfitMerTradeSummay selfStat = db.HelpProfitMerTradeSummay.FirstOrDefault(m => m.MerchantId == MerchantId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate);
                                    if (selfStat == null)
                                    {
                                        selfStat = db.HelpProfitMerTradeSummay.Add(new HelpProfitMerTradeSummay()
                                        {
                                            TradeMonth = TradeMonth,
                                            TradeDate = TradeDate,
                                            MerchantId = MerchantId,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    selfStat.TradeAmount += TradeAmount + MoreAmount;

                                    HelpProfitMerTradeMonthSummay monthStat = db.HelpProfitMerTradeMonthSummay.FirstOrDefault(m => m.MerchantId == MerchantId && m.TradeMonth == TradeMonth);
                                    if (monthStat == null)
                                    {
                                        monthStat = db.HelpProfitMerTradeMonthSummay.Add(new HelpProfitMerTradeMonthSummay()
                                        {
                                            TradeMonth = TradeMonth,
                                            MerchantId = MerchantId,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    monthStat.TradeAmount += TradeAmount + MoreAmount;

                                    HelpProfitAmountSummary amountStat = db.HelpProfitAmountSummary.FirstOrDefault(m => m.UserId == merIds.UserId && m.TradeMonth == TradeMonth);
                                    if (amountStat == null)
                                    {
                                        amountStat = db.HelpProfitAmountSummary.Add(new HelpProfitAmountSummary()
                                        {
                                            TradeMonth = TradeMonth,
                                            UserId = merIds.UserId,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    amountStat.TradeAmount += TradeAmount + MoreAmount;
                                }
                            }
                            OtherMySqlConn.op("update TradeRecord set QueryCount=3 where Id in (" + ids.TrimEnd(',') + ")");
                            function.WritePage("/TradeRecord/", "Id3.txt", startId);
                        }
                        db.SaveChanges();
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时执行助利宝交易额异常");
                }
            }
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "实时执行助利宝交易额日志");
        }

        public void StatTradeAmountTmp()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时执行助利宝交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    DataTable selfDt = OtherMySqlConn.dtable("select MerchantId,DATE_FORMAT(CreateDate,'%Y%m'),sum(TradeAmount) from TradeRecord where CreateDate>='2022-09-05 00:00:00' and MerchantId in (select MerchantId from HelpProfitMerIds) and SeoTitle='HelpProfit' group by MerchantId,DATE_FORMAT(CreateDate,'%Y%m') order by MerchantId,DATE_FORMAT(CreateDate,'%Y%m')");
                    if (selfDt.Rows.Count > 0)
                    {
                        function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "实时执行助利宝交易额日志");
                        foreach (DataRow selfDr in selfDt.Rows)
                        {
                            int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                            string TradeMonth = selfDr[1].ToString();
                            decimal TradeAmount = decimal.Parse(selfDr[2].ToString());
                            HelpProfitMerIds merIds = db.HelpProfitMerIds.FirstOrDefault(m => m.MerchantId == MerchantId) ?? new HelpProfitMerIds();
                            HelpProfitAmountSummary profitStat = db.HelpProfitAmountSummary.FirstOrDefault(m => m.UserId == merIds.UserId && m.TradeMonth == TradeMonth);
                            if (profitStat == null)
                            {
                                int Month = db.HelpProfitAmountSummary.Count(m => m.UserId == merIds.UserId && Convert.ToInt32(m.TradeMonth) <= Convert.ToInt32(TradeMonth));
                                profitStat = db.HelpProfitAmountSummary.Add(new HelpProfitAmountSummary()
                                {
                                    TradeMonth = TradeMonth,
                                    UserId = merIds.UserId,
                                    QueryCount = Month + 1,
                                }).Entity;
                                db.SaveChanges();
                            }
                            profitStat.TradeAmount += TradeAmount;
                        }
                    }
                    db.SaveChanges();
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时执行助利宝交易额2异常");
                }
            }
            db.Dispose();
        }

        // 统计创客商机台数
        public void StartUserTrade()
        {
            Thread th = new Thread(StartUserTradeDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartUserTradeDo()
        {
            while (true)
            {
                if (RedisDbconn.Instance.Get<string>("StatServerStatus") == "1" && DateTime.Now.Hour >= 3)
                {
                    StartUserTradeGo();
                }
                Thread.Sleep(30000);
            }
        }
        public void StartUserTradeGo()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时统计助利宝创客交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    bool op = true;
                    while(op)
                    {
                        string startId = function.ReadInstance("/TradeRecord/HelpProfitMerchantForUserId.txt");
                        if (string.IsNullOrEmpty(startId))
                        {
                            startId = "0";
                        }
                        DataTable idsDt = OtherMySqlConn.dtable("select Id from HelpProfitMerchantForUser where Id>=" + startId + " and Status=0 order by Id limit 50");
                        if (idsDt.Rows.Count > 0)
                        {
                            string ids = "";
                            foreach (DataRow idsDr in idsDt.Rows)
                            {
                                ids += idsDr["Id"].ToString() + ",";
                                startId = idsDr["Id"].ToString();
                            }
                            DataTable selfDt = OtherMySqlConn.dtable("select UserId,DATE_FORMAT(CreateDate,'%Y%m'),count(Id) from HelpProfitMerchantForUser where Id in (" + ids.TrimEnd(',') + ") group by UserId,DATE_FORMAT(CreateDate,'%Y%m')");
                            if (selfDt.Rows.Count > 0)
                            {
                                function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "实时统计助利宝创客交易额日志");
                                foreach (DataRow selfDr in selfDt.Rows)
                                {
                                    int UserId = int.Parse(selfDr["UserId"].ToString());
                                    string TradeMonth = selfDr[1].ToString();
                                    int MerCount = int.Parse(selfDr[2].ToString());
                                    HelpProfitAmountSummary selfStat = db.HelpProfitAmountSummary.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth);
                                    if (selfStat == null)
                                    {
                                        int CheckMonth = db.HelpProfitAmountSummary.Count(m => m.UserId == UserId && Convert.ToInt32(m.TradeMonth) <= Convert.ToInt32(TradeMonth));
                                        selfStat = db.HelpProfitAmountSummary.Add(new HelpProfitAmountSummary()
                                        {
                                            TradeMonth = TradeMonth,
                                            UserId = UserId,
                                            QueryCount = CheckMonth + 1,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    selfStat.MerCount += MerCount;
                                    int Month = selfStat.QueryCount;
                                    if(Month > 24)
                                    {
                                        Month = 24;
                                    }
                                    selfStat.MaxAmount += EveryMonthFixedVal()[Month] * MerCount;
                                }
                                OtherMySqlConn.op("update HelpProfitMerchantForUser set Status=1 where Id in (" + ids.TrimEnd(',') + ")");
                                function.WritePage("/TradeRecord/", "HelpProfitMerchantForUserId.txt", startId);
                            }
                            db.SaveChanges();
                        }
                        else
                        {
                            op = false;
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时统计助利宝创客交易额异常");
                }
            }
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "实时统计助利宝创客交易额日志");
        }




        //计算商户交易额是否入账
        private bool CheckAmount(WebCMSEntities db, int MerchantId, int UserId, string TradeMonth)
        {
            HelpProfitAmountSummary Summary = db.HelpProfitAmountSummary.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth) ?? new HelpProfitAmountSummary();
            // ====================
            if(DateTime.Now >= DateTime.Parse("2023-02-01 00:00:00") && DateTime.Now < DateTime.Parse("2023-03-01 00:00:00"))
            {
                HelpProfitAmountSummary PreSummary = db.HelpProfitAmountSummary.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == "202301") ?? new HelpProfitAmountSummary();
                if(PreSummary.TradeAmount > PreSummary.MaxAmount)
                {
                    string conn = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
                    DataTable check = CustomerSqlConn.dtable("SELECT DISTINCT TradeDate FROM HelpProfitMerTradeSummay WHERE MerchantId IN(SELECT MerchantId FROM HelpProfitMerIds WHERE UserId=" + UserId + ") AND TradeMonth='202301'", conn);
                    if(check.Rows.Count < 31)
                    {
                        decimal HelpAmount = 0; //当天总交易额
                        DataTable dt = CustomerSqlConn.dtable("SELECT SUM(TradeAmount) TradeAmount FROM HelpProfitMerTradeSummay WHERE MerchantId IN(SELECT MerchantId FROM HelpProfitMerIds WHERE UserId=" + UserId + ") AND TradeDate='" + DateTime.Now.ToString("yyyyMMdd") + "'", conn);
                        if(dt.Rows.Count > 0)
                        {
                            HelpAmount = decimal.Parse(function.CheckNum(dt.Rows[0]["TradeAmount"].ToString()));
                        }
                        decimal PreHelpAmount = 0; //上月当天总交易额
                        dt = CustomerSqlConn.dtable("SELECT SUM(TradeAmount) TradeAmount FROM HelpProfitMerTradeSummay WHERE MerchantId IN(SELECT MerchantId FROM HelpProfitMerIds WHERE UserId=" + UserId + ") AND TradeDate='" + DateTime.Now.AddMonths(-1).ToString("yyyyMMdd") + "'", conn);
                        if(dt.Rows.Count > 0)
                        {
                            PreHelpAmount = decimal.Parse(function.CheckNum(dt.Rows[0]["TradeAmount"].ToString()));
                        }
                        if(PreHelpAmount > HelpAmount && PreHelpAmount > 0)
                        {
                            decimal FixedPercent = TmpEveryDayPercent()[DateTime.Now.Day];
                            if(PreHelpAmount * FixedPercent > HelpAmount)
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                }
            }
            // ====================
            decimal MaxTradeAmount = Summary.MaxAmount; //当月最大交易总额
            decimal CheckAmount = 500000 < MaxTradeAmount * 0.3M ? 500000 : MaxTradeAmount * 0.3M;
            //当月单台交易额 <= 50万或当月最大交易总额的30%（取小值），则入账
            HelpProfitMerTradeMonthSummay MonthStat = db.HelpProfitMerTradeMonthSummay.FirstOrDefault(m => m.MerchantId == MerchantId && m.TradeMonth == TradeMonth) ?? new HelpProfitMerTradeMonthSummay();
            decimal SingleTradeAmount = MonthStat.TradeAmount;
            if (SingleTradeAmount < CheckAmount)
            {
                //当月总交易额不超过当月最大交易总额，则入账
                if (Summary.TradeAmount < MaxTradeAmount)
                {
                    decimal EveryDayTradeAmount = MaxTradeAmount / function.get_Random(30, 35); //当月最大交易总额平均值
                    string conn = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
                    decimal HelpAmount = 0; //当天总交易额                    
                    DataTable dt = CustomerSqlConn.dtable("SELECT SUM(TradeAmount) TradeAmount FROM HelpProfitMerTradeSummay WHERE MerchantId IN(SELECT MerchantId FROM HelpProfitMerIds WHERE UserId=" + UserId + ") AND TradeDate='" + DateTime.Now.ToString("yyyyMMdd") + "'", conn);
                    if(dt.Rows.Count > 0)
                    {
                        HelpAmount = decimal.Parse(function.CheckNum(dt.Rows[0]["TradeAmount"].ToString()));
                    }
                    //当天总交易额不超过当月最大交易总额平均值，则入账
                    if(HelpAmount < EveryDayTradeAmount)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        //商户24个月，每月固定额度
        private Dictionary<int, decimal> EveryMonthFixedVal()
        {
            Dictionary<int, decimal> obj = new Dictionary<int, decimal>();
            obj.Add(0, 0M);
            obj.Add(1, 70000M);
            obj.Add(2, 60000M);
            obj.Add(3, 50000M);
            obj.Add(4, 40000M);
            obj.Add(5, 30000M);
            obj.Add(6, 30000M);
            obj.Add(7, 27000M);
            obj.Add(8, 25000M);
            obj.Add(9, 20000M);
            obj.Add(10, 17000M);
            obj.Add(11, 14000M);
            obj.Add(12, 14000M);
            obj.Add(13, 13000M);
            obj.Add(14, 12000M);
            obj.Add(15, 12000M);
            obj.Add(16, 10000M);
            obj.Add(17, 8000M);
            obj.Add(18, 7000M);
            obj.Add(19, 6000M);
            obj.Add(20, 5000M);
            obj.Add(21, 4000M);
            obj.Add(22, 3000M);
            obj.Add(23, 2000M);
            obj.Add(24, 1000M);
            return obj;
        }

        private Dictionary<int, decimal> TmpEveryDayPercent()
        {
            Dictionary<int, decimal> obj = new Dictionary<int, decimal>();
            obj.Add(1, 0.90M);
            obj.Add(2, 0.85M);
            obj.Add(3, 0.83M);
            obj.Add(4, 0.79M);
            obj.Add(5, 0.82M);
            obj.Add(6, 0.75M);
            obj.Add(7, 0.73M);
            obj.Add(8, 0.7M);
            obj.Add(9, 0.68M);
            obj.Add(10, 0.69M);
            obj.Add(11, 0.63M);
            obj.Add(12, 0.66M);
            obj.Add(13, 0.62M);
            obj.Add(14, 0.65M);
            obj.Add(15, 0.6M);
            obj.Add(16, 0.58M);
            obj.Add(17, 0.56M);
            obj.Add(18, 0.53M);
            obj.Add(19, 0.55M);
            obj.Add(20, 0.51M);
            obj.Add(21, 0.53M);
            obj.Add(22, 0.52M);
            obj.Add(23, 0.54M);
            obj.Add(24, 0.52M);
            obj.Add(25, 0.51M);
            obj.Add(26, 0.53M);
            obj.Add(27, 0.51M);
            obj.Add(28, 0.5M);
            return obj;
        }


        #region 每月重置最大交易总额
        public void ResetMaxTradeAmount()
        {
            Thread th = new Thread(ResetMaxTradeAmountDo);
            th.IsBackground = true;
            th.Start();
        }
        public void ResetMaxTradeAmountDo()
        {
            while (true)
            {
                if (DateTime.Now.Day == 1 && DateTime.Now.Hour > 0 && DateTime.Now.Hour < 3)
                {
                    string TradeMonth = DateTime.Now.ToString("yyyyMM");
                    ResetMaxTradeAmountGo(TradeMonth);
                }
                Thread.Sleep(30000);
            }
        }
        public void ResetMaxTradeAmountGo(string TradeMonth)
        {
            try
            {
                string CheckExist = function.ReadInstance("/HelpProfitAmountSummary/" + TradeMonth + ".txt");
                if(string.IsNullOrEmpty(CheckExist))
                {
                    function.WritePage("/HelpProfitAmountSummary/", TradeMonth + ".txt", DateTime.Now.ToString());
                    WebCMSEntities db = new WebCMSEntities();
                    string connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
                    DataTable userlist = CustomerSqlConn.dtable("select DISTINCT UserId from HelpProfitAmountSummary order by UserId", connstr);
                    // DataTable userlist = OtherMySqlConn.dtable("select DISTINCT UserId from HelpProfitAmountSummary where (TradeMonth='202209' or TradeMonth='202210') and UserId not in (select UserId from HelpProfitAmountSummary where TradeMonth='202211')");
                    foreach (DataRow user in userlist.Rows)
                    {
                        int UserId = int.Parse(user["UserId"].ToString());
                        int MonthCount = db.HelpProfitAmountSummary.Count(m => m.UserId == UserId) + 1;
                        int Month = MonthCount;
                        List<int> MerCounts = new List<int>(); //每月台数,包含当月
                        List<decimal> MaxTradeAmounts = new List<decimal>(); //每月最大固定额度
                        List<HelpProfitAmountSummary> Summarys = db.HelpProfitAmountSummary.Where(m => m.UserId == UserId && Convert.ToInt32(m.TradeMonth) <= Convert.ToInt32(TradeMonth)).OrderByDescending(m => m.TradeMonth).Take(24).ToList();
                        int MonthNum = 0;
                        foreach(HelpProfitAmountSummary Summary in Summarys)
                        {
                            MonthNum += 1;
                            MerCounts.Add(Summary.MerCount);
                            MaxTradeAmounts.Add(EveryMonthFixedVal()[MonthNum]);
                        }
                        decimal MaxTradeAmount = 0;
                        for (int i = 0; i < MerCounts.Count; i++)
                        {
                            MaxTradeAmount += MerCounts[i] * MaxTradeAmounts[i];
                        }
                        HelpProfitAmountSummary selfStat = db.HelpProfitAmountSummary.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth);
                        if(selfStat == null)
                        {
                            selfStat = db.HelpProfitAmountSummary.Add(new HelpProfitAmountSummary()
                            {
                                UserId = UserId,
                                TradeMonth = TradeMonth,
                                QueryCount = MonthCount,
                            }).Entity;
                            db.SaveChanges();
                        }
                        selfStat.MaxAmount = MaxTradeAmount;
                        // function.WriteLog("update HelpProfitAmountSummary set MaxAmount=" + MaxTradeAmount + " where UserId=" + UserId + " and TradeMonth='" + TradeMonth + "';", "重置助利宝最大交易额");
                    }
                    db.SaveChanges();
                    db.Dispose();
                }
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "每月重置最大交易总额异常");
            }
        }

        #endregion
    
    



        public void StatTradeTmp()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时执行助利宝交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    DataTable idsDt = OtherMySqlConn.dtable("select Id from TradeRecord where Id>=4150000 and CreateDate>='2022-11-27 00:00:00' and CreateDate<'2022-11-28 00:00:00' and MerchantId in (select MerchantId from HelpProfitMerIds) and SeoTitle='HelpProfit' and QueryCount=3 and MerchantId in (select MerchantId from HelpProfitMerchantForUser where UserId in (144214,144213,144170,144046,143420,143294,142953,142861,142736,142642,142608,142545,142532,142484,142297,142263,141951,141878,141838,141814,141562,141469,141295,141239,141073,140952,140816,140470,140221,140220,139917,139815,139729,139639,139094,138877,138516,138173,138021,138014,137967,137870,137706,137361,136263,136181,135950,135524,135448,135373,135251,135224,135121,134915,134503,133783,133420,132996,132839,132726,132642,132488,132469,132234,131903,131845,131025,130767,130744,130334,130113,129947,129814,129111,128853,128758,128640,128513,128322,127634,127188,126802,126782,126620,126613,125981,125848,125778,125754,124875,124822,124344,123770,123747,123115,122986,121779,121749,121570,121404,121108,120998,120957,120776,120720,120663,120650,120604,110031,109906,109405,106581,105286,100934,99148,93049,91467,88519,88494,84401,80747,72018,69881,69195,68888,64167,63784,62252,60846,60561,60035,59740,59159,57366,56869,56182,56080,55049,54784,54517,52449,52265,51193,50886,49838,49145,48849,46655,46284,45892,41420,41200,40498,40282,40280,39109,38520,37033,36932,36488,35805,33055,32534,27524,24528,21108,18724,15600,15509,15506,11124,9367,7601,7487,6764,6267,4861,3885,3835,3015,1893,1797,1703,1195,1052,668,609,602,599,598,588,586,583,582,565,560,558,514,415,392,391,389,387,281,276,237,45,1))");
                    if (idsDt.Rows.Count > 0)
                    {
                        string ids = "";
                        foreach (DataRow idsDr in idsDt.Rows)
                        {
                            ids += idsDr["Id"].ToString() + ",";
                        }
                        DataTable selfDt = OtherMySqlConn.dtable("select MerchantId,DATE_FORMAT(CreateDate,'%Y%m%d'),sum(TradeAmount) from TradeRecord where Id in (" + ids.TrimEnd(',') + ") group by MerchantId,DATE_FORMAT(CreateDate,'%Y%m%d')");
                        if (selfDt.Rows.Count > 0)
                        {
                            function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "实时执行助利宝交易额日志");
                            foreach (DataRow selfDr in selfDt.Rows)
                            {
                                int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                                string TradeDate = selfDr[1].ToString();
                                string TradeMonth = TradeDate.Substring(0, 6);
                                decimal TradeAmount = decimal.Parse(selfDr[2].ToString());
                                HelpProfitMerIds merIds = db.HelpProfitMerIds.FirstOrDefault(m => m.MerchantId == MerchantId) ?? new HelpProfitMerIds();
                                bool Check = CheckAmount(db, MerchantId, merIds.UserId, TradeMonth);
                                if (Check)
                                {
                                    HelpProfitMerTradeSummay selfStat = db.HelpProfitMerTradeSummay.FirstOrDefault(m => m.MerchantId == MerchantId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate);
                                    if (selfStat == null)
                                    {
                                        selfStat = db.HelpProfitMerTradeSummay.Add(new HelpProfitMerTradeSummay()
                                        {
                                            TradeMonth = TradeMonth,
                                            TradeDate = TradeDate,
                                            MerchantId = MerchantId,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    decimal MoreAmount = TradeAmount * 0.01M;
                                    MoreAmount = decimal.Parse(function.CheckInt(MoreAmount.ToString().Split(".")[0]));
                                    selfStat.TradeAmount = TradeAmount + MoreAmount;
                                }
                            }
                        }
                        db.SaveChanges();
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时执行助利宝交易额异常");
                }
            }
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "实时执行助利宝交易额日志");
        }
    
    }
}