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






        // 重置交易额
        public void Start()
        {
            Thread th = new Thread(StartDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("StatResetUserTradeQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    StatTrade(content);
                    Thread.Sleep(2000);
                }
                else
                {
                    Thread.Sleep(61000);
                }
            }
        }

        public void StatTrade(string content)
        {
            JsonData jsonObj = JsonMapper.ToObject(content);
            string Kind = jsonObj["Kind"].ToString();
            string BrandId = jsonObj["BrandId"].ToString();
            string TradeDate = jsonObj["TradeDate"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "重置创客交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string TradeDateStr = TradeDate.Replace("-", "");
                if(Kind.Contains("1"))
                {
                    CustomerSqlConn.op("delete from TradeDaySummary where TradeDate='" + TradeDateStr + "' and BrandId in (" + BrandId + ")", AppConfig.Base.SqlConn);
                    CustomerSqlConn.op("delete from TradeDaySummary2 where TradeDate='" + TradeDateStr + "' and BrandId in (" + BrandId + ")", AppConfig.Base.SqlConn);
                }
                if(Kind.Contains("2"))
                {
                    CustomerSqlConn.op("delete from TradeDaySummaryBefore where TradeDate='" + TradeDateStr + "' and BrandId in (" + BrandId + ")", AppConfig.Base.SqlConn);
                    CustomerSqlConn.op("delete from TradeDaySummary2Before where TradeDate='" + TradeDateStr + "' and BrandId in (" + BrandId + ")", AppConfig.Base.SqlConn);
                }
                if(Kind.Contains("3"))
                {
                    CustomerSqlConn.op("delete from TradeDaySummaryAfter where TradeDate='" + TradeDateStr + "' and BrandId in (" + BrandId + ")", AppConfig.Base.SqlConn);
                    CustomerSqlConn.op("delete from TradeDaySummary2After where TradeDate='" + TradeDateStr + "' and BrandId in (" + BrandId + ")", AppConfig.Base.SqlConn);
                }
                string startId = "20000000";
                bool op = true;
                while(op)
                {
                    string sql = "select Id from TradeRecord where Id>" + startId + " and CreateDate>='" + TradeDate + " 00:00:00' and CreateDate<='" + TradeDate + " 23:59:59' and BrandId in (" + BrandId + ") order by Id limit 50";
                    DataTable idsDt = CustomerSqlConn.dtable(sql, AppConfig.Base.TmpReadSqlConn);
                    if(idsDt.Rows.Count > 0)
                    {
                        string ids = "";
                        foreach (DataRow idsDr in idsDt.Rows)
                        {
                            ids += idsDr["Id"].ToString() + ",";
                            startId = idsDr["Id"].ToString();
                        }
                        DataTable selfDt = CustomerSqlConn.dtable("select UserId,ParentNav,BrandId,BankCardType,QrPayFlag,MerHelpFlag,Version,CapFlag,VipFlag,PayType,DATE_FORMAT(CreateDate,'%Y%m%d'),sum(TradeAmount),count(Id),SnNo from TradeRecord where Id in (" + ids.TrimEnd(',') + ") group by UserId,ParentNav,BrandId,BankCardType,QrPayFlag,MerHelpFlag,Version,CapFlag,VipFlag,PayType,DATE_FORMAT(CreateDate,'%Y%m%d'),SnNo", AppConfig.Base.TmpReadSqlConn);
                        if (selfDt.Rows.Count > 0)
                        {
                            function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "重置创客交易额日志");
                            foreach (DataRow selfDr in selfDt.Rows)
                            {
                                if(Kind.Contains("1"))
                                {
                                    StatService.Instance.StatTrade(db, selfDr);
                                }

                                int UserId = int.Parse(selfDr["UserId"].ToString());
                                string SnNo = selfDr["SnNo"].ToString();
                                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == SnNo) ?? new PosMachinesTwo();
                                if (UserId == 0)
                                {
                                    UserId = pos.UserId;
                                }
                                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                                string ParentNav = user.ParentNav; //selfDr["ParentNav"].ToString();
                                if (pos.BindingTime < DateTime.Parse("2023-07-01 00:00:00"))
                                {
                                    if(Kind.Contains("2"))
                                    {
                                        Stat2Service.Instance.StatBefore(db, selfDr, UserId, ParentNav);
                                    }
                                }
                                else
                                {
                                    if(Kind.Contains("3"))
                                    {
                                        Stat2Service.Instance.StatAfter(db, selfDr, UserId, ParentNav);
                                    }
                                }
                            }
                        }
                        db.SaveChanges();
                    }
                    else
                    {
                        op = false;
                    }
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "重置创客交易额异常");
            }
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "重置创客交易额日志");
        }
    }
}