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
                {
                    WebCMSEntities spdb = new WebCMSEntities();
                    PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
                    DateTime start = DateTime.Now.AddDays(-10);
                    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 && m.Status == 1).OrderBy(m => m.CreateDate).Take(20);
                    foreach (TradeRecord trade in trades.ToList())
                    {
                        bool check = db.SpOrderNos.Any(m => m.OrderNo == trade.TradeSerialNo);
                        if (!check)
                        {
                            decimal TradeAmount = trade.TradeAmount / 100;
                            PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == trade.TradeSnNo);
                            if (pos != null)
                            {
                                PxcModels.WifiTradeRecord add = db.WifiTradeRecord.Add(new PxcModels.WifiTradeRecord()
                                {
                                    CreateDate = trade.CreateDate,
                                    UpdateDate = trade.UpdateDate,
                                    SnNo = trade.TradeSnNo, //渠道SN号
                                    TradeAmount = TradeAmount, //交易金额
                                    BrandId = pos.BrandId, //品牌
                                    Remark = trade.Remark, //备注                                
                                }).Entity;
                            }
                            db.SpOrderNos.Add(new PxcModels.SpOrderNos()
                            {
                                OrderNo = trade.TradeSerialNo
                            });
                            db.SaveChanges();

                            //开始统计
                            int Months = 0;

                            if(pos.BrandId == 23 && TradeAmount == 49) Months = 1;
                            if(pos.BrandId == 23 && TradeAmount == 79) Months = 3;
                            if(pos.BrandId == 23 && TradeAmount == 119) Months = 12;
                            if(pos.BrandId == 23 && TradeAmount == 199) Months = 24;

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

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

                            if(pos.BrandId == 26 && TradeAmount == 219) Months = 1;
                            if(pos.BrandId == 26 && TradeAmount == 449) Months = 3;
                            if(pos.BrandId == 26 && TradeAmount == 1399) Months = 12;
                            if(pos.BrandId == 26 && TradeAmount == 2698) Months = 24;

                            if(Months > 0)
                            {
                                decimal TradeAmt = TradeAmount / Months;
                                TradeAmt = PublicFunction.NumberFormat(TradeAmt);
                                PxcModels.TradeDaySummary stat = db.TradeDaySummary.Where(m => m.UserId == pos.BuyUserId && m.BrandId == pos.BrandId).OrderByDescending(m => m.Id).FirstOrDefault() ?? new PxcModels.TradeDaySummary();
                                string TradeMonth = string.IsNullOrEmpty(stat.TradeMonth) ? DateTime.Now.AddMonths(-1).ToString("yyyyMM") : stat.TradeMonth;
                                DateTime StartMonth = DateTime.Parse(TradeMonth.Substring(0, 4) + "-" + TradeMonth.Substring(4, 2) + "-01 00:00:00");
                                for (int i = 1; i <= Months; i++)
                                {
                                    StartMonth = StartMonth.AddMonths(1);
                                    StatTrade(db, pos.BuyUserId, pos.BrandId, StartMonth.ToString("yyyyMM"), TradeAmt);
                                }
                            }

                            //检查交易状态，并发奖励
                            if(pos.ActivationState == 1)
                            {
                                PxcModels.PosMerchantInfo add = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId) ?? new PxcModels.PosMerchantInfo();
                                SycnSpMerchantService.Instance.WifiSendPrize(db, pos, add);
                            }

                            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)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP交易数据到MAIN异常");
                }
                Thread.Sleep(500);
            }
        }

        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();
                }
            }
        }
    }
}