using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using MySystem.Models.Main;
using Library;
using System.Threading;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
using LitJson;
using MySystem.Models;

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



        #region 分润

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

        public void StartListenProfitDo()
        {
            while (true)
            {
                if (DateTime.Now.Day < 25 && DateTime.Now.Hour > 2 && DateTime.Now.Hour < 23)
                {
                    try
                    {
                        DoProfit();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "来客吧分润异常");
                    }
                    Thread.Sleep(600000);
                }
                else
                {
                    Thread.Sleep(3600000);
                }
            }
        }

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

        public void StartListenProfitAddDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ProfitAfterNewQueue");
                if (!string.IsNullOrEmpty(content))
                {
                    try
                    {
                        string[] data = content.Split('|');
                        DoProfit(data[0], data[1]);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "来客吧分润异常");
                    }
                    Thread.Sleep(2000);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }

        //分润算法
        public void DoProfit(string otherCondi = "", string TradeMonth = "")
        {
            if(string.IsNullOrEmpty(TradeMonth)) TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            if(string.IsNullOrEmpty(otherCondi))
            {
                string check = function.ReadInstance("/ProfitFlag/" + TradeMonth + "-after-new.txt");
                if (!string.IsNullOrEmpty(check))
                {
                    return;
                }
                function.WritePage("/ProfitFlag/", TradeMonth + "-after-new.txt", DateTime.Now.ToString());
            }
            Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
            WebCMSEntities dbnew = new WebCMSEntities();
            KxsUserModels.WebCMSEntities udb = new KxsUserModels.WebCMSEntities();
            DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount),Sort,QueryCount from UserAmountSummaryNewAfter where TradeMonth='" + TradeMonth + "'" + otherCondi + " and SeoTitle='self' group by IsAct,UserId,Sort,QueryCount", AppConfig.Base.SqlConnStr);
            foreach (DataRow dr in dt.Rows)
            {
                int UserId = int.Parse(dr["UserId"].ToString());
                bool IsActive = dr["IsAct"].ToString() == "1";
                int Sort = int.Parse(dr["Sort"].ToString());
                decimal TotalAmount = decimal.Parse(dr[2].ToString());                
                bool WenDing = dr["QueryCount"].ToString() == "1";
                List<ProfitUsers> users = new List<ProfitUsers>();
                int TopUserId = 0; //顶级创客Id
                KxsUserModels.KxsUser us = udb.KxsUser.FirstOrDefault(a => a.Id == UserId);
                if (us != null)
                {
                    string uidstring = us.Id.ToString();
                    if (!string.IsNullOrEmpty(us.PidPath))
                    {
                        uidstring = us.PidPath.Trim(',').Replace(",,", ",") + "," + uidstring;
                        string[] parents = us.PidPath.Trim(',').Replace(",,", ",").Split(',');
                        if (parents.Length > 2)
                        {
                            TopUserId = int.Parse(function.CheckInt(parents[1]));
                        }
                        else
                        {
                            TopUserId = int.Parse(function.CheckInt(parents[0]));
                        }
                    }
                    string[] uidlist = uidstring.Split(',');
                    Array.Reverse(uidlist);
                    foreach (string uidstr in uidlist)
                    {
                        int puid = int.Parse(function.CheckInt(uidstr));
                        KxsUserModels.KxsUser pus = udb.KxsUser.FirstOrDefault(a => a.Id == puid);
                        if (pus != null)
                        {
                            users.Add(new ProfitUsers()
                            {
                                UserId = pus.Id,
                                MakerCode = pus.UserCode,
                                RealName = pus.Username,
                                UserNav = pus.PidPath,
                                UserLevel = pus.UserLevel,
                                CreateDate = pus.CreateTime.Value,
                            });
                        }
                    }
                }
                KxsUserModels.KxsUser topUser = udb.KxsUser.FirstOrDefault(a => a.Id == TopUserId) ?? new KxsUserModels.KxsUser();
                LogHelper.Instance.WriteLog("---UserId:" + UserId + ";TotalAmount:" + TotalAmount + "；", "来客吧分润日志");
                List<ProfitResult> list = new List<ProfitResult>();
                list = StartProft(TradeMonth, TotalAmount, 1, users, Sort, WenDing, IsActive);
                LogHelper.Instance.WriteLog("---list:" + list.Count + ";", "来客吧分润日志");
                try
                {
                    foreach (ProfitResult sub in list)
                    {
                        int ProfitType = sub.UserId == UserId ? 0 : 1;
                        ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.BrandId == 1 && m.Version == 1 && m.QueryCount == 1 && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth && m.Sort == Sort);
                        if (editprofitrecord == null)
                        {
                            editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
                            {
                                CreateDate = DateTime.Now,
                                UserId = sub.UserId, //创客
                                BrandId = 1, //品牌
                                Version = 1, //新政
                                QueryCount = 1, //增量
                                ProfitType = ProfitType, //创客分润类型
                                TradeMonth = TradeMonth, //交易月
                                TopUserId = TopUserId, //顶级创客
                                CreateMan = sub.MakerCode, //创客编号
                                UpdateMan = topUser.UserCode, //顶级编号
                                SeoTitle = sub.RealName, //创客姓名
                                SeoKeyword = topUser.Username, //创客姓名
                                Sort = Sort,
                            }).Entity;
                            dbnew.SaveChanges();
                            string RecordNo = "KPM";
                            int RecordId = editprofitrecord.Id;
                            string RecordIdString = RecordId.ToString();
                            for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
                            {
                                RecordIdString = "0" + RecordIdString;
                            }
                            RecordNo += RecordIdString;
                            editprofitrecord.RecordNo = RecordNo;
                            dbnew.SaveChanges();
                        }
                        if (IsActive)
                        {
                            editprofitrecord.CreditTradeAmt += TotalAmount;
                            editprofitrecord.CreditTradeProfit += sub.Money;
                        }
                        else
                        {
                            editprofitrecord.TradeAmt += TotalAmount;
                            editprofitrecord.TradeProfit += sub.Money;
                        }
                        dbnew.SaveChanges();
                    }
                    dbnew.SaveChanges();
                }
                catch (Exception ex)
                {
                    LogHelper.Instance.WriteLog(ex.ToString(), "分润异常");
                }
            }
            dbnew.Dispose();
            kxsdb.Dispose();
            udb.Dispose();
        }

        #endregion

        #region 分润算法
        public List<ProfitResult> StartProft(string Month, decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, int Sort, bool WenDing, bool IsActive = true)
        {
            LogHelper.Instance.WriteLog("\n\nTotalAmount：" + TotalAmount + "；", "来客吧分润日志");
            WebCMSEntities db = new WebCMSEntities();
            KxsUserModels.WebCMSEntities udb = new KxsUserModels.WebCMSEntities();
            List<UserLevelSet> levels = db.UserLevelSet.ToList();
            List<ProfitResult> result = new List<ProfitResult>();
            ProfitObjects obj = db.ProfitObjects.FirstOrDefault();
            if (obj.Status == 1) //判断分润是否开启
            {
                int maxLevel = 5; //最大等级
                int maxFloor = obj.MaxFloor; //最大层级
                decimal diffLevelProfit = 0;  //等级级差
                ProfitObjectLevels maxlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.LevelNumber == 5 && m.Version == 1) ?? new ProfitObjectLevels(); //获取最高等级参数
                decimal maxPercent = IsActive ? maxlevel.DebitPercents : maxlevel.Percents;
                LogHelper.Instance.WriteLog("maxPercent：" + maxPercent + "；", "来客吧分润日志");
                decimal maxLevelProfit = TotalAmount * maxPercent;
                LogHelper.Instance.WriteLog("maxLevelProfit：" + maxLevelProfit + "；", "来客吧分润日志");
                maxLevelProfit = PublicFunction.NumberFormat(maxLevelProfit);
                LogHelper.Instance.WriteLog("maxLevelProfit：" + maxLevelProfit + "；", "来客吧分润日志");
                // decimal diffDiviProfit = 0; //分红级差
                
                //0.38分万15  0.25分万2  0.3分万7，成本0.23
                if(Sort == 30 || Sort == 25)
                {
                    decimal profit = 0;
                    if(Sort == 25) profit = TotalAmount * 0.00016M;
                    if(Sort == 30) profit = TotalAmount * 0.0004M;
                    ProfitUsers user = users[0];
                    result.Add(new ProfitResult()
                    {
                        UserId = user.UserId,
                        MakerCode = user.MakerCode,
                        RealName = user.RealName,
                        UserNav = user.UserNav,
                        Money = PublicFunction.NumberFormat(profit),
                        ProfitRate = Sort / 10000,
                        Fee = Sort,
                    });
                }
                else
                {
                    int curLevel = 0; //当前层级的会员等级
                    for (int curFloor = 1; curFloor <= users.Count; curFloor++)
                    {
                        ProfitUsers user = new ProfitUsers();
                        if (curFloor <= users.Count)
                        {
                            user = users[curFloor - 1];
                        }
                        SubUser selfUser = GetUser(udb, user.UserId, int.Parse(Month)) ?? new SubUser();
                        int UserLevel = GetUserLevel(selfUser); //当前会员等级
                        //判断当前创客是否有直推的激活机具，并且在活动时间内
                        if (curLevel == maxLevel)
                        {
                            break;
                        }
                        if (UserLevel <= maxLevel && UserLevel >= curLevel)
                        {
                            ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.LevelNumber == UserLevel && m.Version == 1); //获取当前等级参数
                            if (objlevel != null)
                            {
                                decimal getLevelProfit = 0;  //等级分润
                                UserProfitSet profitSet = new UserProfitSet();                                
                                if(WenDing) objlevel.Percents = objlevel.Percents * 0.8M;
                                decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
                                LogHelper.Instance.WriteLog("money：" + UserLevel + "：" + profitPercent + "；", "来客吧分润日志");
                                if (profitPercent > 0)
                                {
                                    decimal profitTmp = TotalAmount * profitPercent;
                                    getLevelProfit += profitTmp;
                                    LogHelper.Instance.WriteLog("money：" + UserLevel + "：" + profitTmp + "；", "来客吧分润日志");
                                }
                                decimal money = getLevelProfit;
                                getLevelProfit -= diffLevelProfit;
                                if (objlevel.LevelDiff == 1)  //判断是否有级差
                                {
                                    diffLevelProfit = money;
                                }
                                if (getLevelProfit >= obj.MinProfitVal)
                                {
                                    result.Add(new ProfitResult()
                                    {
                                        UserId = user.UserId,
                                        MakerCode = user.MakerCode,
                                        RealName = user.RealName,
                                        UserNav = user.UserNav,
                                        Money = PublicFunction.NumberFormat(getLevelProfit),
                                        ProfitRate = profitSet.ProfitRate,
                                        ProfitPercent = profitSet.ProfitPercent,
                                        AddOrSubRate = profitSet.AddOrSubRate,
                                        ProfitRateBase = profitSet.ProfitRateBase,
                                        Fee = Sort,
                                    });
                                    LogHelper.Instance.WriteLog("money：" + UserLevel + "：" + PublicFunction.NumberFormat(getLevelProfit) + "；", "来客吧分润日志");
                                }
                            }
                        }
                        if (curLevel < UserLevel)
                        {
                            curLevel = UserLevel;
                        }
                    }
                }
            }
            db.Dispose();
            udb.Dispose();
            return result;
        }

        public SubUser GetUser(KxsUserModels.WebCMSEntities db, int UserId, int Month)
        {
            SubUser user = new SubUser();
            KxsUserModels.KxsTradeLevelLog log = db.KxsTradeLevelLog.FirstOrDefault(m => m.TradeMonth == Month && m.Version == 1 && m.UserId == UserId);
            if(log != null)
            {
                user.Id = log.UserId;
                user.Level = log.Level;
                user.ParentNav = log.PidPath;
                user.UserLevel = log.UserLevel;
                user.PreUserLevel = log.PreLevel;
                user.PreLeaderLevel = log.LeaderLevel;;
            }
            // DataTable dt = GetDataTable("select * from kxs_trade_level_log where trade_month=" + Month + " and version=1 and user_id=" + UserId);
            // if (dt.Rows.Count > 0)
            // {
            //     user.Id = int.Parse(dt.Rows[0]["user_id"].ToString());
            //     // user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
            //     user.Level = int.Parse(dt.Rows[0]["level"].ToString());
            //     user.ParentNav = dt.Rows[0]["pid_path"].ToString();
            //     user.UserLevel = int.Parse(dt.Rows[0]["user_level"].ToString());
            //     user.PreUserLevel = int.Parse(dt.Rows[0]["pre_level"].ToString());
            //     user.PreLeaderLevel = int.Parse(dt.Rows[0]["leader_level"].ToString());
            //     Utils.WriteLog(Newtonsoft.Json.JsonConvert.SerializeObject(user), "检查666");
            // }
            return user;
        }

        public int GetUserLevel(SubUser user)
        {
            int[] levels = new int[] { user.Level, user.UserLevel, user.PreUserLevel, user.PreLeaderLevel };
            return levels.ToList().Max();
        }

        public DataTable GetDataTable(string sqlstr)
        {
            DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsUserSqlConnStr"].ToString());
            return dt;
        }
        #endregion




        public void StartSetDivi()
        {
            Thread th = new Thread(StartSetDiviDo);
            th.IsBackground = true;
            th.Start();
        }
        public void StartSetDiviDo()
        {
            while (true)
            {
                string content = RedisDbconn.Instance.RPop<string>("ConsumerOrdersSetDiviHd");
                if (!string.IsNullOrEmpty(content))
                {
                    SetDivi(content);
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }

        public void SetDivi(string content)
        {
            try
            {
                JsonData jsonObj = JsonMapper.ToObject(content);
                int orderId = int.Parse(function.CheckInt(jsonObj["OrderId"].ToString()));
                decimal diviAmt = decimal.Parse(function.CheckNum(jsonObj["DiviAmt"].ToString()));
                WebCMSEntities db = new WebCMSEntities();
                ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == orderId);
                if (order != null)
                {
                    order.CurDivi = diviAmt;
                    db.SaveChanges();
                }
                db.Dispose();
            }
            catch (Exception ex)
            {
                Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "设置订单当前返现金额异常");
            }
        }
    }
}