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

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

        public void Start()//启动
        {
            Thread thread = new Thread(Listen);
            thread.IsBackground = true;
            thread.Start();
        }

        public void Listen()//启动
        {
            while(true)
            {
                if(DateTime.Now.Hour > 0 && DateTime.Now.Hour < 23)
                {
                    
                    string check = function.ReadInstance("/LeaderComp/" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
                    if(string.IsNullOrEmpty(check))
                    {
                        function.WritePage("/LeaderComp/", DateTime.Now.ToString("yyyyMMdd") + ".txt", DateTime.Now.ToString());
                        // if(DateTime.Now.Day == 1)
                        // {
                        //     Ready(DateTime.Now.AddMonths(-1).ToString("yyyy-MM"));
                        //     Thread.Sleep(2000);
                        //     CustomerSqlConn.op("insert into LeaderCompTradeStatBak select * from LeaderCompTradeStat;insert into LeaderCompTmpBak select * from LeaderCompTmp;insert into LeaderCompPrizeBak select * from LeaderCompPrize;insert into LeaderCompAddTradeBak select * from LeaderCompAddTrade;", MysqlConn.SqlConnStr);
                        // }
                        // // Ready(DateTime.Now.ToString("yyyy-MM"));
                        Ready(DateTime.Now.ToString("yyyyMM"));
                    }
                }
                Thread.Sleep(60000);
            }
        }

        public void Ready(string curMonth)
        {
            CustomerSqlConn.op("delete from LeaderCompTradeStat;delete from LeaderCompTmp;delete from LeaderCompPrize;delete from LeaderCompAddTrade;", MysqlConn.SqlConnStr);
            // Thread.Sleep(10000);
            // DateTime Start = DateTime.Parse("2023-06-01 00:00:00");
            // DateTime now = DateTime.Parse(curMonth + "-01 00:00:00");
            // while(now > Start)
            // {
            //     string month = now.ToString("yyyyMM");
            //     string checkMonth = Start.ToString("yyyyMM");
            //     doSomething(month, checkMonth);
            //     now = now.AddMonths(-1);
            // }
            // now = DateTime.Parse(curMonth + "-01 00:00:00");
            // while(now > Start)
            // {
            //     string month = now.ToString("yyyyMM");
            //     string checkMonth = Start.ToString("yyyyMM");
            //     SendPrize(month, checkMonth);
            //     now = now.AddMonths(-1);
            // }
            doSomething(curMonth, curMonth);
            SendPrize(curMonth, curMonth);
        }

        public void doSomething(string month, string checkMonth)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
                MpMainModels.WebCMSEntities mpmaindb = new MpMainModels.WebCMSEntities();
                MpMainModels2.WebCMSEntities mpmaindb2 = new MpMainModels2.WebCMSEntities();
                string MonthString = month + "-" + checkMonth;

                //统计交易增量
                function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");


                
                //创客团队交易额
                string sql = "";
                int num = 0;
                DataTable dt = CustomerSqlConn.dtable("select UserId,sum(HelpNonDirectTradeAmt + NotHelpNonDirectTradeAmt + ProfitNonDirectTradeAmt + HelpNonDirectDebitTradeAmt + NotHelpNonDirectDebitTradeAmt + ProfitNonDirectDebitTradeAmt) Amt from TradeDaySummary where Id>=15055757 and TradeMonth='" + month + "' and SeoTitle='team' and UserId>0 group by UserId", MysqlConn.ReadSqlConnStr);
                foreach(DataRow dr in dt.Rows)
                {
                    int UserId = int.Parse(dr["UserId"].ToString());
                    decimal TradeAmount = decimal.Parse(dr["Amt"].ToString());
                    //码牌团队交易额（直联）
                    bool check = mpmaindb.UserAmountSummary.Any(m => m.UserId == UserId && m.TradeMonth == month && m.SeoTitle == "team" && m.IsAct == 1);
                    if (check)
                    {
                        TradeAmount += mpmaindb.UserAmountSummary.Where(m => m.UserId == UserId && m.TradeMonth == month && m.SeoTitle == "team" && m.IsAct == 1).Sum(m => m.TotalAmount) * 4;
                    }
                    check = mpmaindb.UserAmountSummary.Any(m => m.UserId == UserId && m.TradeMonth == month && m.SeoTitle == "team" && m.IsAct == 1);
                    if (check)
                    {
                        TradeAmount += mpmaindb.UserAmountSummary.Where(m => m.UserId == UserId && m.TradeMonth == month && m.SeoTitle == "team" && m.IsAct == 1).Sum(m => m.TotalAmount);
                    }
                    //码牌团队交易额（银联）
                    check = mpmaindb2.UserAmountSummary.Any(m => m.UserId == UserId && m.TradeMonth == month && m.SeoTitle == "team" && m.IsAct == 1);
                    if (check)
                    {
                        TradeAmount += mpmaindb2.UserAmountSummary.Where(m => m.UserId == UserId && m.TradeMonth == month && m.SeoTitle == "team" && m.IsAct == 1).Sum(m => m.TotalAmount) * 4;
                    }
                    check = mpmaindb2.UserAmountSummary.Any(m => m.UserId == UserId && m.TradeMonth == month && m.SeoTitle == "team" && m.IsAct == 1);
                    if (check)
                    {
                        TradeAmount += mpmaindb2.UserAmountSummary.Where(m => m.UserId == UserId && m.TradeMonth == month && m.SeoTitle == "team" && m.IsAct == 1).Sum(m => m.TotalAmount);
                    }
                    //广电卡扶持期按1万/张计入职级
                    check = db.UserTradeMonthSummary.Any(m => m.UserId == UserId && m.TradeMonth == month && m.SeoTitle == "team" && m.BrandId == 14);
                    if (check)
                    {
                        TradeAmount += db.UserTradeMonthSummary.Where(m => m.UserId == UserId && m.TradeMonth == month && m.SeoTitle == "team" && m.BrandId == 14).Sum(m => m.ActiveBuddyMerStatus) * 10000;
                    }
                    sql += "insert into LeaderCompTradeStat (CreateDate,UserId,StatMonth,TradeAmount) values (now(), " + UserId + ", '" + month + "-" + checkMonth + "', " + TradeAmount + ");\n";
                    num += 1;
                    if(num >= 200)
                    {
                        CustomerSqlConn.op(sql, MysqlConn.SqlConnStr);
                        sql = "";
                        num = 0;
                    }
                }


                // DataTable dt = CustomerSqlConn.dtable("select CONCAT('insert into LeaderCompTradeStat (CreateDate,UserId,StatMonth,TradeAmount,SelfTradeAmount,CheckTradeAmount,CheckSelfTradeAmount) values (now(),', UserId,',\\\'" + month + "-" + checkMonth + "\\\',', amt" + month + ",',', samt" + month + ",',', amt" + checkMonth + ",',', samt" + checkMonth + ",');') from (select UserId,(case when amt" + month + " is null then 0 else amt" + month + " end) amt" + month + ",(case when samt" + month + " is null then 0 else samt" + month + " end) samt" + month + ",(case when amt" + checkMonth + " is null then 0 else amt" + checkMonth + " end) amt" + checkMonth + ",(case when samt" + checkMonth + " is null then 0 else samt" + checkMonth + " end) samt" + checkMonth + " from (select UserId,sum(HelpNonDirectTradeAmt + NotHelpNonDirectTradeAmt + ProfitNonDirectTradeAmt + HelpNonDirectDebitTradeAmt + NotHelpNonDirectDebitTradeAmt + ProfitNonDirectDebitTradeAmt) amt" + month + ",(select sum(HelpNonDirectTradeAmt + NotHelpNonDirectTradeAmt + ProfitNonDirectTradeAmt + HelpNonDirectDebitTradeAmt + NotHelpNonDirectDebitTradeAmt + ProfitNonDirectDebitTradeAmt) from TradeDaySummary" + checkMonth + " where SeoTitle='team' and UserId=main.UserId) amt" + checkMonth + ",(select sum(HelpDirectTradeAmt + NotHelpDirectTradeAmt + ProfitDirectTradeAmt + HelpDirectDebitTradeAmt + NotHelpDirectDebitTradeAmt + ProfitDirectDebitTradeAmt) from TradeDaySummary" + month + " where SeoTitle='self' and UserId=main.UserId) samt" + month + ",(select sum(HelpDirectTradeAmt + NotHelpDirectTradeAmt + ProfitDirectTradeAmt + HelpDirectDebitTradeAmt + NotHelpDirectDebitTradeAmt + ProfitDirectDebitTradeAmt) from TradeDaySummary" + checkMonth + " where SeoTitle='self' and UserId=main.UserId) samt" + checkMonth + " from TradeDaySummary" + month + " main where SeoTitle='team' and UserId>0 group by UserId) tb) tb2", MysqlConn.RdsStatSqlConnStr);


                if(!string.IsNullOrEmpty(sql))
                {
                    CustomerSqlConn.op(sql, MysqlConn.SqlConnStr);
                }
                CustomerSqlConn.op("update LeaderCompTradeStat leader set ParentUserId=case when (select ParentUserId from Users where Id=leader.UserId) is null then 0 else (select ParentUserId from Users where Id=leader.UserId) end,ParentNav=(select ParentNav from Users where Id=leader.UserId) where StatMonth='" + MonthString + "' and UserId>1", MysqlConn.SqlConnStr);

                function.WriteLog("start-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");

                //计算创客名下的达标人数，直推和间接
                function.WriteLog("MonthString:" + MonthString, "领导人达标奖励日志");
                
                // DataTable stats = CustomerSqlConn.dtable("select SelfTradeAmount-CheckSelfTradeAmount from LeaderCompTradeStat p where StatMonth='" + MonthString + "'", MysqlConn.SqlConnStr);

                List<LeaderCompTradeStat> stats = db.LeaderCompTradeStat.Where(m => m.StatMonth == MonthString).ToList();
                function.WriteLog(stats.Count.ToString(), "领导人达标奖励日志");
                foreach(LeaderCompTradeStat stat in stats)
                {
                    function.WriteLog("1-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                    decimal totalAmount = stat.TradeAmount; // - stat.CheckSelfTradeAmount; //当月交易
                    // List<LeaderCompTradeStat> directs = stats.Where(m => m.ParentUserId == stat.UserId).ToList();
                    // foreach(LeaderCompTradeStat direct in directs)
                    // {
                    //     decimal parentTotalAmount = direct.TradeAmount - direct.CheckTradeAmount;
                    //     if(parentTotalAmount < 30000000)
                    //     {
                    //         totalAmount += parentTotalAmount;
                    //     }
                    // }
                    // DataTable directs = CustomerSqlConn.dtable("select sum(TradeAmount) from LeaderCompTradeStat where ParentUserId=" + stat.UserId + " and StatMonth='" + MonthString + "' and TradeAmount<30000000", MysqlConn.SqlConnStr);
                    // function.WriteLog("2-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                    // if(directs.Rows.Count > 0)
                    // {
                    //     totalAmount += decimal.Parse(function.CheckNum(directs.Rows[0][0].ToString()));
                    // }

                    function.WriteLog("UserId:" + stat.UserId, "领导人达标奖励日志");
                    function.WriteLog("totalAmount:" + totalAmount, "领导人达标奖励日志");
                    function.WriteLog("3-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                    LeaderCompTradeStat statEdit = db.LeaderCompTradeStat.FirstOrDefault(m => m.UserId == stat.UserId && m.StatMonth == MonthString);
                    if(statEdit != null)
                    {
                        statEdit.ResultTradeAmount = totalAmount;
                        // db.SaveChanges();
                    }
                    if(totalAmount >= 30000000 && !string.IsNullOrEmpty(stat.ParentNav))
                    {
                        function.WriteLog("4-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                        LeaderCompTmp tmp = db.LeaderCompTmp.FirstOrDefault(m => m.Id == stat.UserId);
                        if(tmp == null)
                        {
                            tmp = db.LeaderCompTmp.Add(new LeaderCompTmp()
                            {
                                Id = stat.UserId,
                                ParentUserId = stat.ParentUserId,
                                ParentNav = stat.ParentNav
                            }).Entity;
                            db.SaveChanges();
                        }
                        Dictionary<string, object> EveryMonthData = new Dictionary<string, object>();
                        if(!string.IsNullOrEmpty(tmp.EveryMonthData))
                        {
                            EveryMonthData = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(tmp.EveryMonthData);
                        }
                        if(!EveryMonthData.ContainsKey(MonthString))
                        {
                            EveryMonthData.Add(MonthString, 1);
                        }
                        else
                        {
                            EveryMonthData[MonthString] = 1;
                        }
                        tmp.EveryMonthData = Newtonsoft.Json.JsonConvert.SerializeObject(EveryMonthData);
                        db.SaveChanges();
                        function.WriteLog("5-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                        string[] parents = stat.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                        Array.Reverse(parents);
                        int index = 0;
                        foreach(string parent in parents)
                        {
                            index += 1;
                            int ParentUserId = int.Parse(function.CheckInt(parent));
                            LeaderCompPrize prize = db.LeaderCompPrize.FirstOrDefault(m => m.UserId == ParentUserId && m.StatMonth == MonthString);
                            if(prize == null)
                            {
                                Users user = db.Users.FirstOrDefault(m => m.Id == ParentUserId) ?? new Users();
                                prize = db.LeaderCompPrize.Add(new LeaderCompPrize()
                                {
                                    CreateDate = DateTime.Now,
                                    UserId = ParentUserId,
                                    ParentUserId = user.ParentUserId,
                                    ParentNav = user.ParentNav,
                                    StatMonth = MonthString,
                                }).Entity;
                                db.SaveChanges();
                            }
                            if(index == 1)
                            {
                                prize.DirectCount += 1;
                            }
                            else
                            {
                                prize.NotDirectCount += 1;
                            }
                            db.SaveChanges();
                        }
                        function.WriteLog("6-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                    }
                    // LeaderCompAddTrade addTrade = db.LeaderCompAddTrade.FirstOrDefault(m => m.UserId == stat.UserId && m.StatMonth == MonthString);
                    // if(addTrade == null)
                    // {
                    //     addTrade = db.LeaderCompAddTrade.Add(new LeaderCompAddTrade()
                    //     {
                    //         CreateDate = DateTime.Now,
                    //         UserId = stat.UserId,
                    //         StatMonth = MonthString,
                    //     }).Entity;
                    //     db.SaveChanges();
                    // }
                    // addTrade.AddTradeAmount = totalAmount < 0 ? 0 : totalAmount;
                    // db.SaveChanges();
                    function.WriteLog("7-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                    function.WriteLog(DateTime.Now.ToString() + "------" + stat.UserId, "领导人达标奖励日志");
                }
                db.SaveChanges();
                opdb.Dispose();
                mpmaindb.Dispose();
                mpmaindb2.Dispose();
                function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");
                
                CustomerSqlConn.op("insert into LeaderCompAddTrade (UserId,StatMonth,CreateDate,AddTradeAmount) select UserId,StatMonth,now(),ResultTradeAmount from LeaderCompTradeStat where ResultTradeAmount>0 and StatMonth='" + MonthString + "'", MysqlConn.SqlConnStr);
                
                CustomerSqlConn.op("update LeaderCompTradeStat set ResultTradeAmount=0 where ResultTradeAmount<30000000 and StatMonth='" + MonthString + "'", MysqlConn.SqlConnStr);
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "领导达标人奖励异常");
            }
        }

        private void SendPrize(string month, string checkDate)
        {
            string MonthFlag = month + "-" + checkDate;
            function.WriteLog("发放奖励" + MonthFlag, "领导人达标奖励日志");
            WebCMSEntities db = new WebCMSEntities();
            OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
            //计算运营中心或大盟主达标奖励
            List<LeaderCompPrize> leaderPrizes = db.LeaderCompPrize.Where(m => m.StatMonth == MonthFlag).ToList();
            function.WriteLog(leaderPrizes.Count.ToString(), "领导人达标奖励日志");
            foreach(LeaderCompPrize leaderPrize in leaderPrizes)
            {
                function.WriteLog("发放人" + leaderPrize.UserId, "领导人达标奖励日志");
                Users user = db.Users.FirstOrDefault(m => m.Id == leaderPrize.UserId) ?? new Users();
                // if(user.UserType == 1)
                // {
                //     OpModels.SysAdmin opSys = opdb.SysAdmin.FirstOrDefault(m => m.UserId == user.Id);
                //     if(opSys != null)
                //     {
                //         checkDate = opSys.CreateDate.Value.AddMonths(-1).ToString("yyyyMM");
                //     }
                // }
                // else if(user.LeaderLevel == 2)
                // {
                //     Leaders leader = db.Leaders.FirstOrDefault(m => m.Id == user.Id);
                //     if(leader != null)
                //     {
                //         checkDate = leader.LastBuyDate.Value.AddMonths(-1).ToString("yyyyMM");
                //     }
                // }
                string CheckJson = "\"" + MonthFlag + "\":1";
                function.WriteLog("CheckJson：" + CheckJson, "领导人达标奖励日志");
                string NavUserId = "," + user.Id + ",";
                int person = 0;
                int directPerson = 0;
                int totalPerson = db.LeaderCompTmp.Count(m => (m.ParentNav.Contains(NavUserId)) && m.EveryMonthData.Contains(CheckJson));
                var subusers = db.Users.Select(m => new { m.Id, m.ParentUserId }).Where(m => m.ParentUserId == user.Id).ToList();
                foreach(var subuser in subusers)
                {
                    string subNavUserId = "," + subuser.Id + ",";
                    function.WriteLog("------subNavUserId：" + subNavUserId, "领导人达标奖励日志");
                    if(db.LeaderCompTmp.Count(m => (m.ParentNav.Contains(subNavUserId) || m.Id == subuser.Id) && m.EveryMonthData.Contains(CheckJson)) > 0)
                    {
                        person += 1;
                    }
                    if(db.LeaderCompTmp.Any(m => m.Id == subuser.Id && m.EveryMonthData.Contains(CheckJson)))
                    {
                        directPerson += 1;
                    }
                }
                function.WriteLog("directPerson：" + directPerson, "领导人达标奖励日志");
                function.WriteLog("person" + person, "领导人达标奖励日志");
                function.WriteLog("totalPerson" + totalPerson, "领导人达标奖励日志");

                int maxPerson = person * person;
                decimal CompPrize = 0;
                if(totalPerson >= maxPerson)
                {
                    CompPrize = GetPrize(maxPerson - person, person);
                }
                else
                {
                    CompPrize = GetPrize(totalPerson - person, person);
                }

                LeaderCompPrize edit = db.LeaderCompPrize.FirstOrDefault(m => m.StatMonth == MonthFlag && m.UserId == leaderPrize.UserId);
                if(edit != null)
                {
                    edit.DirectCount = directPerson;
                    edit.NotDirectCount = totalPerson - person;
                    edit.SecDirectCount = person;
                    edit.CompPrize = CompPrize;
                    function.WriteLog("已设置", "领导人达标奖励日志");
                }
                db.SaveChanges();
            }
            function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");
            db.Dispose();
            opdb.Dispose();
        }

        private decimal GetPrize(int count, int direct)
        {
            decimal prize = 0;
            // if (count + direct >= 30)
            // {
            //     prize = 3000 * (count + direct * 2);
            // }
            // else if (count + direct >= 25)
            // {
            //     prize = 2500 * (count + direct * 2);
            // }
            // else if (count + direct >= 20)
            // {
            //     prize = 2000 * (count + direct * 2);
            // }
            // else if (count + direct >= 15)
            // {
            //     prize = 1500 * (count + direct * 2);
            // }
            // else if (count + direct >= 10)
            // {
            //     prize = 1000 * (count + direct * 2);
            // }
            // else if (count + direct >= 5)
            // {
            //     prize = 500 * (count + direct * 2);
            // }
            prize = 500 * count;
            return prize;
        }
    
    
    
    
    
    
    
    
    
        public void doEverday(string month, string checkMonth)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
                string MonthString = month + "-" + checkMonth;

                //统计交易增量
                function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");
                DataTable dt = CustomerSqlConn.dtable("select CONCAT('insert into LeaderCompTradeStatBak (CreateDate,UserId,StatMonth,TradeAmount,SelfTradeAmount,CheckTradeAmount,CheckSelfTradeAmount) values (now(),', UserId,',\\\'" + month + "-" + checkMonth + "\\\',', amt" + month + ",',', samt" + month + ",',', amt" + checkMonth + ",',', samt" + checkMonth + ",');') from (select UserId,(case when amt" + month + " is null then 0 else amt" + month + " end) amt" + month + ",(case when samt" + month + " is null then 0 else samt" + month + " end) samt" + month + ",(case when amt" + checkMonth + " is null then 0 else amt" + checkMonth + " end) amt" + checkMonth + ",(case when samt" + checkMonth + " is null then 0 else samt" + checkMonth + " end) samt" + checkMonth + " from (select UserId,sum(HelpNonDirectTradeAmt + NotHelpNonDirectTradeAmt + ProfitNonDirectTradeAmt + HelpNonDirectDebitTradeAmt + NotHelpNonDirectDebitTradeAmt + ProfitNonDirectDebitTradeAmt) amt" + month + ",(select sum(HelpNonDirectTradeAmt + NotHelpNonDirectTradeAmt + ProfitNonDirectTradeAmt + HelpNonDirectDebitTradeAmt + NotHelpNonDirectDebitTradeAmt + ProfitNonDirectDebitTradeAmt) from TradeDaySummary" + checkMonth + " where SeoTitle='team' and UserId=main.UserId) amt" + checkMonth + ",(select sum(HelpDirectTradeAmt + NotHelpDirectTradeAmt + ProfitDirectTradeAmt + HelpDirectDebitTradeAmt + NotHelpDirectDebitTradeAmt + ProfitDirectDebitTradeAmt) from TradeDaySummary" + month + " where SeoTitle='self' and UserId=main.UserId) samt" + month + ",(select sum(HelpDirectTradeAmt + NotHelpDirectTradeAmt + ProfitDirectTradeAmt + HelpDirectDebitTradeAmt + NotHelpDirectDebitTradeAmt + ProfitDirectDebitTradeAmt) from TradeDaySummary" + checkMonth + " where SeoTitle='self' and UserId=main.UserId) samt" + checkMonth + " from TradeDaySummary" + month + " main where SeoTitle='team' and UserId>0 group by UserId) tb) tb2", MysqlConn.RdsStatSqlConnStr);
                string sql = "";
                int num = 0;
                foreach(DataRow dr in dt.Rows)
                {
                    sql += dr[0].ToString();
                    num += 1;
                    if(num >= 200)
                    {
                        CustomerSqlConn.op(sql, MysqlConn.SqlConnStr);
                        sql = "";
                        num = 0;
                    }
                }
                if(!string.IsNullOrEmpty(sql))
                {
                    CustomerSqlConn.op(sql, MysqlConn.SqlConnStr);
                }
                CustomerSqlConn.op("update LeaderCompTradeStatBak leader set ParentUserId=case when (select ParentUserId from Users where Id=leader.UserId) is null then 0 else (select ParentUserId from Users where Id=leader.UserId) end,ParentNav=(select ParentNav from Users where Id=leader.UserId) where StatMonth='" + month + "-" + checkMonth + "' and UserId>1", MysqlConn.SqlConnStr);

                function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");

                //计算创客名下的达标人数，直推和间接
                function.WriteLog("MonthString:" + MonthString, "领导人达标奖励日志");
                List<LeaderCompTradeStatBak> stats = db.LeaderCompTradeStatBak.Where(m => m.StatMonth == MonthString).ToList();
                function.WriteLog(stats.Count.ToString(), "领导人达标奖励日志");
                foreach(LeaderCompTradeStatBak stat in stats)
                {
                    decimal totalAmount = stat.SelfTradeAmount - stat.CheckSelfTradeAmount; //当月交易
                    List<LeaderCompTradeStatBak> directs = stats.Where(m => m.ParentUserId == stat.UserId).ToList();
                    foreach(LeaderCompTradeStatBak direct in directs)
                    {
                        decimal parentTotalAmount = direct.TradeAmount - direct.CheckTradeAmount;
                        if(parentTotalAmount < 30000000)
                        {
                            totalAmount += parentTotalAmount;
                        }
                    }
                    function.WriteLog("UserId:" + stat.UserId, "领导人达标奖励日志");
                    function.WriteLog("totalAmount:" + totalAmount, "领导人达标奖励日志");
                    if(totalAmount >= 30000000 && !string.IsNullOrEmpty(stat.ParentNav))
                    {
                        LeaderCompTradeStatBak statEdit = db.LeaderCompTradeStatBak.FirstOrDefault(m => m.UserId == stat.UserId && m.StatMonth == MonthString);
                        if(statEdit != null)
                        {
                            statEdit.ResultTradeAmount = totalAmount;
                            db.SaveChanges();
                        }
                        LeaderCompTmpBak tmp = db.LeaderCompTmpBak.FirstOrDefault(m => m.Id == stat.UserId);
                        if(tmp == null)
                        {
                            tmp = db.LeaderCompTmpBak.Add(new LeaderCompTmpBak()
                            {
                                Id = stat.UserId,
                                ParentUserId = stat.ParentUserId,
                                ParentNav = stat.ParentNav
                            }).Entity;
                            db.SaveChanges();
                        }
                        Dictionary<string, object> EveryMonthData = new Dictionary<string, object>();
                        if(!string.IsNullOrEmpty(tmp.EveryMonthData))
                        {
                            EveryMonthData = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(tmp.EveryMonthData);
                        }
                        if(!EveryMonthData.ContainsKey(MonthString))
                        {
                            EveryMonthData.Add(MonthString, 1);
                        }
                        else
                        {
                            EveryMonthData[MonthString] = 1;
                        }
                        tmp.EveryMonthData = Newtonsoft.Json.JsonConvert.SerializeObject(EveryMonthData);
                        db.SaveChanges();
                        string[] parents = stat.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                        Array.Reverse(parents);
                        int index = 0;
                        foreach(string parent in parents)
                        {
                            index += 1;
                            int ParentUserId = int.Parse(function.CheckInt(parent));
                            LeaderCompPrizeBak prize = db.LeaderCompPrizeBak.FirstOrDefault(m => m.UserId == ParentUserId && m.StatMonth == MonthString);
                            if(prize == null)
                            {
                                Users user = db.Users.FirstOrDefault(m => m.Id == ParentUserId) ?? new Users();
                                prize = db.LeaderCompPrizeBak.Add(new LeaderCompPrizeBak()
                                {
                                    CreateDate = DateTime.Now,
                                    UserId = ParentUserId,
                                    ParentUserId = user.ParentUserId,
                                    ParentNav = user.ParentNav,
                                    StatMonth = MonthString,
                                }).Entity;
                                db.SaveChanges();
                            }
                            if(index == 1)
                            {
                                prize.DirectCount += 1;
                            }
                            else
                            {
                                prize.NotDirectCount += 1;
                            }
                            db.SaveChanges();
                        }
                    }
                    function.WriteLog(DateTime.Now.ToString() + "------" + stat.UserId, "领导人达标奖励日志");
                }
                function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");
                db.Dispose();
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "领导达标人奖励异常");
            }
        }

        
        private void SendPrizeEveryDay(string month, string checkDate)
        {
            string MonthFlag = month + "-" + checkDate;
            WebCMSEntities db = new WebCMSEntities();
            OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();
            //计算运营中心或大盟主达标奖励
            List<LeaderCompPrizeBak> leaderPrizes = db.LeaderCompPrizeBak.Where(m => m.StatMonth == MonthFlag).ToList();
            function.WriteLog(leaderPrizes.Count.ToString(), "领导人达标奖励日志");
            foreach(LeaderCompPrizeBak leaderPrize in leaderPrizes)
            {
                Users user = db.Users.FirstOrDefault(m => m.Id == leaderPrize.UserId) ?? new Users();
                string CheckJson = "\"" + MonthFlag + "\":1";
                string NavUserId = "," + user.Id + ",";
                int person = 0;
                int directPerson = 0;
                int totalPerson = db.LeaderCompTmpBak.Count(m => (m.ParentNav.Contains(NavUserId)) && m.EveryMonthData.Contains(CheckJson));
                var subusers = db.Users.Select(m => new { m.Id, m.ParentUserId }).Where(m => m.ParentUserId == user.Id).ToList();
                foreach(var subuser in subusers)
                {
                    string subNavUserId = "," + subuser.Id + ",";
                    if(db.LeaderCompTmpBak.Count(m => (m.ParentNav.Contains(subNavUserId) || m.Id == subuser.Id) && m.EveryMonthData.Contains(CheckJson)) > 0)
                    {
                        person += 1;
                    }
                    if(db.LeaderCompTmpBak.Any(m => m.Id == subuser.Id && m.EveryMonthData.Contains(CheckJson)))
                    {
                        directPerson += 1;
                    }
                }

                int maxPerson = person * person;
                decimal CompPrize = 0;
                if(totalPerson >= maxPerson)
                {
                    CompPrize = GetPrize(maxPerson - person, person);
                }
                else
                {
                    CompPrize = GetPrize(totalPerson - person, person);
                }

                LeaderCompPrizeBak edit = db.LeaderCompPrizeBak.FirstOrDefault(m => m.StatMonth == MonthFlag && m.UserId == leaderPrize.UserId);
                if(edit != null)
                {
                    edit.DirectCount = directPerson;
                    edit.NotDirectCount = totalPerson - person;
                    edit.SecDirectCount = person;
                    edit.CompPrize = CompPrize;
                }
                db.SaveChanges();
            }
            function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");
            db.Dispose();
            opdb.Dispose();
        }

    
    }
}