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



        #region 分润

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

        public void StartListenProfitDo()
        {
            while (true)
            {
                if (DateTime.Now.Day < 10 && 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 DoProfit()
        {
            string TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            string check = function.ReadInstance("/ProfitFlag/" + TradeMonth + "-after.txt");
            if (!string.IsNullOrEmpty(check))
            {
                return;
            }
            function.WritePage("/ProfitFlag/", TradeMonth + "-after.txt", DateTime.Now.ToString());
            Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
            WebCMSEntities dbnew = new WebCMSEntities();
            DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount) from UserAmountSummaryAfter where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId", AppConfig.Base.SqlConnStr);
            foreach (DataRow dr in dt.Rows)
            {
                int UserId = int.Parse(dr["UserId"].ToString());
                bool IsActive = dr["IsAct"].ToString() == "1";
                decimal TotalAmount = decimal.Parse(dr[2].ToString());
                List<ProfitUsers> users = new List<ProfitUsers>();
                int TopUserId = 0; //顶级创客Id
                Models.KxsMain.Users us = kxsdb.Users.FirstOrDefault(a => a.Id == UserId);
                if (us != null)
                {
                    string uidstring = us.Id.ToString();
                    if (!string.IsNullOrEmpty(us.ParentNav))
                    {
                        uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
                        string[] parents = us.ParentNav.Trim(',').Replace(",,", ",").Split(',');
                        if (parents.Length > 1)
                        {
                            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));
                        Models.KxsMain.Users pus = kxsdb.Users.FirstOrDefault(a => a.Id == puid);
                        if (pus != null)
                        {
                            users.Add(new ProfitUsers()
                            {
                                UserId = pus.Id,
                                MakerCode = pus.MakerCode,
                                RealName = pus.RealName,
                                UserNav = pus.ParentNav,
                                UserLevel = pus.UserLevel,
                                CreateDate = pus.CreateDate.Value,
                            });
                        }
                    }
                }
                Models.KxsMain.Users topUser = kxsdb.Users.FirstOrDefault(a => a.Id == TopUserId) ?? new Models.KxsMain.Users();
                LogHelper.Instance.WriteLog("---UserId:" + UserId + ";TotalAmount:" + TotalAmount + "；", "来客吧分润日志");
                List<ProfitResult> list = new List<ProfitResult>();
                list = StartProft(TotalAmount, 1, users, 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.ProfitType == ProfitType && m.TradeMonth == TradeMonth);
                        if (editprofitrecord == null)
                        {
                            editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
                            {
                                CreateDate = DateTime.Now,
                                UserId = sub.UserId, //创客
                                BrandId = 1, //品牌
                                ProfitType = ProfitType, //创客分润类型
                                TradeMonth = TradeMonth, //交易月
                                TopUserId = TopUserId, //顶级创客
                                CreateMan = sub.MakerCode, //创客编号
                                UpdateMan = topUser.MakerCode, //顶级编号
                                SeoTitle = sub.RealName, //创客姓名
                                SeoKeyword = topUser.RealName, //创客姓名
                            }).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();
        }

        #endregion

        #region 分润算法
        public List<ProfitResult> StartProft(decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, bool IsActive = true)
        {
            LogHelper.Instance.WriteLog("\n\nTotalAmount：" + TotalAmount + "；", "来客吧分润日志");
            string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            WebCMSEntities db = new WebCMSEntities();
            List<UserLevelSet> levels = db.UserLevelSet.ToList();
            List<ProfitResult> result = new List<ProfitResult>();
            ProfitObjects obj = db.ProfitObjects.FirstOrDefault();
            if (obj.Status == 1) //判断分润是否开启
            {
                int maxLevel = obj.MaxLevel; //最大等级
                int maxFloor = obj.MaxFloor; //最大层级
                decimal diffLevelProfit = 0;  //等级级差
                ProfitObjectLevels maxlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == 9) ?? 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; //分红级差
                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(user.UserId, Month) ?? new SubUser();
                    int UserLevel = GetUserLevel(selfUser); //当前会员等级
                    //判断当前创客是否有直推的激活机具，并且在活动时间内
                    if (curLevel == maxLevel)
                    {
                        break;
                    }
                    if (UserLevel <= maxLevel && UserLevel >= curLevel)
                    {
                        ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel); //获取当前等级参数
                        if (objlevel != null)
                        {
                            decimal getLevelProfit = 0;  //等级分润
                            UserProfitSet profitSet = new UserProfitSet();
                            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,
                                });
                                LogHelper.Instance.WriteLog("money：" + UserLevel + "：" + PublicFunction.NumberFormat(getLevelProfit) + "；", "来客吧分润日志");
                            }
                        }
                    }
                    if (curLevel < UserLevel)
                    {
                        curLevel = UserLevel;
                    }
                }
            }
            db.Dispose();
            return result;
        }

        public SubUser GetUser(int UserId, string Month)
        {
            SubUser user = new SubUser();
            DataTable dt = GetDataTable("select * from Users" + Month + " where Id=" + UserId);
            if (dt.Rows.Count > 0)
            {
                user.Id = int.Parse(dt.Rows[0]["Id"].ToString());
                user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
                user.ParentNav = dt.Rows[0]["ParentNav"].ToString();
                user.UserLevel = int.Parse(dt.Rows[0]["UserLevel"].ToString());
                user.PreUserLevel = int.Parse(dt.Rows[0]["PreUserLevel"].ToString());
                user.PreLeaderLevel = int.Parse(dt.Rows[0]["PreLeaderLevel"].ToString());
                user.PreOpLevel = int.Parse(dt.Rows[0]["PreOpLevel"].ToString());
            }
            return user;
        }

        public int GetUserLevel(SubUser user)
        {
            int level = user.UserLevel;
            if (user.PreUserLevel > level) level = user.PreUserLevel;
            if (user.PreLeaderLevel > level) level = user.PreLeaderLevel;
            if (user.PreOpLevel > level) level = user.PreOpLevel;
            return level;
        }

        public DataTable GetDataTable(string sqlstr)
        {
            DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsStatSqlConnStr"].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)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "设置订单当前返现金额异常");
            }
        }
    }
}