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






        // 统计交易额V2
        public void StartEverDayV2()
        {
            Thread th = new Thread(StartEverDayV2Do);
            th.IsBackground = true;
            th.Start();
        }
        public void StartEverDayV2Do()
        {
            while (true)
            {
                if(DateTime.Now.Hour >= 3)
                {
                    StatTradeAmountEverDayV2();
                }
                Thread.Sleep(30000);
            }
        }
        public void StatTradeAmountEverDayV2()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时执行企业交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    string startId = function.ReadInstance("/TradeRecord/Id2.txt");
                    if(string.IsNullOrEmpty(startId))
                    {
                        startId = "867041";
                    }
                    DataTable idsDt = OtherMySqlConn.dtable("select Id from TradeRecord where Id>=" + startId + " and ActStatus=1 and CreateDate>='2022-08-16 00:00:00' and UserId in (select Id from Users where BusinessFlag=1) and QueryCount=1 order by Id limit 50");
                    if(idsDt.Rows.Count > 0)
                    {
                        string ids = "";
                        foreach (DataRow idsDr in idsDt.Rows)
                        {
                            ids += idsDr["Id"].ToString() + ",";
                            startId = idsDr["Id"].ToString();
                        }
                        DataTable selfDt = OtherMySqlConn.dtable("select UserId,MerchantId,BrandId,BankCardType,QrPayFlag,MerHelpFlag,CapFlag,VipFlag,PayType,DATE_FORMAT(CreateDate,'%Y%m%d'),sum(TradeAmount),count(Id) from TradeRecord where Id in (" + ids.TrimEnd(',') + ") group by UserId,MerchantId,BrandId,BankCardType,QrPayFlag,MerHelpFlag,CapFlag,VipFlag,PayType,DATE_FORMAT(CreateDate,'%Y%m%d')");
                        if (selfDt.Rows.Count > 0)
                        {
                            function.WriteLog("统计人数:" + selfDt.Rows.Count + "\n\n", "实时执行企业交易额日志");
                            foreach (DataRow selfDr in selfDt.Rows)
                            {
                                int UserId = int.Parse(selfDr["UserId"].ToString());
                                int MerchantId = int.Parse(selfDr["MerchantId"].ToString());
                                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                                BusinessPartnerMerchant merchant = db.BusinessPartnerMerchant.FirstOrDefault(m => m.MerchantId == MerchantId) ?? new BusinessPartnerMerchant();
                                int PartnerId = merchant.PartnerId;
                                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 CapFlag = int.Parse(selfDr["CapFlag"].ToString());
                                int VipFlag = int.Parse(selfDr["VipFlag"].ToString());
                                int PayType = int.Parse(selfDr["PayType"].ToString());
                                string TradeDate = selfDr[9].ToString();
                                decimal TradeAmount = decimal.Parse(selfDr[10].ToString());
                                int TradeCount = int.Parse(selfDr[11].ToString());
                                string TradeMonth = TradeDate.Substring(0, 6);
                                BusinessTradeSummary selfStat = db.BusinessTradeSummary.FirstOrDefault(m => m.UserId == UserId && m.PartnerId == PartnerId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.VipFlag == VipFlag && m.PayType == PayType);
                                if (selfStat == null)
                                {
                                    selfStat = db.BusinessTradeSummary.Add(new BusinessTradeSummary()
                                    {
                                        UserId = UserId,
                                        PartnerId = PartnerId,
                                        TradeMonth = TradeMonth,
                                        TradeDate = TradeDate,
                                        BrandId = BrandId,
                                        QueryCount = QrPayFlag,
                                        VipFlag = VipFlag,
                                        PayType = PayType,
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                if (BankCardType == 0)
                                {
                                    if (MerHelpFlag == 1)
                                    {
                                        selfStat.HelpDirectDebitTradeAmt += TradeAmount;
                                        if (CapFlag == 1)
                                        {
                                            selfStat.HelpDirectDebitCapTradeAmt += TradeAmount;
                                            selfStat.HelpDirectDebitCapNum += TradeCount;
                                        }
                                    }
                                    else
                                    {
                                        selfStat.NotHelpDirectDebitTradeAmt += TradeAmount;
                                        if (CapFlag == 1)
                                        {
                                            selfStat.NotHelpDirectDebitCapTradeAmt += TradeAmount;
                                            selfStat.NotHelpDirectDebitCapNum += TradeCount;
                                        }
                                    }
                                }
                                else if (BankCardType != 0)
                                {
                                    if (MerHelpFlag == 1)
                                    {
                                        selfStat.HelpDirectTradeAmt += TradeAmount;
                                    }
                                    else
                                    {
                                        selfStat.NotHelpDirectTradeAmt += TradeAmount;
                                    }
                                }
                            }
                            OtherMySqlConn.op("update TradeRecord set QueryCount=2 where Id in (" + ids.TrimEnd(',') + ")");
                            function.WritePage("/TradeRecord/", "Id2.txt", startId);
                        }
                        db.SaveChanges();
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "实时执行企业交易额异常");
                }
            }
            db.Dispose();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "实时执行企业交易额日志");
        }



        // 统计创客激活数
        public void StartPosActNum()
        {
            Thread th = new Thread(StartPosActNumFor);
            th.IsBackground = true;
            th.Start();
        }
        public void StartPosActNumFor()
        {
            while (true)
            {
                if(DateTime.Now.Hour >= 3)
                {
                    StartPosActNumEverTime();
                }
                Thread.Sleep(120000);
            }
        }
        public void StartPosActNumEverTime()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "实时执行企业激活数日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                DataTable idsDt = OtherMySqlConn.dtable("select Id from PosMachinesTwo where QueryCount=1 and BuyUserId in (select Id from Users where BusinessFlag=1) and ActivationState=1 and ActivationTime is not null and ActivationTime>='2022-08-16 00:00:00' and BuyUserId>0 limit 50");
                if(idsDt.Rows.Count > 0)
                {
                    string ids = "";
                    foreach (DataRow idsDr in idsDt.Rows)
                    {
                        ids += idsDr["Id"].ToString() + ",";
                    }
                    DataTable userDt = OtherMySqlConn.dtable("select Id,BuyUserId,BrandId,ActivationTime from PosMachinesTwo where Id in (" + ids.TrimEnd(',') + ")");
                    if (userDt.Rows.Count > 0)
                    {
                        function.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "实时执行企业激活数日志");
                        foreach (DataRow userDr in userDt.Rows)
                        {
                            int Id = int.Parse(userDr["Id"].ToString());
                            int UserId = int.Parse(userDr["BuyUserId"].ToString());
                            int BrandId = int.Parse(userDr["BrandId"].ToString());
                            string TradeDate = DateTime.Parse(userDr["ActivationTime"].ToString()).ToString("yyyyMMdd");
                            int ActCount = 1;
                            string TradeMonth = TradeDate.Substring(0, 6);
                            string date = TradeDate.Substring(0, 4) + "-" + TradeDate.Substring(4, 2) + "-" + TradeDate.Substring(6, 2);
                            string start = date + " 00:00:00";
                            string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                            Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                            BusinessPartnerPos pos = db.BusinessPartnerPos.FirstOrDefault(m => m.PosId == Id) ?? new BusinessPartnerPos();
                            int PartnerId = pos.PartnerId;
                            BusinessActSummary selfStat = db.BusinessActSummary.FirstOrDefault(m => m.UserId == UserId && m.PartnerId == PartnerId && m.TradeMonth == TradeMonth && m.SeoKeyword == TradeDate && m.BrandId == BrandId);
                            if (selfStat == null)
                            {
                                selfStat = db.BusinessActSummary.Add(new BusinessActSummary()
                                {
                                    UserId = UserId,
                                    PartnerId = PartnerId,
                                    TradeMonth = TradeMonth,
                                    SeoKeyword = TradeDate,
                                    BrandId = BrandId,
                                }).Entity;
                                db.SaveChanges();
                            }
                            selfStat.ActCount += ActCount;
                        }
                        db.SaveChanges();
                        OtherMySqlConn.op("update PosMachinesTwo set QueryCount=2 where Id in (" + ids.TrimEnd(',') + ")");
                    }
                }
            }
            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", "实时执行企业激活数日志");
        }

        


    }
}