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

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

        public void dosomething()
        {
            while (true)
            {
                string data = RedisDbconn.Instance.RPop<string>("TradeChangeQueue");
                if (!string.IsNullOrEmpty(data))
                {
                    try
                    {
                        JsonData jsonOj = JsonMapper.ToObject(data);
                        int Id = int.Parse(function.CheckInt(jsonOj["Id"].ToString()));
                        int OldType = int.Parse(function.CheckInt(jsonOj["OldType"].ToString()));
                        int NewType = int.Parse(function.CheckInt(jsonOj["NewType"].ToString()));
                        StatTradeAmount(Id, OldType, NewType);
                    }
                    catch (Exception ex)
                    {                        
                        Utils.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "设置激活奖励异常");
                    }
                }
                else
                {
                    Thread.Sleep(500);
                }
            }
        }

        public void StatTradeAmount(int Id, int OldType, int NewType)
        {
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "交易额类型变更");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                DataTable selfDt = CustomerSqlConn.dtable("select UserId,ParentNav,BrandId,BankCardType,QrPayFlag,MerHelpFlag,Version,CapFlag,VipFlag,PayType,DATE_FORMAT(CreateDate,'%Y%m%d'),TradeAmount from TradeRecord where Id=" + Id + "", MysqlConn.SqlConnStr);
                if (selfDt.Rows.Count > 0)
                {
                    Utils.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "交易额类型变更");
                    foreach (DataRow selfDr in selfDt.Rows)
                    {
                        int UserId = int.Parse(selfDr["UserId"].ToString());
                        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["TradeAmount"].ToString());
                        string TradeMonth = TradeDate.Substring(0, 6);

                        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)
                        {
                            if (BankCardType == 0)
                            {
                                if(OldType == 2)
                                {
                                    if(selfStat.NotHelpDirectDebitTradeAmt >= TradeAmount)
                                    {
                                        selfStat.NotHelpDirectDebitTradeAmt -= TradeAmount;
                                        if(NewType == 1)
                                        {
                                            selfStat.HelpDirectDebitTradeAmt += TradeAmount;
                                        }
                                    }
                                    if (CapFlag == 1)
                                    {
                                        if(selfStat.NotHelpDirectDebitCapTradeAmt >= TradeAmount)
                                        {
                                            selfStat.NotHelpDirectDebitCapTradeAmt -= TradeAmount;
                                            if(NewType == 1)
                                            {
                                                selfStat.HelpDirectDebitCapTradeAmt += TradeAmount;
                                            }
                                        }
                                    }
                                }
                            }
                            else if (BankCardType != 0)
                            {
                                if(OldType == 2)
                                {
                                    if(selfStat.NotHelpDirectTradeAmt >= TradeAmount)
                                    {
                                        selfStat.NotHelpDirectTradeAmt -= TradeAmount;
                                        if(NewType == 1)
                                        {
                                            selfStat.HelpDirectTradeAmt += 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)
                                    {
                                        if (BankCardType == 0)
                                        {
                                            if(OldType == 2)
                                            {
                                                if(teamStat.NotHelpNonDirectDebitTradeAmt >= TradeAmount)
                                                {
                                                    teamStat.NotHelpNonDirectDebitTradeAmt -= TradeAmount;
                                                    if(NewType == 1)
                                                    {
                                                        teamStat.HelpNonDirectDebitTradeAmt += TradeAmount;
                                                    }
                                                }
                                                if (CapFlag == 1)
                                                {
                                                    if(teamStat.NotHelpDirectDebitCapTradeAmt >= TradeAmount)
                                                    {
                                                        teamStat.NotHelpDirectDebitCapTradeAmt -= TradeAmount;
                                                        if(NewType == 1)
                                                        {
                                                            teamStat.HelpDirectDebitCapTradeAmt += TradeAmount;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        else if (BankCardType != 0)
                                        {
                                            if(OldType == 2)
                                            {
                                                if(teamStat.NotHelpNonDirectTradeAmt >= TradeAmount)
                                                {
                                                    teamStat.NotHelpNonDirectTradeAmt -= TradeAmount;
                                                    if(NewType == 1)
                                                    {
                                                        teamStat.HelpNonDirectTradeAmt += TradeAmount;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "交易额类型变更异常");
            }
            db.Dispose();
            Utils.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "交易额类型变更");
        }
    }
}