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

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



        
        // 统计交易额到RDS
        public void StartStat()
        {
            Thread th = new Thread(StartStatDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartStatDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ProfitTradeAmountQueue");
                if(!string.IsNullOrEmpty(content))
                {
                    StatTradeAmount(content);
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }
        public void StatTradeAmount(string content)
        {
            WebCMSEntities db = new WebCMSEntities();
            PxcModels.WebCMSEntities maindb = new PxcModels.WebCMSEntities();
            try
            {
                JsonData selfDr = JsonMapper.ToObject(content);
                int UserId = int.Parse(selfDr["UserId"].ToString());
                PxcModels.Users user = maindb.Users.FirstOrDefault(m => m.Id == UserId) ?? new PxcModels.Users();
                string ParentNav = user.ParentNav;
                int BrandId = int.Parse(selfDr["BrandId"].ToString());
                int BankCardType = int.Parse(selfDr["BankCardType"].ToString());
                int QrPayFlag = int.Parse(selfDr["QrPayFlag"].ToString());
                int MerHelpFlag = int.Parse(selfDr["MerHelpFlag"].ToString());
                int Version = int.Parse(selfDr["Version"].ToString());
                int CapFlag = int.Parse(selfDr["CapFlag"].ToString());
                int VipFlag = int.Parse(selfDr["VipFlag"].ToString());
                int PayType = int.Parse(selfDr["PayType"].ToString());
                string TradeDate = selfDr["TradeDate"].ToString();
                decimal TradeAmount = decimal.Parse(selfDr["TradeAmount"].ToString());
                int TradeCount = int.Parse(selfDr["TradeCount"].ToString());
                string TradeMonth = TradeDate.Substring(0, 6);

                TradeDaySummary selfStat = db.TradeDaySummary.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType && m.SeoTitle == "self");
                if (selfStat == null)
                {
                    selfStat = db.TradeDaySummary.Add(new TradeDaySummary()
                    {
                        UserId = UserId,
                        TradeMonth = TradeMonth,
                        TradeDate = TradeDate,
                        BrandId = BrandId,
                        QueryCount = QrPayFlag,
                        VipFlag = VipFlag,
                        PayType = PayType,
                        SeoTitle = "self",
                    }).Entity;
                    db.SaveChanges();
                }
                if (BankCardType == 0)
                {
                    if (Version == 1)
                    {
                        selfStat.ProfitDirectDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat.ProfitDirectDebitCapTradeAmt += TradeAmount;
                            selfStat.ProfitDirectDebitCapNum += TradeCount;
                        }
                    }
                    else if (MerHelpFlag == 1)
                    {
                        selfStat.HelpDirectDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat.HelpDirectDebitCapTradeAmt += TradeAmount;
                            selfStat.HelpDirectDebitCapNum += TradeCount;
                        }
                    }
                    else
                    {
                        selfStat.NotHelpDirectDebitTradeAmt += TradeAmount;
                        if (CapFlag == 1)
                        {
                            selfStat.NotHelpDirectDebitCapTradeAmt += TradeAmount;
                            selfStat.NotHelpDirectDebitCapNum += TradeCount;
                        }
                    }
                }
                else if (BankCardType != 0)
                {
                    if (Version == 1)
                    {
                        selfStat.ProfitDirectTradeAmt += TradeAmount;
                    }
                    else if (MerHelpFlag == 1)
                    {
                        selfStat.HelpDirectTradeAmt += TradeAmount;
                    }
                    else
                    {
                        selfStat.NotHelpDirectTradeAmt += TradeAmount;
                    }
                }
                ParentNav += "," + UserId + ",";
                if (!string.IsNullOrEmpty(ParentNav))
                {
                    string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    foreach (string NavUserIdString in ParentNavList)
                    {
                        int NavUserId = int.Parse(NavUserIdString);
                        TradeDaySummary teamStat = db.TradeDaySummary.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType && m.SeoTitle == "team");
                        if (teamStat == null)
                        {
                            teamStat = db.TradeDaySummary.Add(new TradeDaySummary()
                            {
                                UserId = NavUserId,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                BrandId = BrandId,
                                QueryCount = QrPayFlag,
                                VipFlag = VipFlag,
                                PayType = PayType,
                                SeoTitle = "team",
                            }).Entity;
                            db.SaveChanges();
                        }
                        if (BankCardType == 0)
                        {
                            if (Version == 1)
                            {
                                teamStat.ProfitNonDirectDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat.ProfitDirectDebitCapTradeAmt += TradeAmount;
                                    teamStat.ProfitDirectDebitCapNum += TradeCount;
                                }
                            }
                            else if (MerHelpFlag == 1)
                            {
                                teamStat.HelpNonDirectDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat.HelpDirectDebitCapTradeAmt += TradeAmount;
                                    teamStat.HelpDirectDebitCapNum += TradeCount;
                                }
                            }
                            else
                            {
                                teamStat.NotHelpNonDirectDebitTradeAmt += TradeAmount;
                                if (CapFlag == 1)
                                {
                                    teamStat.NotHelpDirectDebitCapTradeAmt += TradeAmount;
                                    teamStat.NotHelpDirectDebitCapNum += TradeCount;
                                }
                            }
                        }
                        else if (BankCardType != 0)
                        {
                            if (Version == 1)
                            {
                                teamStat.ProfitNonDirectTradeAmt += TradeAmount;
                            }
                            else if (MerHelpFlag == 1)
                            {
                                teamStat.HelpNonDirectTradeAmt += TradeAmount;
                            }
                            else
                            {
                                teamStat.NotHelpNonDirectTradeAmt += TradeAmount;
                            }
                        }
                    }
                }
                
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时统计交易额日志RDSnew异常");
            }
            maindb.Dispose();
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "实时统计交易额日志RDSnew");
        }




        public void AddRds()
        {
            // AddTradeDaySummary(); //补TradeDaySummary数据
            // AddUserAccountRecord(); //补UserAccountRecord数据
            // AddProfitRecord(); //补ProfitRecord数据
            // AddSubsidyRecord(); //补SubsidyRecord数据

            AddRdsData("TradeRecord");
            AddRdsData("PosMerchantTradeSummay");
            AddRdsData("UserAccountRecord");
            AddRdsData("ProfitRecord");
            AddRdsData("SubsidyRecord");
            AddRdsData("StoreChangeHistory");
            AddRdsData("StoreStockChange");
            AddRdsData("MsgPlacardRead");
            AddRdsData("UserTradeMonthSummary");
            // AddRdsData("ProfitRewardRecord");
            AddRdsData("HelpProfitMerTradeSummay");
            // AddRdsData("MsgPersonal");
            AddRdsData("OpenReward");
            AddRdsData("OpenRewardDetail");
            AddRdsData("UserStoreChange");
            // AddRdsData("ProfitRewardExport");
            AddRdsData("ActiveReward");
            AddRdsData("RecommendTradeSummary");
            AddRdsData("StoreHouseAmountRecord");
            // AddRdsData("ProfitSubsidyDetail");
            // AddRdsData("ProfitSubsidyExport");
            AddRdsData("FluxProfitDetail");
        }

        public void AddRdsData(string TableName)
        {
            Thread th = new Thread(AddRdsDataDo);
            th.IsBackground = true;
            th.Start(TableName);
        }
        public void AddRdsDataDo(object sender)
        {
            string TableName = sender.ToString();
            while (true)
            {
                if(RedisDbconn.Instance.Get<string>("RdsThreadStatus") == "1")
                {
                    RdsDataDo(TableName);
                    Thread.Sleep(500);
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }
        public void RdsDataDo(string TableName)
        {
            try
            {
                string condition = "";
                if(TableName == "PosMerchantTradeSummay") condition += " and Id<=14473274";
                if(TableName == "UserTradeMonthSummary") condition += " and Id<=1132650";
                if(TableName == "HelpProfitMerTradeSummay") condition += " and Id<=473971";
                if(TableName == "RecommendTradeSummary") condition += " and Id<=236748";
                string sql = "";
                int startId = int.Parse(function.CheckInt(function.ReadInstance("/TradeRecord/" + TableName + "Id.txt")));
                DataTable dt = CustomerSqlConn.dtable("select * from " + TableName + " where Id>" + startId + condition + " order by Id limit 100", AppConfig.Base.SqlConn);
                if(dt.Rows.Count > 0)
                {
                    foreach(DataRow dr in dt.Rows)
                    {
                        string fields = "";
                        string vals = "";
                        foreach(DataColumn dc in dt.Columns)
                        {
                            fields += dc.ColumnName + ",";
                            if(dc.DataType == typeof(DateTime))
                            {
                                string val = dr[dc.ColumnName].ToString();
                                if(string.IsNullOrEmpty(val))
                                {
                                    val = "NULL";
                                }
                                else
                                {
                                    val = "'" + DateTime.Parse(val).ToString("yyyy-MM-dd HH:mm:ss") + "'";
                                }
                                vals += val + ",";
                            }
                            else if(dc.DataType == typeof(int) || dc.DataType == typeof(decimal) || dc.DataType == typeof(ulong))
                            {
                                vals += dr[dc.ColumnName].ToString() + ",";
                            }
                            else
                            {
                                vals += "'" + dr[dc.ColumnName].ToString() + "',";
                            }
                        }
                        sql += "insert into " + TableName + " (" + fields.TrimEnd(',') + ") values (" + vals.TrimEnd(',') + ");\n";
                        startId = int.Parse(function.CheckInt(dr["Id"].ToString()));
                    }
                    CustomerSqlConn.op(sql, AppConfig.Base.ProfitSqlConn);
                    function.WritePage("/TradeRecord/", TableName + "Id.txt", startId.ToString());   
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "补" + TableName + "数据异常");
            }
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "补" + TableName + "数据");
        }



        // 补TradeDaySummary数据
        public void AddTradeDaySummary()
        {
            Thread th = new Thread(AddTradeDaySummaryDo);
            th.IsBackground = true;
            th.Start();
        }
        public void AddTradeDaySummaryDo()
        {
            while (true)
            {
                if(RedisDbconn.Instance.Get<string>("TradeDaySummaryThreadStatus") == "1")
                {
                    TradeDaySummaryDo();
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }
        }
        public void TradeDaySummaryDo()
        {
            WebCMSEntities db = new WebCMSEntities();
            PxcModels.WebCMSEntities maindb = new PxcModels.WebCMSEntities();
            try
            {
                int startId = int.Parse(function.CheckInt(function.ReadInstance("/TradeRecord/TradeDaySummaryId.txt")));
                List<PxcModels.TradeDaySummary> list = maindb.TradeDaySummary.Where(m => m.Id > startId && m.Id <= 13509689).OrderBy(m => m.Id).Take(100).ToList();
                foreach(PxcModels.TradeDaySummary sub in list)
                {
                    db.TradeDaySummary.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<TradeDaySummary>(Newtonsoft.Json.JsonConvert.SerializeObject(sub)));
                    startId = sub.Id;
                }
                function.WritePage("/TradeRecord/", "TradeDaySummaryId.txt", startId.ToString());                
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "补TradeDaySummary数据异常");
            }
            maindb.Dispose();
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "补TradeDaySummary数据");
        }


        // 同步UserAccountRecord数据
        public void AddUserAccountRecord()
        {
            Thread th = new Thread(AddUserAccountRecordDo);
            th.IsBackground = true;
            th.Start();
        }
        public void AddUserAccountRecordDo()
        {
            while (true)
            {
                if(RedisDbconn.Instance.Get<string>("UserAccountRecordThreadStatus") == "1")
                {
                    UserAccountRecordDo();
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }
        }
        public void UserAccountRecordDo()
        {
            WebCMSEntities db = new WebCMSEntities();
            PxcModels.WebCMSEntities maindb = new PxcModels.WebCMSEntities();
            try
            {
                int startId = int.Parse(function.CheckInt(function.ReadInstance("/TradeRecord/UserAccountRecordId.txt")));
                List<PxcModels.UserAccountRecord> list = maindb.UserAccountRecord.Where(m => m.Id > startId).OrderBy(m => m.Id).Take(100).ToList();
                foreach(PxcModels.UserAccountRecord sub in list)
                {
                    db.UserAccountRecord.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<UserAccountRecord>(Newtonsoft.Json.JsonConvert.SerializeObject(sub)));
                    startId = sub.Id;
                }
                function.WritePage("/TradeRecord/", "UserAccountRecordId.txt", startId.ToString());                
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "补UserAccountRecord数据异常");
            }
            maindb.Dispose();
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "补UserAccountRecord数据");
        }


        // 同步ProfitRecord数据
        public void AddProfitRecord()
        {
            Thread th = new Thread(AddProfitRecordDo);
            th.IsBackground = true;
            th.Start();
        }
        public void AddProfitRecordDo()
        {
            while (true)
            {
                if(RedisDbconn.Instance.Get<string>("ProfitRecordThreadStatus") == "1")
                {
                    ProfitRecordDo();
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }
        }
        public void ProfitRecordDo()
        {
            WebCMSEntities db = new WebCMSEntities();
            PxcModels.WebCMSEntities maindb = new PxcModels.WebCMSEntities();
            try
            {
                int startId = int.Parse(function.CheckInt(function.ReadInstance("/TradeRecord/ProfitRecordId.txt")));
                List<PxcModels.ProfitRecord> list = maindb.ProfitRecord.Where(m => m.Id > startId).OrderBy(m => m.Id).Take(100).ToList();
                foreach(PxcModels.ProfitRecord sub in list)
                {
                    db.ProfitRecord.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<ProfitRecord>(Newtonsoft.Json.JsonConvert.SerializeObject(sub)));
                    startId = sub.Id;
                }
                function.WritePage("/TradeRecord/", "ProfitRecordId.txt", startId.ToString());                
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "补ProfitRecord数据异常");
            }
            maindb.Dispose();
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "补ProfitRecord数据");
        }


        // 同步SubsidyRecord数据
        public void AddSubsidyRecord()
        {
            Thread th = new Thread(AddSubsidyRecordDo);
            th.IsBackground = true;
            th.Start();
        }
        public void AddSubsidyRecordDo()
        {
            while (true)
            {
                if(RedisDbconn.Instance.Get<string>("SubsidyRecordThreadStatus") == "1")
                {
                    SubsidyRecordDo();
                }
                else
                {
                    Thread.Sleep(1000);
                }
            }
        }
        public void SubsidyRecordDo()
        {
            WebCMSEntities db = new WebCMSEntities();
            PxcModels.WebCMSEntities maindb = new PxcModels.WebCMSEntities();
            try
            {
                int startId = int.Parse(function.CheckInt(function.ReadInstance("/TradeRecord/SubsidyRecordId.txt")));
                List<PxcModels.SubsidyRecord> list = maindb.SubsidyRecord.Where(m => m.Id > startId).OrderBy(m => m.Id).Take(100).ToList();
                foreach(PxcModels.SubsidyRecord sub in list)
                {
                    db.SubsidyRecord.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<SubsidyRecord>(Newtonsoft.Json.JsonConvert.SerializeObject(sub)));
                    startId = sub.Id;
                }
                function.WritePage("/TradeRecord/", "SubsidyRecordId.txt", startId.ToString());                
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "补SubsidyRecord数据异常");
            }
            maindb.Dispose();
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "补SubsidyRecord数据");
        }
    }
}