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






        // 统计交易额V2
        public void Start()
        {
            Thread th = new Thread(StartDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartDo()
        {
            while (true)
            {
                StatTradeAmount();
                Thread.Sleep(200);
            }
        }
        public void StatTradeAmount()
        {
            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/TmpId.txt");
                    if(string.IsNullOrEmpty(startId))
                    {
                        startId = "18503140";
                    }
                    string sql = "select Id from TradeRecord where Id>=" + startId + " and Id>=18503140 and Id<=18669881 and ActStatus=1 and BrandId!=14 order by Id limit 500";
                    DataTable idsDt = CustomerSqlConn.dtable(sql, AppConfig.Base.TmpReadSqlConn);
                    if(idsDt.Rows.Count > 0)
                    {
                        string ids = "";
                        foreach (DataRow idsDr in idsDt.Rows)
                        {
                            ids += idsDr["Id"].ToString() + ",";
                            startId = idsDr["Id"].ToString();
                        }
                        DataTable selfDt = CustomerSqlConn.dtable("select UserId,ParentNav,BrandId,BankCardType,QrPayFlag,MerHelpFlag,Version,CapFlag,VipFlag,PayType,DATE_FORMAT(CreateDate,'%Y%m%d'),sum(TradeAmount),count(Id),SnNo from TradeRecord where Id in (" + ids.TrimEnd(',') + ") group by UserId,ParentNav,BrandId,BankCardType,QrPayFlag,MerHelpFlag,Version,CapFlag,VipFlag,PayType,DATE_FORMAT(CreateDate,'%Y%m%d'),SnNo", AppConfig.Base.TmpReadSqlConn);
                        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 SnNo = selfDr["SnNo"].ToString();
                                if(UserId == 0)
                                {
                                    PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == SnNo);
                                    if(pos != null)
                                    {
                                        UserId = pos.UserId;
                                    }
                                }
                                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                                string ParentNav = user.ParentNav; //selfDr["ParentNav"].ToString();
                                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[10].ToString();
                                decimal TradeAmount = decimal.Parse(selfDr[11].ToString());
                                int TradeCount = int.Parse(selfDr[12].ToString());
                                string TradeMonth = TradeDate.Substring(0, 6);

                                if(Version < 2)
                                {
                                    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;
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //盈利期，费率0.6
                                    TradeDaySummary2 selfStat2 = db.TradeDaySummary2.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 (selfStat2 == null)
                                    {
                                        selfStat2 = db.TradeDaySummary2.Add(new TradeDaySummary2()
                                        {
                                            UserId = UserId,
                                            TradeMonth = TradeMonth,
                                            TradeDate = TradeDate,
                                            BrandId = BrandId,
                                            QueryCount = QrPayFlag,
                                            VipFlag = VipFlag,
                                            PayType = PayType,
                                            SeoTitle = "self",
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    if (BankCardType == 0)
                                    {
                                        if (Version == 2)
                                        {
                                            selfStat2.ProfitDebitTradeAmt += TradeAmount;
                                            if (CapFlag == 1)
                                            {
                                                selfStat2.ProfitDebitCapTradeAmt += TradeAmount;
                                                selfStat2.ProfitDebitCapNum += TradeCount;
                                            }
                                        }
                                    }
                                    else if (BankCardType != 0)
                                    {
                                        if (Version == 2)
                                        {
                                            selfStat2.ProfitTradeAmt += TradeAmount;
                                        }
                                    }
                                    ParentNav += "," + UserId + ",";
                                    if (!string.IsNullOrEmpty(ParentNav))
                                    {
                                        string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                        foreach (string NavUserIdString in ParentNavList)
                                        {
                                            int NavUserId = int.Parse(NavUserIdString);
                                            TradeDaySummary2 teamStat2 = db.TradeDaySummary2.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 (teamStat2 == null)
                                            {
                                                teamStat2 = db.TradeDaySummary2.Add(new TradeDaySummary2()
                                                {
                                                    UserId = NavUserId,
                                                    TradeMonth = TradeMonth,
                                                    TradeDate = TradeDate,
                                                    BrandId = BrandId,
                                                    QueryCount = QrPayFlag,
                                                    VipFlag = VipFlag,
                                                    PayType = PayType,
                                                    SeoTitle = "team",
                                                }).Entity;
                                                db.SaveChanges();
                                            }
                                            if (BankCardType == 0)
                                            {
                                                if (Version == 2)
                                                {
                                                    teamStat2.ProfitDebitTradeAmt += TradeAmount;
                                                    if (CapFlag == 1)
                                                    {
                                                        teamStat2.ProfitDebitCapTradeAmt += TradeAmount;
                                                        teamStat2.ProfitDebitCapNum += TradeCount;
                                                    }
                                                }
                                            }
                                            else if (BankCardType != 0)
                                            {
                                                if (Version == 2)
                                                {
                                                    teamStat2.ProfitTradeAmt += TradeAmount;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            function.WritePage("/TradeRecord/", "TmpId.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", "临时补交易额日志");
        }



    }
}