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

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

        public void Listen()//启动
        {
            while(true)
            {
                if(DateTime.Now.Hour > 3 && 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("yyyyMM"));
                        }
                        Ready(DateTime.Now.ToString("yyyyMM"));
                    }
                }
                Thread.Sleep(60000);
            }
        }

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

        public void ListenTest()//启动
        {
            string check = function.ReadInstance("/LeaderComp/Repeat/202502.txt");
            if (string.IsNullOrEmpty(check))
            {
                function.WritePage("/LeaderComp/Repeat/", "202502.txt", DateTime.Now.ToString());
                Ready("202502");
            }
            check = function.ReadInstance("/LeaderComp/Repeat/202503.txt");
            if (string.IsNullOrEmpty(check))
            {
                function.WritePage("/LeaderComp/Repeat/", "202503.txt", DateTime.Now.ToString());
                Ready("202503");
            }
        }

        public void Ready(string curMonth)
        {
            CustomerSqlConn.op("delete from LeaderCompTradeStat;delete from LeaderCompTmp;delete from LeaderCompPrize;delete from LeaderCompAddTrade;", MysqlConn.SqlConnStr);
            CustomerSqlConn.op("delete from kxs_shd_leader where trade_month='" + curMonth + "'", MysqlConn.JavaUserSqlConnStr);
            doSomething(curMonth);
            SendPrize(curMonth);
        }

        public void doSomething(string month)
        {
            try
            {
                WebCMSEntities db = new WebCMSEntities();
                string MonthString = month;
                string Now = DateTime.Parse(month.Substring(0, 4) + "-" + month.Substring(4, 2) + "-01 00:00:00").AddMonths(1).ToString("yyyy-MM-dd HH:mm:ss");
                string PreMonthString = DateTime.Parse(month.Substring(0, 4) + "-" + month.Substring(4, 2) + "-01 00:00:00").AddMonths(-1).ToString("yyyyMM");

                //统计交易增量
                function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");
                
                //创客团队交易额
                string sql = "";
                int rownum = 0;
                int num = 0;
                List<LeaderCompUser> UserData = new List<LeaderCompUser>();
                string rootsql = "select tb.user_id,pid,pid_path,leader_type,trade_amt from (select user_id,trade_amt from kxs_user_trade_info where trade_month='" + month + "' and trade_amt>0) tb LEFT JOIN kxs_user u on tb.user_id=u.id LEFT JOIN kxs_leader l on tb.user_id=l.id and l.expired_date>='" + Now + "'";
                function.WriteLog(rootsql, "领导人达标奖励日志");
                DataTable dt = CustomerSqlConn.dtable(rootsql, MysqlConn.JavaUserSqlConnStr);
                foreach(DataRow dr in dt.Rows)
                {
                    int UserId = int.Parse(dr["user_id"].ToString());
                    int ParentUserId = int.Parse(function.CheckInt(dr["pid"].ToString()));
                    string ParentNav = dr["pid_path"].ToString();
                    int LeaderType = int.Parse(function.CheckInt(dr["leader_type"].ToString()));
                    decimal Amt = decimal.Parse(function.CheckNum(dr["trade_amt"].ToString()));
                    LeaderCompUser item = UserData.FirstOrDefault(m => m.UserId == UserId);
                    if(item == null)
                    {
                        UserData.Add(new LeaderCompUser()
                        {
                            UserId = UserId,
                            ParentUserId = ParentUserId,
                            ParentNav = ParentNav,
                            LeaderType = LeaderType,
                            Amt = Amt,
                        });
                    }
                    else
                    {
                        item.Amt += Amt;
                    }
                }
                function.WriteLog("交易数:" + dt.Rows.Count.ToString(), "领导人达标奖励日志");
                foreach(LeaderCompUser SubUser in UserData)
                {
                    rownum += 1;
                    function.WriteLog("rownum:" + rownum.ToString(), "领导人达标奖励日志");
                    int UserId = SubUser.UserId;
                    function.WriteLog("UserId:" + UserId.ToString(), "领导人达标奖励日志");
                    decimal TradeAmount = SubUser.Amt;
                    int ParentUserId = SubUser.ParentUserId;
                    string ParentNav = SubUser.ParentNav;
                    int LeaderType = SubUser.LeaderType;
                    sql += "insert into LeaderCompTradeStat (LeaderType,ParentNav,ParentUserId,TradeAmount,StatMonth,UserId,CreateDate) values (" + LeaderType + ", '" + ParentNav + "', " + ParentUserId + ", " + TradeAmount + ", '" + month + "', " + UserId + ",now());\n";
                    num += 1;
                    if(num >= 200)
                    {
                        CustomerSqlConn.op(sql, MysqlConn.SqlConnStr);
                        sql = "";
                        num = 0;
                    }
                }

                if(!string.IsNullOrEmpty(sql))
                {
                    CustomerSqlConn.op(sql, MysqlConn.SqlConnStr);
                }

                //计算创客名下的达标人数，直推和间接
                function.WriteLog("MonthString:" + MonthString, "领导人达标奖励日志");

                //计算达标市场
                DataTable tmps = CustomerSqlConn.dtable("select id,pid,pid_path from kxs_user where id in ((select user_id from kxs_user_trade_info where trade_month='" + month + "' and is_vip=1))", MysqlConn.JavaUserSqlConnStr);
                function.WriteLog(tmps.Rows.Count.ToString(), "领导人达标奖励日志");
                foreach(DataRow stat in tmps.Rows)
                {
                    int UserId = int.Parse(function.CheckInt(stat["id"].ToString()));
                    int ParentUserId = int.Parse(function.CheckInt(stat["pid"].ToString()));
                    string ParentNav = stat["pid_path"].ToString();
                    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();
                }

                Thread.Sleep(60000);
                
                // List<LeaderCompTradeStat> stats = db.LeaderCompTradeStat.Where(m => m.StatMonth == MonthString).ToList();
                DataTable stats = CustomerSqlConn.dtable("select UserId,ParentUserId,ParentNav,TradeAmount,LeaderType,(select sum(TradeAmount) from LeaderCompTradeStat where ParentUserId=p.UserId and TradeAmount>=30000000) BigTradeAmount,(select count(1) from LeaderCompTradeStat where ParentUserId=p.UserId and TradeAmount>=30000000) BigCount,(select count(1) from LeaderCompTradeStat where ParentUserId=p.UserId and TradeAmount<30000000) SmallCount,(select count(1) from LeaderCompTradeStat where ParentUserId=p.UserId and LeaderType=2) LeaderCount,(select count(1) from LeaderCompTradeStat where ParentUserId=p.UserId and LeaderType>2) OperaterCount from LeaderCompTradeStat p where StatMonth='" + MonthString + "'", MysqlConn.ReadSqlConnStr);
                function.WriteLog(stats.Rows.Count.ToString(), "领导人达标奖励日志");
                string sqlString = "";
                foreach(DataRow stat in stats.Rows)
                {
                    int UserId = int.Parse(function.CheckInt(stat["UserId"].ToString()));
                    int ParentUserId = int.Parse(function.CheckInt(stat["ParentUserId"].ToString()));
                    int LeaderType = int.Parse(function.CheckInt(stat["LeaderType"].ToString()));
                    decimal totalAmount = decimal.Parse(function.CheckNum(stat["TradeAmount"].ToString()));
                    decimal bigTradeAmount = decimal.Parse(function.CheckNum(stat["BigTradeAmount"].ToString()));
                    decimal smallTradeAmount = totalAmount - bigTradeAmount;
                    int BigCount = int.Parse(function.CheckInt(stat["BigCount"].ToString()));
                    int SmallCount = int.Parse(function.CheckInt(stat["SmallCount"].ToString()));
                    int LeaderCount = int.Parse(function.CheckInt(stat["LeaderCount"].ToString()));
                    int OperaterCount = int.Parse(function.CheckInt(stat["OperaterCount"].ToString()));
                    string ParentNav = stat["ParentNav"].ToString();
                    
                    //计算达标市场
                    // if((BigCount == 1 && smallTradeAmount >= 12000000) || BigCount >= 2 || smallTradeAmount >= 30000000)
                    // {
                    //     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();
                    // }

                    //培养奖
                    if(smallTradeAmount < 30000000) BigCount -= 1;
                    if(BigCount > 0)
                    {
                        // decimal leaderOnePrize = 2500;
                        // decimal operaterOnePrize = 3000;
                        decimal onePrize = 0;
                        if(BigCount == 1) onePrize = 2000;
                        if(BigCount == 2) onePrize = 2500;
                        if(LeaderType == 2) onePrize = 2500;
                        if(BigCount == 3) 
                        {
                            onePrize = 3000;
                            // leaderOnePrize = 3000;
                        }
                        if(LeaderType > 2) onePrize = 3000;
                        if(BigCount == 4) 
                        {
                            onePrize = 4000;
                            // leaderOnePrize = 4000;
                            // operaterOnePrize = 4000;
                        }
                        if(BigCount == 5) 
                        {
                            onePrize = 5000;
                            // leaderOnePrize = 5000;
                            // operaterOnePrize = 5000;
                        }
                        if(BigCount >= 6) 
                        {
                            onePrize = 6000;
                            // leaderOnePrize = 6000;
                            // operaterOnePrize = 6000;
                        }
                        // decimal tradePrize = onePrize * (BigCount - LeaderCount - OperaterCount) + LeaderCount * leaderOnePrize + OperaterCount * operaterOnePrize; //培养奖金额
                        decimal tradePrize = onePrize * BigCount; //培养奖金额
                        sqlString += "insert into kxs_shd_leader (shd_type,trade_amt,source_bonus_amt,create_time,trade_month,user_id) values (0," + totalAmount + "," + tradePrize + ",now(),'" + MonthString + "'," + UserId + ");";
                    }
                }
                db.SaveChanges();
                function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");

                CustomerSqlConn.op(sqlString, MysqlConn.JavaUserSqlConnStr);
            }
            catch(Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "领导达标人奖励异常");
            }
        }

        private void SendPrize(string month)
        {
            string sql = "";
            string MonthFlag = month;
            WebCMSEntities db = new WebCMSEntities();
            // DataTable dt = CustomerSqlConn.dtable("select * from (select UserId,ParentUserId,ParentNav,(select count(1) from LeaderCompTradeStat where ParentUserId=p.UserId and TradeAmount>=30000000) BigCount from LeaderCompTradeStat p where StatMonth='" + month + "' and LeaderType>=2) tb where BigCount>0", MysqlConn.SqlConnStr);
            DataTable dt = CustomerSqlConn.dtable("select * from (select UserId,ParentUserId,ParentNav,(select count(1) from LeaderCompTradeStat where ParentUserId=p.UserId and TradeAmount>=30000000) BigCount from LeaderCompTradeStat p where StatMonth='" + month + "') tb where BigCount>0", MysqlConn.SqlConnStr);
            foreach(DataRow dr in dt.Rows)
            {
                int UserId = int.Parse(function.CheckInt(dr["UserId"].ToString()));
                function.WriteLog(UserId.ToString(), "核对");
                string ParentNav = dr["ParentNav"].ToString();
                int Count = int.Parse(function.CheckInt(dr["BigCount"].ToString()));
                function.WriteLog(Count.ToString(), "核对");
                LeaderCompPrize edit = db.LeaderCompPrize.FirstOrDefault(m => m.StatMonth == MonthFlag && m.UserId == UserId);
                if(edit == null)
                {
                    edit = db.LeaderCompPrize.Add(new LeaderCompPrize()
                    {
                        CreateDate = DateTime.Now,
                        StatMonth = MonthFlag,
                        UserId = UserId,
                    }).Entity;
                    db.SaveChanges();
                }
                edit.DirectCount = Count; //达标市场
                DataTable dtsub = CustomerSqlConn.dtable("select UserId from LeaderCompTradeStat where ParentUserId=" + UserId, MysqlConn.SqlConnStr);
                foreach(DataRow drsub in dtsub.Rows)
                {
                    int SubCount = 0;
                    DataTable subuser = CustomerSqlConn.dtable("select count(1) from LeaderCompTmp where Id=" + drsub["UserId"].ToString() + " or ParentNav like '%," + drsub["UserId"].ToString() + ",%'", MysqlConn.SqlConnStr);
                    if(subuser.Rows.Count > 0)
                    {
                        SubCount = int.Parse(function.CheckInt(subuser.Rows[0][0].ToString()));
                    }
                    function.WriteLog("SubCount:" + SubCount, "核对");
                    edit.NotDirectCount += SubCount; //深度达标总数
                    if(SubCount > Count)
                    {
                        SubCount = Count;
                    }
                    edit.SecDirectCount += SubCount; //深度达标计奖数
                }
                function.WriteLog(edit.SecDirectCount.ToString(), "核对");
                decimal CompPrize = edit.SecDirectCount * 1000;
                edit.CompPrize = CompPrize;
                db.SaveChanges();

                LeaderCompTradeStat stat = db.LeaderCompTradeStat.FirstOrDefault(m => m.UserId == UserId) ?? new LeaderCompTradeStat();
                // if(stat.LeaderType > 1 && CompPrize > 0)
                if(CompPrize > 0)
                {
                    sql += "insert into kxs_shd_leader (shd_type,trade_amt,source_bonus_amt,create_time,trade_month,user_id) values (1," + stat.TradeAmount + "," + CompPrize + ",now(),'" + MonthFlag + "'," + UserId + ");";
                }
            }
            CustomerSqlConn.op(sql, MysqlConn.JavaUserSqlConnStr);
            function.WriteLog(DateTime.Now.ToString(), "领导人达标奖励日志");
            db.Dispose();
        }        
    }
}