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 StatResetService
    {
        public readonly static StatResetService Instance = new StatResetService();
        private StatResetService()
        { }


        public void StartReset()
        {
            Thread th = new Thread(StartResetMerchantDo);
            th.IsBackground = true;
            th.Start();
            
            Thread thUser = new Thread(StartResetUserSelfDo);
            thUser.IsBackground = true;
            thUser.Start();
            
            Thread thUserTeam = new Thread(StartResetUserTeamDo);
            thUserTeam.IsBackground = true;
            thUserTeam.Start();

            Thread thSn = new Thread(StartResetSnDo);
            thSn.IsBackground = true;
            thSn.Start();
        }
        public void StartResetMerchantDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ResetMerchantStatDataQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    StatResetMerchantAmount(content);
                }
                Thread.Sleep(10000);
            }
        }
        public void StatResetMerchantAmount(string content)
        {
            JsonData jsonObj = JsonMapper.ToObject(content);
            string merchantId = jsonObj["MerchantId"].ToString();
            string startDate = jsonObj["StartDate"].ToString();
            string endDate = jsonObj["EndDate"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "重置商户交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            string conn = Library.ConfigurationManager.AppSettings["StatSqlConnStr"].ToString();
            KxsMainModels.WebCMSEntities maindb = new KxsMainModels.WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    DataTable selfDt = CustomerSqlConn.dtable("select MerchantId,PayMode,IsAct,DATE_FORMAT(CreateDate,'%Y%m%d'),sum(PayMoney),count(Id),sum(MerchantActualAmount) from ConsumerOrders where MerchantId=" + merchantId + " and CreateDate>='" + startDate.Substring(0, 4) + "-" + startDate.Substring(4, 2) + "-" + startDate.Substring(6, 2) + " 00:00:00' and CreateDate<='" + endDate.Substring(0, 4) + "-" + endDate.Substring(4, 2) + "-" + endDate.Substring(6, 2) + " 23:59:59' group by MerchantId,PayMode,IsAct,DATE_FORMAT(CreateDate,'%Y%m%d')", AppConfig.Base.SqlConn);
                    if (selfDt.Rows.Count > 0)
                    {
                        function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "重置商户交易额日志");
                        var ResetDate = "";
                        bool check = false; //重置统计表数据开关
                        decimal NonActAmounts = 0;
                        decimal ActAmounts = 0;
                        decimal AliPayInFactAmounts = 0;
                        decimal WeChatInfactAmounts = 0;
                        int OderCounts = 0;
                        decimal InFactAmounts = 0;
                        decimal TradeAmounts = 0;
                        foreach (DataRow selfDr in selfDt.Rows)
                        {
                            int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                            int PayMode = int.Parse(selfDr["PayMode"].ToString());
                            int IsAct = int.Parse(selfDr["IsAct"].ToString());
                            string TradeDate = selfDr[3].ToString();
                            decimal TradeAmount = decimal.Parse(selfDr[4].ToString());
                            int TradeCount = int.Parse(selfDr[5].ToString());
                            decimal ActualAmount = decimal.Parse(selfDr[6].ToString());
                            string TradeMonth = TradeDate.Substring(0, 6);

                            //商户交易额
                            MerchantAmountSummay merchantStat = db.MerchantAmountSummay.FirstOrDefault(m => m.MerchantId == MerchantId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode);
                            if (merchantStat == null)
                            {
                                merchantStat = db.MerchantAmountSummay.Add(new MerchantAmountSummay()
                                {
                                    MerchantId = MerchantId,
                                    TradeMonth = TradeMonth,
                                    TradeDate = TradeDate,
                                    PayMode = PayMode,
                                    IsAct = IsAct,
                                }).Entity;
                                db.SaveChanges();
                            }
                            var LastDate = ResetDate; //上次重置时间
                            if (ResetDate == "")
                            {
                                LastDate = TradeDate;
                            }
                            ResetDate = TradeDate; //覆盖重置时间
                            if (LastDate == TradeDate)
                            {
                                OderCounts += TradeCount;
                                TradeAmounts += TradeAmount;
                                if (IsAct == 0) NonActAmounts += TradeAmount;
                                if (IsAct == 1) ActAmounts += TradeAmount;
                                if (PayMode == 1) AliPayInFactAmounts += ActualAmount;
                                if (PayMode == 2) WeChatInfactAmounts += ActualAmount;
                                if (IsAct == 1) InFactAmounts += TradeAmount;
                                if (selfDt.Rows.Count == 1)
                                {
                                    CustomerSqlConn.op("UPDATE MerchantTradeSummary" + LastDate + " SET NonActAmount=" + NonActAmounts + ",ActAmount=" + ActAmounts + ",AliPayInFactAmount=" + AliPayInFactAmounts + ",WeChatInfactAmount=" + WeChatInfactAmounts + ",OderCount=" + OderCounts + ",InFactAmount=" + InFactAmounts + ",TradeAmount=" + TradeAmounts + " WHERE MerchantId=" + MerchantId + "", conn);
                                    CustomerSqlConn.op("UPDATE MerchantTradeSummaryList" + TradeMonth + " SET NonActAmount=" + NonActAmounts + ",ActAmount=" + ActAmounts + ",AliPayInFactAmount=" + AliPayInFactAmounts + ",WeChatInfactAmount=" + WeChatInfactAmounts + ",OderCount=" + OderCounts + ",InFactAmount=" + InFactAmounts + ",TradeAmount=" + TradeAmounts + " WHERE MerchantId=" + MerchantId + " AND TradeDate='" + LastDate + "'", conn);
                                }
                            }
                            else
                            {
                                check = true;
                                if (check)
                                {
                                    if (check)
                                    {
                                        CustomerSqlConn.op("UPDATE MerchantTradeSummary" + LastDate + " SET NonActAmount=" + NonActAmounts + ",ActAmount=" + ActAmounts + ",AliPayInFactAmount=" + AliPayInFactAmounts + ",WeChatInfactAmount=" + WeChatInfactAmounts + ",OderCount=" + OderCounts + ",InFactAmount=" + InFactAmounts + ",TradeAmount=" + TradeAmounts + " WHERE MerchantId=" + MerchantId + "", conn);
                                        CustomerSqlConn.op("UPDATE MerchantTradeSummaryList" + TradeMonth + " SET NonActAmount=" + NonActAmounts + ",ActAmount=" + ActAmounts + ",AliPayInFactAmount=" + AliPayInFactAmounts + ",WeChatInfactAmount=" + WeChatInfactAmounts + ",OderCount=" + OderCounts + ",InFactAmount=" + InFactAmounts + ",TradeAmount=" + TradeAmounts + " WHERE MerchantId=" + MerchantId + " AND TradeDate='" + LastDate + "'", conn);
                                        check = false;
                                    }
                                }
                                if (check == false)
                                {
                                    OderCounts = TradeCount;
                                    TradeAmounts = TradeAmount;
                                    if (IsAct == 0) NonActAmounts = TradeAmount;
                                    if (IsAct == 1) ActAmounts = TradeAmount;
                                    if (PayMode == 1) AliPayInFactAmounts = ActualAmount;
                                    if (PayMode == 2) WeChatInfactAmounts = ActualAmount;
                                    if (IsAct == 1) InFactAmounts = TradeAmount;
                                }
                            }
                            merchantStat.TradeAmount = TradeAmount;
                            merchantStat.TradeCount = TradeCount;
                            merchantStat.TotalActual = ActualAmount;
                            db.SaveChanges();
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "重置商户交易额异常");
                }
            }
            db.Dispose();
            maindb.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "重置商户交易额日志");
        }

        public void StartResetSnDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ResetSnStatDataQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    StatResetSnAmount(content);
                }
                Thread.Sleep(10000);
            }
        }
        public void StatResetSnAmount(string content)
        {
            JsonData jsonObj = JsonMapper.ToObject(content);
            string snNo = jsonObj["SnNo"].ToString();
            string startDate = jsonObj["StartDate"].ToString();
            string endDate = jsonObj["EndDate"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "重置码牌交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            KxsMainModels.WebCMSEntities maindb = new KxsMainModels.WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    DataTable selfDt = CustomerSqlConn.dtable("select SnNo,PayMode,IsAct,DATE_FORMAT(CreateDate,'%Y%m%d'),sum(PayMoney),count(Id),sum(MerchantActualAmount) from ConsumerOrders where SnNo=" + snNo + " and CreateDate>='" + startDate.Substring(0, 4) + "-" + startDate.Substring(4, 2) + "-" + startDate.Substring(6, 2) + " 00:00:00' and CreateDate<='" + endDate.Substring(0, 4) + "-" + endDate.Substring(4, 2) + "-" + endDate.Substring(6, 2) + " 23:59:59' group by SnNo,PayMode,IsAct,DATE_FORMAT(CreateDate,'%Y%m%d')", AppConfig.Base.SqlConn);
                    if (selfDt.Rows.Count > 0)
                    {
                        function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "重置码牌交易额日志");
                        foreach (DataRow selfDr in selfDt.Rows)
                        {
                            int PayMode = int.Parse(selfDr["PayMode"].ToString());
                            int IsAct = int.Parse(selfDr["IsAct"].ToString());
                            string SnNo = selfDr["SnNo"].ToString();
                            string TradeDate = selfDr[3].ToString();
                            decimal TradeAmount = decimal.Parse(selfDr[4].ToString());
                            int TradeCount = int.Parse(selfDr[5].ToString());
                            decimal ActualAmount = decimal.Parse(selfDr[6].ToString());
                            string TradeMonth = TradeDate.Substring(0, 6);

                            //码牌交易额
                            QrCodeAmountSummay qrcode = db.QrCodeAmountSummay.FirstOrDefault(m => m.SnNo == SnNo && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode);
                            if (qrcode == null)
                            {
                                qrcode = db.QrCodeAmountSummay.Add(new QrCodeAmountSummay()
                                {
                                    SnNo = SnNo,
                                    TradeMonth = TradeMonth,
                                    TradeDate = TradeDate,
                                    PayMode = PayMode,
                                    IsAct = IsAct,
                                }).Entity;
                                db.SaveChanges();
                            }
                            qrcode.TradeAmount += TradeAmount;
                            qrcode.TradeCount += TradeCount;
                            qrcode.TotalActual += ActualAmount;
                            db.SaveChanges();
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "重置码牌交易额异常");
                }
            }
            db.Dispose();
            maindb.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "重置码牌交易额日志");
        }

        public void StartResetUserSelfDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ResetUserSelfStatDataQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    StatResetUserSelfAmount(content);
                }
                Thread.Sleep(10000);
            }
        }
        public void StatResetUserSelfAmount(string content)
        {
            JsonData jsonObj = JsonMapper.ToObject(content);
            string userId = jsonObj["UserId"].ToString();
            string startDate = jsonObj["StartDate"].ToString();
            string endDate = jsonObj["EndDate"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "重置创客个人交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            KxsMainModels.WebCMSEntities maindb = new KxsMainModels.WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    DataTable selfDt = CustomerSqlConn.dtable("select UserId,PayMode,IsAct,DATE_FORMAT(CreateDate,'%Y%m%d'),sum(PayMoney),count(Id) from ConsumerOrders where UserId=" + userId + " and CreateDate>='" + startDate.Substring(0, 4) + "-" + startDate.Substring(4, 2) + "-" + startDate.Substring(6, 2) + " 00:00:00' and CreateDate<='" + endDate.Substring(0, 4) + "-" + endDate.Substring(4, 2) + "-" + endDate.Substring(6, 2) + " 23:59:59' group by UserId,PayMode,IsAct,DATE_FORMAT(CreateDate,'%Y%m%d')", AppConfig.Base.SqlConn);
                    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());
                            KxsMainModels.Users user = maindb.Users.FirstOrDefault(m => m.Id == UserId) ?? new KxsMainModels.Users();
                            int PayMode = int.Parse(selfDr["PayMode"].ToString());
                            int IsAct = int.Parse(selfDr["IsAct"].ToString());
                            string TradeDate = selfDr[3].ToString();
                            decimal TradeAmount = decimal.Parse(selfDr[4].ToString());
                            int TradeCount = int.Parse(selfDr[5].ToString());
                            string TradeMonth = TradeDate.Substring(0, 6);

                            //创客交易额
                            UserAmountSummary selfStat = db.UserAmountSummary.FirstOrDefault(m => m.UserId == UserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "self");
                            if (selfStat == null)
                            {
                                selfStat = db.UserAmountSummary.Add(new UserAmountSummary()
                                {
                                    UserId = UserId,
                                    TradeMonth = TradeMonth,
                                    TradeDate = TradeDate,
                                    PayMode = PayMode,
                                    IsAct = IsAct,
                                    SeoTitle = "self",
                                }).Entity;
                                db.SaveChanges();
                            }
                            selfStat.TotalAmount = TradeAmount;
                            selfStat.TradeCount = TradeCount;
                            db.SaveChanges();

                            string ParentNav = user.ParentNav + "," + userId + ",";
                            if(!string.IsNullOrEmpty(ParentNav))
                            {
                                string[] ParentNavList = ParentNav.Replace(",,", ",").Trim(',').Split(',');
                                foreach(string id in ParentNavList)
                                {
                                    string reqdata = "{\"UserId\":\"" + id + "\",\"StartDate\":\"" + startDate + "\",\"EndDate\":\"" + endDate + "\"}";
                                    RedisDbconn.Instance.AddList("ResetUserTeamStatDataQueue", reqdata);
                                }
                            }
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "重置创客个人交易额异常");
                }
            }
            db.Dispose();
            maindb.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "重置创客个人交易额日志");
        }

        public void StartResetUserTeamDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ResetUserTeamStatDataQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    StatResetUserTeamAmount(content);
                }
                Thread.Sleep(10000);
            }
        }
        public void StatResetUserTeamAmount(string content)
        {
            JsonData jsonObj = JsonMapper.ToObject(content);
            int userId = int.Parse(jsonObj["UserId"].ToString());
            string startDate = jsonObj["StartDate"].ToString();
            string endDate = jsonObj["EndDate"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "重置团队创客交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            KxsMainModels.WebCMSEntities maindb = new KxsMainModels.WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    string subUserId = "0";
                    var subusers = maindb.Users.Select(m => new { m.Id, m.ParentUserId }).Where(m => m.ParentUserId == userId).ToList();
                    foreach(var subuser in subusers)
                    {
                        subUserId += "," + subuser.Id;
                    }
                    DataTable selfDt = CustomerSqlConn.dtable("select PayMode,TotalAmount,TradeMonth,TradeDate,UserId,TradeCount,IsAct from UserAmountSummary where UserId in (" + subUserId + ") and TradeDate>='" + startDate + "' and TradeDate<='" + endDate + "' and SeoTitle='team'", AppConfig.Base.SqlConn);
                    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());
                            int PayMode = int.Parse(selfDr["PayMode"].ToString());
                            int IsAct = int.Parse(selfDr["IsAct"].ToString());
                            string TradeDate = selfDr["TradeDate"].ToString();
                            decimal TradeAmount = decimal.Parse(selfDr["TotalAmount"].ToString());
                            int TradeCount = int.Parse(selfDr["TradeCount"].ToString());
                            string TradeMonth = selfDr["TradeMonth"].ToString();

                            //创客交易额
                            UserAmountSummary teamStat = db.UserAmountSummary.FirstOrDefault(m => m.UserId == UserId && m.IsAct == IsAct && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.PayMode == PayMode && m.SeoTitle == "Team");
                            if (teamStat == null)
                            {
                                teamStat = db.UserAmountSummary.Add(new UserAmountSummary()
                                {
                                    UserId = UserId,
                                    TradeMonth = TradeMonth,
                                    TradeDate = TradeDate,
                                    PayMode = PayMode,
                                    IsAct = IsAct,
                                    SeoTitle = "self",
                                }).Entity;
                                db.SaveChanges();
                            }
                            teamStat.TotalAmount = TradeAmount;
                            teamStat.TradeCount = TradeCount;
                            db.SaveChanges();
                        }
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "重置团队创客交易额异常");
                }
            }
            db.Dispose();
            maindb.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "重置团队创客交易额日志");
        }
    }
}