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("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);
            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;
                    }
                }

                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, "领导人达标奖励日志");
                
                // List<LeaderCompTradeStat> stats = db.LeaderCompTradeStat.Where(m => m.StatMonth == MonthString).ToList();
                DataTable stats = CustomerSqlConn.dtable("select UserId,ParentUserId,ParentNav,TradeAmount,(select sum(TradeAmount) from LeaderCompTradeStat where ParentUserId=p.UserId and TradeAmount<30000000) SmallTradeAmount from LeaderCompTradeStat p where StatMonth='" + MonthString + "' and UserId>1", MysqlConn.SqlConnStr);
                function.WriteLog(stats.Rows.Count.ToString(), "领导人达标奖励日志");
                foreach(DataRow stat in stats.Rows)
                {
                    int UserId = int.Parse(function.CheckInt(stat["UserId"].ToString()));
                    int ParentUserId = int.Parse(function.CheckInt(stat["ParentUserId"].ToString()));
                    decimal totalAmount = decimal.Parse(function.CheckNum(stat["TradeAmount"].ToString()));
                    decimal smallTradeAmount = decimal.Parse(function.CheckNum(stat["SmallTradeAmount"].ToString()));
                    string ParentNav = stat["ParentNav"].ToString();
                    function.WriteLog("1-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                    function.WriteLog("UserId:" + UserId, "领导人达标奖励日志");
                    function.WriteLog("totalAmount:" + totalAmount, "领导人达标奖励日志");
                    function.WriteLog("3-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                    
                    //直推创客交易额大于等于3000万即成为达标市场
                    if(totalAmount >= 30000000 && !string.IsNullOrEmpty(ParentNav))
                    {
                        function.WriteLog("4-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                        LeaderCompTmp tmp = db.LeaderCompTmp.FirstOrDefault(m => m.Id == UserId);
                        if(tmp == null)
                        {
                            tmp = db.LeaderCompTmp.Add(new LeaderCompTmp()
                            {
                                Id = UserId,
                                ParentUserId = ParentUserId,
                                ParentNav = ParentNav
                            }).Entity;
                            db.SaveChanges();
                        }
                        tmp.EveryMonthData += "1";
                        db.SaveChanges();
                        function.WriteLog("5-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                    }
                    if(smallTradeAmount >= 30000000 && !string.IsNullOrEmpty(ParentNav))
                    {
                        function.WriteLog("4-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                        LeaderCompTmp tmp = db.LeaderCompTmp.FirstOrDefault(m => m.Id == UserId);
                        if(tmp == null)
                        {
                            tmp = db.LeaderCompTmp.Add(new LeaderCompTmp()
                            {
                                Id = UserId,
                                ParentUserId = ParentUserId,
                                ParentNav = ParentNav
                            }).Entity;
                            db.SaveChanges();
                        }
                        tmp.EveryMonthData += "2";
                        db.SaveChanges();
                        function.WriteLog("5-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                    }
                    
                    function.WriteLog("7-----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), "领导人达标奖励日志");
                    function.WriteLog(DateTime.Now.ToString() + "------" + UserId, "领导人达标奖励日志");
                }
                db.SaveChanges();
                opdb.Dispose();
                mpmaindb.Dispose();
                mpmaindb2.Dispose();
                function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "领导达标人奖励异常");
            }
        }

        private void SendPrize(string month, string checkDate)
        {
            string MonthFlag = month + "-" + checkDate;
            WebCMSEntities db = new WebCMSEntities();
            DataTable dt = CustomerSqlConn.dtable("select ParentUserId,ParentNav,count(1) from LeaderCompTmp where SUBSTR(EveryMonthData,1,1)='1' GROUP BY ParentUserId,ParentNav", MysqlConn.SqlConnStr);
            foreach(DataRow dr in dt.Rows)
            {
                int ParentUserId = int.Parse(function.CheckInt(dr["ParentUserId"].ToString()));
                string ParentNav = dr["ParentNav"].ToString();
                int Count = int.Parse(function.CheckInt(dr[2].ToString()));
                LeaderCompPrize edit = db.LeaderCompPrize.FirstOrDefault(m => m.StatMonth == MonthFlag && m.UserId == ParentUserId);
                if(edit == null)
                {
                    edit = db.LeaderCompPrize.Add(new LeaderCompPrize()
                    {
                        CreateDate = DateTime.Now,
                        StatMonth = MonthFlag,
                        UserId = ParentUserId,
                    }).Entity;
                    db.SaveChanges();
                }
                edit.DirectCount = Count; //达标市场
                DataTable dtsub = CustomerSqlConn.dtable("select SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(ParentNav, '" + ParentNav + "', ''),',',2),',',-1),count(1) from LeaderCompTmp where ParentUserId!=" + ParentUserId + " and ParentNav like '%," + ParentUserId + ",%' and SUBSTR(EveryMonthData,2,1)='2' group by SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(ParentNav, '" + ParentNav + "', ''),',',2),',',-1)", MysqlConn.SqlConnStr);
                foreach(DataRow drsub in dtsub.Rows)
                {
                    int SubCount = int.Parse(function.CheckInt(drsub[1].ToString()));
                    edit.NotDirectCount += SubCount; //深度达标总数
                    if(SubCount > Count)
                    {
                        SubCount = Count;
                    }
                    edit.SecDirectCount += SubCount; //深度达标计奖数
                }
                edit.CompPrize = edit.SecDirectCount * 500;
                db.SaveChanges();
            }
            function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");
            db.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;
        }
        
    }
}