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

public class WifiTradeHelper
{
    public readonly static WifiTradeHelper Instance = new WifiTradeHelper();
    private WifiTradeHelper()
    {
    }

    public void Start()
    {
        Thread th = new Thread(DoWorks);
        th.IsBackground = true;
        th.Start();
    }

    private void DoWorks()
    {
        while (true)
        {
            try
            {
                if(DateTime.Now.Day < 25 && DateTime.Now.Hour < 20)
                {
                    string Month = DateTime.Now.ToString("yyyy-MM");
                    DoSomething(Month);
                }
                Thread.Sleep(3600000);
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "WIFI发放交易额异常");
            }
        }
    }

    public void DoSomething(string Month)
    {
        string chk = function.ReadInstance("/wifi/trade" + Month + ".txt");
        if(!string.IsNullOrEmpty(chk))
        {
            return;
        }
        function.WritePage("/wifi/", "trade" + Month + ".txt", DateTime.Now.ToString());
        string MonthString = Month.Replace("-", "");
        WebCMSEntities db = new WebCMSEntities();
        MySystem.ReadModels.WebCMSEntities rdb = new MySystem.ReadModels.WebCMSEntities();
        DateTime end = DateTime.Parse(Month + "-01 00:00:00");
        List<string> SnNos = new List<string>();
        List<MySystem.ReadModels.WifiTradeRecord> trades = rdb.WifiTradeRecord.Where(m => m.Duration >= m.DoMonths && m.CreateDate < end && m.LastMonth != MonthString).ToList();
        List<MySystem.ReadModels.Users> users = rdb.Users.Where(m => m.AuthFlag == 1).ToList();
        List<string> PosSns = trades.Select(m => m.SnNo).ToList();
        List<PosMachinesTwo> posList = db.PosMachinesTwo.Where(m => PosSns.Contains(m.PosSn)).ToList();
        List<PosMerchantInfo> merList = db.PosMerchantInfo.Where(m => PosSns.Contains(m.KqMerNo)).ToList();
        List<TradeDaySummary> statTrade = new List<TradeDaySummary>();
        List<TradeDaySummaryBefore> statTradeBefore = new List<TradeDaySummaryBefore>();
        List<TradeDaySummaryAfter> statTradeAfter = new List<TradeDaySummaryAfter>();
        Utils.WriteLog(trades.Count.ToString(), "WIFI发放交易额日志");
        foreach(MySystem.ReadModels.WifiTradeRecord trade in trades)
        {
            Utils.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(trade), "WIFI发放交易额日志");
            if(trade.Unit == "m" && trade.Duration > 0 && !SnNos.Contains(trade.SnNo))
            {
                decimal TradeAmt = trade.TradeAmount / trade.Duration;
                TradeAmt = PublicFunction.NumberFormat(TradeAmt);
                // PosMachinesTwo pos = posList.FirstOrDefault(m => m.PosSn == trade.SnNo) ?? new PosMachinesTwo();
                // PosMerchantInfo mer = merList.FirstOrDefault(m => m.Id == pos.BindMerchantId) ?? new PosMerchantInfo();
                // StatTrade(statTrade, users, pos.BuyUserId, pos.BrandId, Month.Replace("-", ""), TradeAmt);
                // if (pos.BindingTime < trade.CreateDate.Value.AddMonths(-9))
                // {
                //     StatTradeBefore(statTradeBefore, users, pos.BuyUserId, pos.BrandId, Month.Replace("-", ""), TradeAmt);
                // }
                // else
                // {
                //     StatTradeAfter(statTradeAfter, users, pos.BuyUserId, pos.BrandId, Month.Replace("-", ""), TradeAmt);
                // }
                WifiTradeRecord edit = db.WifiTradeRecord.FirstOrDefault(m => m.Id == trade.Id);
                if(edit != null)
                {
                    edit.DoMonths += 1;
                    edit.LastMonth = Month.Replace("-", "");
                    db.SaveChanges();

                    //推送wifi交易给java
                    PosPushDataNewHelper.Trade(new MySystem.SpModels.TradeRecord()
                    {
                        TradeSnNo = edit.SnNo,
                        MerNo = edit.SnNo,
                        TradeAmount = TradeAmt,
                        TradeSerialNo = Guid.NewGuid().ToString(),
                        CreateDate = DateTime.Parse(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01 01:00:00"),
                        ProductType = edit.BrandId.ToString(),
                    });
                }
                SnNos.Add(trade.SnNo);
            }
        }
        
        int index = 0;
        foreach(TradeDaySummary sub in statTrade)
        {
            index += 1;
            db.TradeDaySummary.Add(sub);
            if(index % 200 == 0)
            {
                db.SaveChanges();
            }
        }
        db.SaveChanges();
        index = 0;
        foreach(TradeDaySummaryBefore sub in statTradeBefore)
        {
            index += 1;
            db.TradeDaySummaryBefore.Add(sub);
            if(index % 200 == 0)
            {
                db.SaveChanges();
            }
        }
        db.SaveChanges();
        index = 0;
        foreach(TradeDaySummaryAfter sub in statTradeAfter)
        {
            index += 1;
            db.TradeDaySummaryAfter.Add(sub);
            if(index % 200 == 0)
            {
                db.SaveChanges();
            }
        }
        db.SaveChanges();
        db.Dispose();

        function.WritePage("/wifi/", "trade" + Month + "-end.txt", DateTime.Now.ToString());
    }


    // public void DoSomethingNew(string Month)
    // {
    //     WebCMSEntities db = new WebCMSEntities();
    //     MySystem.ReadModels.WebCMSEntities rdb = new MySystem.ReadModels.WebCMSEntities();
    //     DateTime end = DateTime.Parse(Month + "-01 00:00:00").AddMonths(1);
    //     List<string> SnNos = new List<string>();
    //     List<MySystem.ReadModels.WifiTradeRecord> trades = rdb.WifiTradeRecord.Where(m => m.Duration >= m.DoMonths && m.CreateDate < end).ToList();
    //     foreach(MySystem.ReadModels.WifiTradeRecord trade in trades)
    //     {
    //         if(trade.Unit == "m" && trade.Duration > 0 && !SnNos.Contains(trade.SnNo))
    //         {
    //             DoOne(db, trade.Id, Month, "");
    //             SnNos.Add(trade.SnNo);
    //         }
    //     }
    //     db.SaveChanges();
    //     db.Dispose();
    // }

    public void DoOne(WebCMSEntities db, int Id, string Month, string OrderNo, bool time = false)
    {
        WifiTradeRecord edit = db.WifiTradeRecord.FirstOrDefault(m => m.Id == Id);
        if(edit != null)
        { 
            int orderCount = 0;
            if(!string.IsNullOrEmpty(edit.MerNo))
            {
                orderCount = db.WifiTradeRecord.Count(m => m.SnNo == edit.SnNo && m.MerNo == edit.MerNo);
            }
            if(edit.LastMonth != Month.Replace("-", ""))
            {
                // decimal TradeAmt = edit.TradeAmount / edit.Duration;
                // TradeAmt = PublicFunction.NumberFormat(TradeAmt);

                // if(orderCount > 1) TradeAmt = 0.01M;
                decimal TradeAmt = 0.01M;
                
                edit.DoMonths += 1;
                edit.LastMonth = Month.Replace("-", "");

                //推送wifi交易给java
                PosPushDataNewHelper.Trade(new MySystem.SpModels.TradeRecord()
                {
                    TradeSnNo = edit.SnNo,
                    MerNo = edit.SnNo,
                    TradeAmount = TradeAmt,
                    TradeSerialNo = Guid.NewGuid().ToString(),
                    CreateDate = time ? DateTime.Now : DateTime.Parse(Month + "-01 01:00:00"),
                    ProductType = edit.BrandId.ToString(),
                    ErrorMsg = edit.DoMonths == 1 ? edit.TradeAmount.ToString() : "0",
                    ChannelSerial = OrderNo,
                });
            }
        }
    }

    public void StatTrade(List<TradeDaySummary> statTrade, List<MySystem.ReadModels.Users> users, int UserId, int BrandId, string TradeMonth, decimal TradeAmount)
    {
        MySystem.ReadModels.Users user = users.FirstOrDefault(m => m.Id == UserId) ?? new MySystem.ReadModels.Users();
        string ParentNav = user.ParentNav;
        string TradeDate = TradeMonth + "01";
        ParentNav += "," + UserId + ",";

        TradeDaySummary selfStat = statTrade.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.SeoTitle == "self");
        if (selfStat == null)
        {
            statTrade.Add(new TradeDaySummary()
            {
                UserId = UserId,
                TradeMonth = TradeMonth,
                TradeDate = TradeDate,
                BrandId = BrandId,
                SeoTitle = "self",
                HelpDirectTradeAmt = TradeAmount,
            });
        }
        else
        {
            selfStat.HelpDirectTradeAmt += TradeAmount;
        }
        if (!string.IsNullOrEmpty(ParentNav))
        {
            string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
            foreach (string NavUserIdString in ParentNavList)
            {
                int NavUserId = int.Parse(NavUserIdString);
                TradeDaySummary teamStat = statTrade.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.SeoTitle == "team");
                if (teamStat == null)
                {
                    statTrade.Add(new TradeDaySummary()
                    {
                        UserId = NavUserId,
                        TradeMonth = TradeMonth,
                        TradeDate = TradeDate,
                        BrandId = BrandId,
                        SeoTitle = "team",
                        HelpNonDirectTradeAmt = TradeAmount,
                    });
                }
                else
                {
                    teamStat.HelpNonDirectTradeAmt += TradeAmount;
                }
            }
        }
    }

    public void StatTradeBefore(List<TradeDaySummaryBefore> statTrade, List<MySystem.ReadModels.Users> users, int UserId, int BrandId, string TradeMonth, decimal TradeAmount)
    {
        MySystem.ReadModels.Users user = users.FirstOrDefault(m => m.Id == UserId) ?? new MySystem.ReadModels.Users();
        string ParentNav = user.ParentNav;
        string TradeDate = TradeMonth + "01";
        ParentNav += "," + UserId + ",";

        TradeDaySummaryBefore selfStat = statTrade.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.SeoTitle == "self");
        if (selfStat == null)
        {
            statTrade.Add(new TradeDaySummaryBefore()
            {
                UserId = UserId,
                TradeMonth = TradeMonth,
                TradeDate = TradeDate,
                BrandId = BrandId,
                SeoTitle = "self",
                HelpDirectTradeAmt = TradeAmount,
            });
        }
        else
        {
            selfStat.HelpDirectTradeAmt += TradeAmount;
        }
        if (!string.IsNullOrEmpty(ParentNav))
        {
            string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
            foreach (string NavUserIdString in ParentNavList)
            {
                int NavUserId = int.Parse(NavUserIdString);
                TradeDaySummaryBefore teamStat = statTrade.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.SeoTitle == "team");
                if (teamStat == null)
                {
                    statTrade.Add(new TradeDaySummaryBefore()
                    {
                        UserId = NavUserId,
                        TradeMonth = TradeMonth,
                        TradeDate = TradeDate,
                        BrandId = BrandId,
                        SeoTitle = "team",
                        HelpNonDirectTradeAmt = TradeAmount,
                    });
                }
                else
                {
                    teamStat.HelpNonDirectTradeAmt += TradeAmount;
                }
            }
        }
    }

    public void StatTradeAfter(List<TradeDaySummaryAfter> statTrade, List<MySystem.ReadModels.Users> users, int UserId, int BrandId, string TradeMonth, decimal TradeAmount)
    {
        MySystem.ReadModels.Users user = users.FirstOrDefault(m => m.Id == UserId) ?? new MySystem.ReadModels.Users();
        string ParentNav = user.ParentNav;
        string TradeDate = TradeMonth + "01";
        ParentNav += "," + UserId + ",";

        TradeDaySummaryAfter selfStat = statTrade.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.SeoTitle == "self");
        if (selfStat == null)
        {
            statTrade.Add(new TradeDaySummaryAfter()
            {
                UserId = UserId,
                TradeMonth = TradeMonth,
                TradeDate = TradeDate,
                BrandId = BrandId,
                SeoTitle = "self",
                HelpDirectTradeAmt = TradeAmount,
            });
        }
        else
        {
            selfStat.HelpDirectTradeAmt += TradeAmount;
        }
        if (!string.IsNullOrEmpty(ParentNav))
        {
            string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
            foreach (string NavUserIdString in ParentNavList)
            {
                int NavUserId = int.Parse(NavUserIdString);
                TradeDaySummaryAfter teamStat = statTrade.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.SeoTitle == "team");
                if (teamStat == null)
                {
                    statTrade.Add(new TradeDaySummaryAfter()
                    {
                        UserId = NavUserId,
                        TradeMonth = TradeMonth,
                        TradeDate = TradeDate,
                        BrandId = BrandId,
                        SeoTitle = "team",
                        HelpNonDirectTradeAmt = TradeAmount,
                    });
                }
                else
                {
                    teamStat.HelpNonDirectTradeAmt += TradeAmount;
                }
            }
        }
    }
}