using System;
using System.Collections.Generic;
using Library;
using LitJson;
using System.Linq;
using System.Data;
using System.Threading;
using MySystem.OpModels;

namespace MySystem
{
    public class OperateService
    {
        public readonly static OperateService Instance = new OperateService();
        private OperateService()
        { }



        public void Start()
        {
            Thread th = new Thread(StartDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartDo()
        {
            while (true)
            {
                if (RedisDbconn.Instance.Get<string>("StatServerStatus") == "1" && DateTime.Now.Hour >= 3)
                {
                    StatSendEverDay();
                }
                Thread.Sleep(30000);
            }
        }
        public void StatSendEverDay()
        {
            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("/SendStat/Id.txt");
                    if (string.IsNullOrEmpty(startId))
                    {
                        startId = "0";
                    }
                    DataTable idsDt = OtherMySqlConn.dtable("select Id from StoreStockChange where Id>=" + startId + " and CreateDate>='2022-12-19 00:00:00' and OpId>0 and Status=0 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 OpId,StoreId,TransType,DATE_FORMAT(CreateDate,'%Y%m%d'),count(Id) from StoreStockChange where Id in (" + ids.TrimEnd(',') + ") group by OpId,StoreId,TransType,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 OpId = int.Parse(selfDr["OpId"].ToString());
                                int StoreId = int.Parse(selfDr["StoreId"].ToString());
                                int TransType = int.Parse(selfDr["TransType"].ToString());
                                string TradeDate = selfDr[3].ToString();
                                string TradeMonth = TradeDate.Substring(0, 6);
                                int SendCount = int.Parse(selfDr[4].ToString());
                                if(TransType == 10 || TransType == 11)
                                {
                                    SendDaySummary selfStat = db.SendDaySummary.FirstOrDefault(m => m.OpId == OpId && m.TradeDate == TradeDate);
                                    if (selfStat == null)
                                    {
                                        selfStat = db.SendDaySummary.Add(new SendDaySummary()
                                        {
                                            TradeDate = TradeDate,
                                            OpId = OpId,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    selfStat.SendCount += SendCount;

                                    SendMonthSummary monthStat = db.SendMonthSummary.FirstOrDefault(m => m.OpId == OpId && m.TradeMonth == TradeMonth);
                                    if (monthStat == null)
                                    {
                                        monthStat = db.SendMonthSummary.Add(new SendMonthSummary()
                                        {
                                            TradeMonth = TradeMonth,
                                            OpId = OpId,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    monthStat.SendCount += SendCount;
                                    
                                    StoreSendDaySummary selfStoreStat = db.StoreSendDaySummary.FirstOrDefault(m => m.OpId == StoreId && m.TradeDate == TradeDate);
                                    if (selfStoreStat == null)
                                    {
                                        selfStoreStat = db.StoreSendDaySummary.Add(new StoreSendDaySummary()
                                        {
                                            TradeDate = TradeDate,
                                            OpId = StoreId,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    selfStoreStat.SendCount += SendCount;

                                    StoreSendMonthSummary monthStoreStat = db.StoreSendMonthSummary.FirstOrDefault(m => m.OpId == StoreId && m.TradeMonth == TradeMonth);
                                    if (monthStoreStat == null)
                                    {
                                        monthStoreStat = db.StoreSendMonthSummary.Add(new StoreSendMonthSummary()
                                        {
                                            TradeMonth = TradeMonth,
                                            OpId = StoreId,
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    monthStoreStat.SendCount += SendCount;
                                }
                            }
                            OtherMySqlConn.op("update StoreStockChange set Status=1 where Id in (" + ids.TrimEnd(',') + ")");
                            function.WritePage("/SendStat/", "Id.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(RedisDbconn.Instance.Get<string>("StatServerStatus") == "1" && 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 ActivationState=1 and ActivationTime is not null and ActivationTime>='2022-12-19 00:00:00' and OpId>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 OpId,StoreId,DATE_FORMAT(ActivationTime, '%Y%m%d'),count(Id) from PosMachinesTwo where Id in (" + ids.TrimEnd(',') + ") group by OpId,StoreId,DATE_FORMAT(ActivationTime, '%Y%m%d')");
                    if (userDt.Rows.Count > 0)
                    {
                        function.WriteLog("人数:" + userDt.Rows.Count + "\n\n", "运营中心激活数日志");
                        foreach (DataRow userDr in userDt.Rows)
                        {
                            int OpId = int.Parse(userDr["OpId"].ToString());
                            int StoreId = int.Parse(userDr["StoreId"].ToString());
                            string TradeDate = userDr[2].ToString();
                            int ActCount = int.Parse(function.CheckInt(userDr[3].ToString()));
                            string TradeMonth = TradeDate.Substring(0, 6);
                            ActMerDaySummary selfStat = db.ActMerDaySummary.FirstOrDefault(m => m.OpId == OpId && m.TradeDate == TradeDate);
                            if (selfStat == null)
                            {
                                selfStat = db.ActMerDaySummary.Add(new ActMerDaySummary()
                                {
                                    OpId = OpId,
                                    TradeDate = TradeDate,
                                }).Entity;
                                db.SaveChanges();
                            }
                            selfStat.ActCount += ActCount;

                            ActMerMonthSummary monthStat = db.ActMerMonthSummary.FirstOrDefault(m => m.OpId == OpId && m.TradeMonth == TradeMonth);
                            if (monthStat == null)
                            {
                                monthStat = db.ActMerMonthSummary.Add(new ActMerMonthSummary()
                                {
                                    OpId = OpId,
                                    TradeMonth = TradeMonth,
                                }).Entity;
                                db.SaveChanges();
                            }
                            monthStat.ActCount += ActCount;

                            StoreActMerDaySummary selfStat2 = db.StoreActMerDaySummary.FirstOrDefault(m => m.OpId == StoreId && m.TradeDate == TradeDate);
                            if (selfStat2 == null)
                            {
                                selfStat2 = db.StoreActMerDaySummary.Add(new StoreActMerDaySummary()
                                {
                                    OpId = StoreId,
                                    TradeDate = TradeDate,
                                }).Entity;
                                db.SaveChanges();
                            }
                            selfStat2.ActCount += ActCount;

                            StoreActMerMonthSummary monthStat2 = db.StoreActMerMonthSummary.FirstOrDefault(m => m.OpId == StoreId && m.TradeMonth == TradeMonth);
                            if (monthStat2 == null)
                            {
                                monthStat2 = db.StoreActMerMonthSummary.Add(new StoreActMerMonthSummary()
                                {
                                    OpId = StoreId,
                                    TradeMonth = TradeMonth,
                                }).Entity;
                                db.SaveChanges();
                            }
                            monthStat2.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", "运营中心激活数日志");
        }


        // 统计运营中心机具券销售量
        public void StartPosCouponSaleNum()
        {
            Thread th = new Thread(StartPosCouponSaleNumFor);
            th.IsBackground = true;
            th.Start();
        }
        public void StartPosCouponSaleNumFor()
        {
            while (true)
            {
                if(RedisDbconn.Instance.Get<string>("StatServerStatus") == "1" && DateTime.Now.Hour >= 3)
                {
                    StartPosCouponSaleNumEverTime();
                }
                Thread.Sleep(120000);
            }
        }
        public void StartPosCouponSaleNumEverTime()
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "运营中心机具券销售量日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string startId = function.ReadInstance("/SaleStat/Id.txt");
                if (string.IsNullOrEmpty(startId))
                {
                    startId = "0";
                }
                DataTable idsDt = OtherMySqlConn.dtable("select Id from PosCoupons where Id>=" + startId + " and CreateDate>='2022-12-19 00:00:00' and OpId>0 and Status=0 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 OpId,DATE_FORMAT(CreateDate,'%Y%m%d'),count(Id) from PosCoupons where Id in (" + ids.TrimEnd(',') + ") group by OpId,DATE_FORMAT(CreateDate,'%Y%m%d')");
                    if (selfDt.Rows.Count > 0)
                    {
                        function.WriteLog("人数:" + selfDt.Rows.Count + "\n\n", "运营中心机具券销售量日志");
                        foreach (DataRow userDr in selfDt.Rows)
                        {
                            int OpId = int.Parse(userDr["OpId"].ToString());
                            string TradeDate = userDr[1].ToString();
                            int SaleCount = int.Parse(function.CheckInt(userDr[2].ToString()));
                            string TradeMonth = TradeDate.Substring(0, 6);
                            PosCouponDaySummary selfStat = db.PosCouponDaySummary.FirstOrDefault(m => m.OpId == OpId && m.TradeDate == TradeDate);
                            if (selfStat == null)
                            {
                                selfStat = db.PosCouponDaySummary.Add(new PosCouponDaySummary()
                                {
                                    OpId = OpId,
                                    TradeDate = TradeDate,
                                }).Entity;
                                db.SaveChanges();
                            }
                            selfStat.SaleCount += SaleCount;

                            PosCouponMonthSummary monthStat = db.PosCouponMonthSummary.FirstOrDefault(m => m.OpId == OpId && m.TradeMonth == TradeMonth);
                            if (monthStat == null)
                            {
                                monthStat = db.PosCouponMonthSummary.Add(new PosCouponMonthSummary()
                                {
                                    OpId = OpId,
                                    TradeMonth = TradeMonth,
                                }).Entity;
                                db.SaveChanges();
                            }
                            monthStat.SaleCount += SaleCount;
                        }
                        db.SaveChanges();
                        OtherMySqlConn.op("update PosCoupons set Status=1 where Id in (" + ids.TrimEnd(',') + ")");
                        function.WritePage("/SaleStat/", "Id.txt", startId);
                    }
                }
            }
            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", "运营中心机具券销售量日志");
        }

    }
}