using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.Extensions.Hosting;
using MySystem;
using MySystem.Models;
using LitJson;
using Library;

public class TradeStatTimer2
{
    public readonly static TradeStatTimer2 Instance = new TradeStatTimer2();
    private TradeStatTimer2()
    {
    }
    
    public void Start()
    {
        Thread th = new Thread(DoWorks);
        th.IsBackground = true;
        th.Start();
    }

    private void DoWorks()
    {
        while (true)
        {
            string content = RedisDbconn.Instance.RPop<string>("TradeStatQueueTest");
            if (!string.IsNullOrEmpty(content))
            {
                JsonData jsonObj = JsonMapper.ToObject(content);
                string DateString = jsonObj["DateString"].ToString();
                int UserId = int.Parse(jsonObj["UserId"].ToString()); //创客ID
                if (UserId == 9)
                {
                    string ss = "123";
                }
                int BrandId = int.Parse(jsonObj["BrandId"].ToString()); //品牌
                int BankCardType = int.Parse(jsonObj["BankCardType"].ToString()); //卡类型
                int MerchantId = int.Parse(jsonObj["MerchantId"].ToString()); //商户Id
                int QrPayFlag = int.Parse(jsonObj["QrPayFlag"].ToString()); //云闪付
                decimal TradeAmount = decimal.Parse(jsonObj["TradeAmount"].ToString()); //当日交易额
                string TradeMonth = DateTime.Parse(DateString).ToString("yyyyMM");
                string TradeDate = DateTime.Parse(DateString).ToString("yyyyMMdd");
                WebCMSEntities db = new WebCMSEntities();
                var tran = db.Database.BeginTransaction();
                try
                {
                    PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new PosMerchantInfo();
                    MachineForMerNo machineFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == merchant.KqMerNo) ?? new MachineForMerNo();
                    PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == machineFor.SnId) ?? new PosMachinesTwo();
                    int MerchantTypeUserId = int.Parse(function.CheckInt(pos.SeoTitle));
                    if (MerchantTypeUserId > 0)
                    {
                        Users merchantUser = db.Users.FirstOrDefault(m => m.Id == MerchantTypeUserId && m.MerchantType == 1);
                        if (merchantUser != null)
                        {
                            UserId = MerchantTypeUserId;
                        }
                    }
                    Users user = db.Users.FirstOrDefault(m => m.Id == UserId);
                    if (user != null)
                    {
                        if (user.AuthFlag == 1)
                        {
                            UserTradeDaySummary selfStat = db.UserTradeDaySummary.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.Sort == MerchantId && m.SeoTitle == "self");
                            if (selfStat == null)
                            {
                                selfStat = db.UserTradeDaySummary.Add(new UserTradeDaySummary()
                                {
                                    UserId = UserId,
                                    TradeMonth = TradeMonth,
                                    TradeDate = TradeDate,
                                    BrandId = BrandId,
                                    QueryCount = QrPayFlag,
                                    Sort = MerchantId,
                                    SeoTitle = "self",
                                }).Entity;
                                db.SaveChanges();
                            }
                            if (BankCardType == 0)
                            { 
                                selfStat.DirectDebitTradeAmt += TradeAmount;
                            }
                            else if (BankCardType == 1)
                            {
                                selfStat.DirectTradeAmt += TradeAmount;
                            }
                            db.SaveChanges();

                            string ParentNav = user.ParentNav;
                            if (UserId != pos.UserId)
                            {
                                user = db.Users.FirstOrDefault(m => m.Id == pos.UserId);
                                if (user != null)
                                {
                                    ParentNav = user.ParentNav;
                                    UserId = pos.UserId;
                                }
                            }
                            if (!string.IsNullOrEmpty(ParentNav))
                            {
                                ParentNav += "," + UserId + ",";
                                string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                                foreach (string UserIdString in ParentNavList)
                                {
                                    int ParentUserId = int.Parse(UserIdString);
                                    UserTradeDaySummary teamStat = db.UserTradeDaySummary.FirstOrDefault(m => m.UserId == ParentUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.Sort == MerchantId && m.SeoTitle == "team");
                                    if (teamStat == null)
                                    {
                                        teamStat = db.UserTradeDaySummary.Add(new UserTradeDaySummary()
                                        {
                                            UserId = ParentUserId,
                                            TradeMonth = TradeMonth,
                                            TradeDate = TradeDate,
                                            BrandId = BrandId,
                                            QueryCount = QrPayFlag,
                                            Sort = MerchantId,
                                            SeoTitle = "team",
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    if (BankCardType == 0)
                                    { 
                                        teamStat.NonDirectDebitTradeAmt += TradeAmount;
                                    }
                                    else if (BankCardType == 1)
                                    {
                                        teamStat.NonDirectTradeAmt += TradeAmount;
                                    }
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                    else
                    { 
                        int ParentUserId = 1;
                        UserTradeDaySummary teamStat = db.UserTradeDaySummary.FirstOrDefault(m => m.UserId == ParentUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.Sort == MerchantId && m.SeoTitle == "team");
                        if (teamStat == null)
                        {
                            teamStat = db.UserTradeDaySummary.Add(new UserTradeDaySummary()
                            {
                                UserId = ParentUserId,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                BrandId = BrandId,
                                QueryCount = QrPayFlag,
                                Sort = MerchantId,
                                SeoTitle = "team",
                            }).Entity;
                            db.SaveChanges();
                        }
                        if (BankCardType == 0)
                        { 
                            teamStat.NonDirectDebitTradeAmt += TradeAmount;
                        }
                        else if (BankCardType == 1)
                        {
                            teamStat.NonDirectTradeAmt += TradeAmount;
                        }
                        db.SaveChanges();
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + content + "\n" + ex.ToString(), "统计交易额异常2");
                    tran.Rollback();
                }
                tran.Dispose();
                db.Dispose();
            }
            else
            {
                Thread.Sleep(5000);
            }
        }
    }
}