using System;
using System.Collections.Generic;
using System.Linq;
using MySystem.SpModels;
using Library;
using LitJson;
using System.Threading;

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

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

        public void StartDo()
        {
            while (true)
            {
                try
                {
                    List<string> SaveDataBindIds = Utils.Instance.SaveDataBindIds();
                    WebCMSEntities spdb = new WebCMSEntities();
                    PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                    DateTime start = DateTime.Now.AddDays(-60);
                    DateTime end = DateTime.Now.AddMinutes(-1);
                    int StartId = int.Parse(function.CheckInt(function.ReadInstance("/SycnSp/TradeRecordId.txt")));
                    IQueryable<TradeRecord> trades = spdb.TradeRecord.Where(m => m.Id >= StartId && m.ProductType == "23" && m.CreateDate >= start && SaveDataBindIds.Contains(m.ProductType) && m.Status == 1).OrderBy(m => m.CreateDate).Take(20);
                    foreach (TradeRecord trade in trades.ToList())
                    {
                        DoQueueTrade(db, trade);
                        TradeRecord edit = spdb.TradeRecord.FirstOrDefault(m => m.Id == trade.Id);
                        if (edit != null)
                        {
                            edit.Status = 2;
                            spdb.SaveChanges();
                        }
                    }
                    spdb.Dispose();
                    db.Dispose();
                }
                catch (Exception ex)
                {
                    Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP交易数据到MAIN异常");
                }
                Thread.Sleep(500);
            }
        }

        public void DoQueueTrade(PxcModels.WebCMSEntities db, TradeRecord trade)
        {
            bool check = db.SpOrderNos.Any(m => m.OrderNo == trade.TradeSerialNo);
            if (!check && trade.SerEntryMode != "1")
            {
                int BrandId = int.Parse(function.CheckInt(trade.ProductType));
                decimal TradeAmount = trade.TradeAmount;
                if(trade.SeoTitle != "v2") TradeAmount = TradeAmount / 100;
                PxcModels.WifiTradeRecord add = db.WifiTradeRecord.Add(new PxcModels.WifiTradeRecord()
                {
                    CreateDate = trade.CreateDate,
                    UpdateDate = trade.UpdateDate,
                    SnNo = trade.TradeSnNo, //渠道SN号
                    MerNo = trade.MerNo, //商户号
                    TradeAmount = TradeAmount, //交易金额
                    BrandId = BrandId, //品牌
                    Remark = trade.MerNo, //备注
                    OrderNo = trade.TradeSerialNo,
                }).Entity;
                db.SpOrderNos.Add(new PxcModels.SpOrderNos()
                {
                    OrderNo = trade.TradeSerialNo
                });
                db.SaveChanges();

                //开始统计
                int Months = 0;

                if(trade.SeoTitle == "v2")
                {
                    string duration = trade.Field2; //设备套餐时长
                    string unit = trade.Field3; //套餐单位 0:按天 1:按月
                    if(unit == "1") Months = int.Parse(function.CheckInt(duration));
                    else Months = int.Parse(function.CheckInt(duration)) / 30;
                }
                else
                {
                    if(BrandId == 23 && TradeAmount == 49) Months = 1;
                    else if(BrandId == 23 && TradeAmount == 79) Months = 3;
                    else if(BrandId == 23 && TradeAmount == 119) Months = 12;
                    else if(BrandId == 23 && TradeAmount == 199) Months = 24;
                    else Months = trade.QueryCount;

                    // if(BrandId == 24 && TradeAmount == 59) Months = 1;
                    // if(BrandId == 24 && TradeAmount == 159) Months = 3;
                    // if(BrandId == 24 && TradeAmount == 399) Months = 12;
                    // if(BrandId == 24 && TradeAmount == 699) Months = 24;

                    // if(BrandId == 25 && TradeAmount == 69) Months = 1;
                    // if(BrandId == 25 && TradeAmount == 199) Months = 3;
                    // if(BrandId == 25 && TradeAmount == 499) Months = 12;
                    // if(BrandId == 25 && TradeAmount == 799) Months = 24;

                    // if(BrandId == 26 && TradeAmount == 219) Months = 1;
                    // if(BrandId == 26 && TradeAmount == 449) Months = 3;
                    // if(BrandId == 26 && TradeAmount == 1399) Months = 12;
                    // if(BrandId == 26 && TradeAmount == 2698) Months = 24;
                }
                string TradeMonth = DateTime.Now.ToString("yyyyMM");

                add.Duration = Months;
                add.Unit = "m";
                WifiTradeHelper.Instance.DoOne(db, add.Id, DateTime.Now.ToString("yyyy-MM"), trade.TradeSerialNo, true);
                db.SaveChanges();
            }
            if(trade.SerEntryMode == "1")
            {
                PosPushDataNewHelper.Deposit(new ActivateRecord()
                {
                    SeoTitle = trade.TradeAmount.ToString(),
                    ProductType = trade.ProductType,
                    SnNo = trade.TradeSnNo,
                    MerNo = trade.TradeSnNo,
                    Id = trade.Id,
                });
            }
        }

        

        public void StatTrade(PxcModels.WebCMSEntities db, int UserId, int BrandId, string TradeMonth, decimal TradeAmount)
        {
            PxcModels.Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new PxcModels.Users();
            string ParentNav = user.ParentNav;
            string TradeDate = TradeMonth + "01";
            ParentNav += "," + UserId + ",";

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

        public void StatTradeBefore(PxcModels.WebCMSEntities db, int UserId, int BrandId, string TradeMonth, decimal TradeAmount)
        {
            PxcModels.Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new PxcModels.Users();
            string ParentNav = user.ParentNav;
            string TradeDate = TradeMonth + "01";
            ParentNav += "," + UserId + ",";

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

        public void StatTradeAfter(PxcModels.WebCMSEntities db, int UserId, int BrandId, string TradeMonth, decimal TradeAmount)
        {
            PxcModels.Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new PxcModels.Users();
            string ParentNav = user.ParentNav;
            string TradeDate = TradeMonth + "01";
            ParentNav += "," + UserId + ",";

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

        //推送wifi每月交易到java
        public void PushMsgToJava(string MsgContent)
        {
            PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
            try
            {
                JsonData jsonObj = JsonMapper.ToObject(MsgContent);
                string PosSn = jsonObj["pos_sn"].ToString();
                decimal TradeAmount = decimal.Parse(jsonObj["amt"].ToString());
                PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn) ?? new PxcModels.PosMachinesTwo();
                if(pos.Status > -1 && pos.BuyUserId > 0 && pos.ActivationState == 1)
                {
                    PxcModels.PosMerchantInfo mer = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId) ?? new PxcModels.PosMerchantInfo();
                    PosPushDataNewHelper.Trade(new TradeRecord()
                    {
                        TradeSnNo = pos.PosSn,
                        MerNo = mer.KqMerNo,
                        TradeSerialNo = Guid.NewGuid().ToString(),
                        TradeAmount = TradeAmount,
                        CreateDate = DateTime.Now,
                        ProductType = pos.BrandId.ToString(),
                    });
                }
            }
            catch(Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "推送wifi每月交易到java异常");
            }
            db.Dispose();
        }
    }
}