using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using MySystem.Models;
using Library;

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

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

        public void doSomething()
        { 
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ResetUserTradeQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
                        WebCMSEntities db = new WebCMSEntities();
                        string[] datalist = content.Split(new string[] { "#cut#" }, StringSplitOptions.None);
                        int UserId = int.Parse(datalist[0]);
                        DateTime sdate = DateTime.Parse(datalist[1]);
                        DateTime edate = DateTime.Parse(datalist[2]);
                        int BrandId = int.Parse(datalist[3]);
                        function.WriteLog(DateTime.Now.ToString(), "重置创客交易额");
                        List<string> uids = new List<string>();
                        DataTable userDt = OtherMySqlConn.dtable("select Id,ParentNav from Users where Id=" + UserId);
                        if (userDt.Rows.Count > 0)
                        {
                            while (sdate <= edate)
                            {
                                string date = sdate.ToString("yyyy-MM-dd");
                                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";
                                DataRow userDr = userDt.Rows[0];
                                string ParentNav = userDr["ParentNav"].ToString();
                                OtherMySqlConn.op("delete from UserTradeDaySummary where UserId=" + UserId + " and BrandId=" + BrandId + " and TradeMonth='" + TradeMonth + "' and TradeDate='" + TradeDate + "' and SeoTitle='self'");
                                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=" + BrandId + " group by BrandId,BankCardType,QrPayFlag");
                                foreach (DataRow selfDr in selfdt.Rows)
                                {
                                    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);
                                            OtherMySqlConn.op("delete from UserTradeDaySummary where UserId=" + NavUserId + " and BrandId=" + BrandId + " and TradeMonth='" + TradeMonth + "' and TradeDate='" + TradeDate + "' and SeoTitle='team'");
                                            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=" + BrandId + " group by BrandId,BankCardType,QrPayFlag");
                                            foreach (DataRow teamDr in teamDt.Rows)
                                            {
                                                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();
                                            }
                                        }
                                    }
                                }
                                sdate = sdate.AddDays(1);
                                Thread.Sleep(200);
                            }
                        }
                        db.Dispose();
                        function.WriteLog(DateTime.Now.ToString() + "\r\n\r\n", "重置创客交易额");
                    }
                    catch (Exception ex)
                    {
                        function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "重置创客交易额异常");
                    }
                }
                else
                {
                    Thread.Sleep(5000);
                }
            }
        }
    }
}