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


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

        // 每天统计头一天的交易额
        public void StartEverDay()
        {
            string chk = function.ReadInstance("/log/临时重置盛付通交易额.txt");
            if(string.IsNullOrEmpty(chk))
            {
                function.WritePage("/log/", "临时重置盛付通交易额.txt", DateTime.Now.ToString());
                OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
                DateTime end = DateTime.Parse("2022-06-23 00:00:00");
                DateTime check = DateTime.Parse("2022-06-14");
                while (check <= end)
                {
                    StatTradeAmountEverDay(check.ToString("yyyy-MM-dd"));
                    check = check.AddDays(1);
                    Thread.Sleep(1000);
                }
            }
        }
        public void StatTradeAmountEverDay(object sender)
        {
            string date = sender.ToString();
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "临时重置交易额日志");
            WebCMSEntities db = new WebCMSEntities();
            try
            {
                string TradeDate = date.Replace("-", "");
                string TradeMonth = TradeDate.Substring(0, 6);
                string start = date + " 00:00:00";
                string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                string startId = "0", endId = "9999999999";
                List<string> uids = new List<string>();
                DataTable startDt = OtherMySqlConn.dtable("select min(Id) from TradeRecord where CreateDate>='" + start + "'");
                if (startDt.Rows.Count > 0)
                {
                    startId = startDt.Rows[0][0].ToString();
                }
                function.WriteLog(startId + "\n\n", "临时重置交易额日志");
                DataTable userDt = OtherMySqlConn.dtable("select Id,ParentNav from Users where Id in (select DISTINCT UserId from TradeRecord where Id>=" + startId + " and Id<=" + endId + " and CreateDate>='" + start + "' and CreateDate<'" + end + "' and BrandId=7)");
                function.WriteLog("交易人数:" + userDt.Rows.Count + "\n\n", "临时重置交易额日志");
                foreach (DataRow userDr in userDt.Rows)
                {
                    int UserId = int.Parse(userDr["Id"].ToString());
                    string ParentNav = userDr["ParentNav"].ToString();
                    function.WriteLog(UserId + ":" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "临时重置交易额日志");
                    DataTable selfdt = OtherMySqlConn.dtable("select BrandId,BankCardType,QrPayFlag,sum(TradeAmount) from TradeRecord where Id>=" + startId + " and Id<=" + endId + " and CreateDate>='" + start + "' and CreateDate<'" + end + "' and UserId=" + UserId + " and BrandId=7 group by BrandId,BankCardType,QrPayFlag");
                    function.WriteLog(UserId + ":" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "临时重置交易额日志");
                    OtherMySqlConn.op("delete from UserTradeDaySummary where UserId=" + UserId + " and TradeMonth='" + TradeMonth + "' and TradeDate='" + TradeDate + "' and BrandId=7 and SeoTitle='self'");
                    foreach (DataRow selfDr in selfdt.Rows)
                    {
                        int BrandId = int.Parse(selfDr["BrandId"].ToString());
                        int BankCardType = int.Parse(selfDr["BankCardType"].ToString());
                        int QrPayFlag = int.Parse(selfDr["QrPayFlag"].ToString());
                        decimal TradeAmount = decimal.Parse(selfDr[3].ToString());
                        UserTradeDaySummary selfStat = db.UserTradeDaySummary.FirstOrDefault(m => m.UserId == UserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.SeoTitle == "self");
                        if (selfStat == null)
                        {
                            selfStat = db.UserTradeDaySummary.Add(new UserTradeDaySummary()
                            {
                                UserId = UserId,
                                TradeMonth = TradeMonth,
                                TradeDate = TradeDate,
                                BrandId = BrandId,
                                QueryCount = QrPayFlag,
                                SeoTitle = "self",
                            }).Entity;
                            db.SaveChanges();
                        }
                        if (BankCardType == 0)
                        {
                            selfStat.DirectDebitTradeAmt += TradeAmount;
                        }
                        else if (BankCardType != 0)
                        {
                            selfStat.DirectTradeAmt += TradeAmount;
                        }
                        db.SaveChanges();
                    }
                    if (!string.IsNullOrEmpty(ParentNav))
                    {
                        ParentNav += "," + UserId + ",";
                        string[] ParentNavList = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                        foreach (string NavUserIdString in ParentNavList)
                        {
                            if (!uids.Contains(NavUserIdString + start))
                            {
                                uids.Add(NavUserIdString + start);
                                int NavUserId = int.Parse(NavUserIdString);
                                function.WriteLog(NavUserId + ":team:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "临时重置交易额日志");
                                DataTable teamDt = OtherMySqlConn.dtable("select BrandId,BankCardType,QrPayFlag,sum(TradeAmount) from TradeRecord where Id>=" + startId + " and Id<=" + endId + " and CreateDate>='" + start + "' and CreateDate<'" + end + "' and UserId in (select Id from Users where ParentNav like '%," + NavUserId + ",%' or Id=" + NavUserId + ") and BrandId=7 group by BrandId,BankCardType,QrPayFlag");
                                function.WriteLog(NavUserId + ":team:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "临时重置交易额日志");
                                OtherMySqlConn.op("delete from UserTradeDaySummary where UserId=" + NavUserId + " and TradeMonth='" + TradeMonth + "' and TradeDate='" + TradeDate + "' and BrandId=7 and SeoTitle='team'");
                                foreach (DataRow teamDr in teamDt.Rows)
                                {
                                    int BrandId = int.Parse(teamDr["BrandId"].ToString());
                                    int BankCardType = int.Parse(teamDr["BankCardType"].ToString());
                                    int QrPayFlag = int.Parse(teamDr["QrPayFlag"].ToString());
                                    decimal TradeAmount = decimal.Parse(teamDr[3].ToString());
                                    UserTradeDaySummary teamStat = db.UserTradeDaySummary.FirstOrDefault(m => m.UserId == NavUserId && m.TradeMonth == TradeMonth && m.TradeDate == TradeDate && m.BrandId == BrandId && m.QueryCount == QrPayFlag && m.SeoTitle == "team");
                                    if (teamStat == null)
                                    {
                                        teamStat = db.UserTradeDaySummary.Add(new UserTradeDaySummary()
                                        {
                                            UserId = NavUserId,
                                            TradeMonth = TradeMonth,
                                            TradeDate = TradeDate,
                                            BrandId = BrandId,
                                            QueryCount = QrPayFlag,
                                            SeoTitle = "team",
                                        }).Entity;
                                        db.SaveChanges();
                                    }
                                    if (BankCardType == 0)
                                    {
                                        teamStat.NonDirectDebitTradeAmt += TradeAmount;
                                    }
                                    else if (BankCardType != 0)
                                    {
                                        teamStat.NonDirectTradeAmt += TradeAmount;
                                    }
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }
            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", "临时重置交易额日志");

            StatMerchantTrade(date);
        }

        

        //统计商户交易额
        private void StatMerchantTrade(string date)
        {
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "执行商户交易额日志");
            try
            {
                string TradeDate = date.Replace("-", "");
                string start = date + " 00:00:00";
                string end = DateTime.Parse(date).AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
                OtherMySqlConn.op("delete from PosMerchantTradeSummay where TradeDate='" + TradeDate + "' and BrandId=7");
                OtherMySqlConn.op("insert into PosMerchantTradeSummay (MerchantId,BrandId,TradeDate,TradeMonth,TradeAmount,CreateDate)  select *,now() from (select MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y%m%d') as TradeDate,DATE_FORMAT(CreateDate,'%Y%m') as TradeMonth,sum(TradeAmount) as TradeAmount from TradeRecord where CreateDate>='" + start + "' and CreateDate<'" + end + "' and BrandId=7 group by MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y%m%d'),TradeDate,DATE_FORMAT(CreateDate,'%Y%m') order by MerchantId,BrandId,DATE_FORMAT(CreateDate,'%Y%m%d')) tb");
                RedisDbconn.Instance.Clear("PosMerchantAmount:*");
                RedisDbconn.Instance.Clear("PosMerchantAmount:*:" + date.Replace("-", "").Substring(0, 6)); //商户当月交易
                RedisDbconn.Instance.Clear("PosMerchantAmount:*:" + date.Replace("-", "")); //商户当日交易
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "临时重置商户的交易额");
            }
            function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\n\n", "临时重置商户交易额日志");
        }



    }
}