using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using MySystem.Models;
using Library;
using LitJson;

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

        public void Start()
        {
            try
            {
                LogHelper.Instance.WriteLog("导出分润:" + DateTime.Now.ToString(), "分润结果检查");
                ExportProfitData(); //导出分润
                LogHelper.Instance.WriteLog("导出补贴:" + DateTime.Now.ToString(), "分润结果检查");
                ExportSubsidyData(); //导出补贴
                LogHelper.Instance.WriteLog("检查分润:" + DateTime.Now.ToString(), "分润结果检查");
                CheckProfit(); //检查分润
                LogHelper.Instance.WriteLog("检查补贴:" + DateTime.Now.ToString(), "分润结果检查");
                CheckSubsidy(); //检查补贴
                LogHelper.Instance.WriteLog("结束:" + DateTime.Now.ToString(), "分润结果检查");
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "分润结果检查异常");
            }
        }

        public void ExportProfitData()
        {
            string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            WebCMSEntities db = new WebCMSEntities();
            string StartId = function.CheckInt(function.ReadInstance("/PublicParam/ProfitRewardRecordId/" + Month + ".txt"));
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            DataTable dt = OtherMySqlConn.dtable("select u.MakerCode,u.RealName,u.UserLevel,r.Rank,(case when ProfitType=1 then '直营' else '团队' end) as DirectFlag,k.Name,BrandId,CreditTradeAmt,CreditTradeProfit,QrCreditTradeAmt,QrCreditTradeProfit,NonQrCreditTradeAmt,NonQrCreditTradeProfit,HelpCreditTradeAmt,HelpCreditTradeProfit,NotHelpCreditTradeAmt,NotHelpCreditTradeProfit,ProfitCreditTradeAmt,ProfitCreditTradeProfit,DebitTradeAmt,DebitTradeProfit from (select UserId,ProfitType,BrandId,sum(CreditTradeAmt) as CreditTradeAmt,sum(CreditTradeProfit) as CreditTradeProfit,sum(QrCreditTradeAmt) as QrCreditTradeAmt,sum(QrCreditTradeProfit) as QrCreditTradeProfit,sum(NonQrCreditTradeAmt) as NonQrCreditTradeAmt,sum(NonQrCreditTradeProfit) as NonQrCreditTradeProfit,sum(HelpCreditTradeAmt) as HelpCreditTradeAmt,sum(HelpCreditTradeProfit) as HelpCreditTradeProfit,sum(NotHelpCreditTradeAmt) as NotHelpCreditTradeAmt,sum(NotHelpCreditTradeProfit) as NotHelpCreditTradeProfit,sum(ProfitCreditTradeAmt) as ProfitCreditTradeAmt,sum(ProfitCreditTradeProfit) as ProfitCreditTradeProfit,sum(DebitNonCapTradeAmt+DebitCapTradeAmt) as DebitTradeAmt,sum(DebitNonTradeCapProfit+DebitTradeCapProfit) as DebitTradeProfit from ProfitRewardRecord where Id>=" + StartId + " and TradeMonth='" + Month + "' GROUP BY UserId,ProfitType,BrandId) tb left join Users u on tb.UserId=u.Id LEFT JOIN KqProducts k ON k.Id=tb.BrandId left join UserRankWhite r on u.Id=r.Id and r.CreateDate<'" + DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00' and r.UpdateDate>'" + DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00' ORDER BY u.MakerCode");
            LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + dt.Rows.Count, "分润结果检查");
            int index = 0;
            foreach(DataRow dr in dt.Rows)
            {
                index += 1;
                string MakerCode = dr["MakerCode"].ToString();
                string RealName = dr["RealName"].ToString();
                int UserLevel = int.Parse(function.CheckInt(dr["UserLevel"].ToString()));
                int Rank = int.Parse(function.CheckInt(dr["Rank"].ToString()));
                string DirectFlag = dr["DirectFlag"].ToString();
                string BrandName = dr["Name"].ToString();
                int BrandId = int.Parse(function.CheckInt(dr["BrandId"].ToString()));
                decimal CreditTradeAmt = decimal.Parse(function.CheckNum(dr["CreditTradeAmt"].ToString()));
                decimal CreditTradeProfit = decimal.Parse(function.CheckNum(dr["CreditTradeProfit"].ToString()));
                decimal QrCreditTradeAmt = decimal.Parse(function.CheckNum(dr["QrCreditTradeAmt"].ToString()));
                decimal QrCreditTradeProfit = decimal.Parse(function.CheckNum(dr["QrCreditTradeProfit"].ToString()));
                decimal NonQrCreditTradeAmt = decimal.Parse(function.CheckNum(dr["NonQrCreditTradeAmt"].ToString()));
                decimal NonQrCreditTradeProfit = decimal.Parse(function.CheckNum(dr["NonQrCreditTradeProfit"].ToString()));
                decimal HelpCreditTradeAmt = decimal.Parse(function.CheckNum(dr["HelpCreditTradeAmt"].ToString()));
                decimal HelpCreditTradeProfit = decimal.Parse(function.CheckNum(dr["HelpCreditTradeProfit"].ToString()));
                decimal NotHelpCreditTradeAmt = decimal.Parse(function.CheckNum(dr["NotHelpCreditTradeAmt"].ToString()));
                decimal NotHelpCreditTradeProfit = decimal.Parse(function.CheckNum(dr["NotHelpCreditTradeProfit"].ToString()));
                decimal ProfitCreditTradeAmt = decimal.Parse(function.CheckNum(dr["ProfitCreditTradeAmt"].ToString()));
                decimal ProfitCreditTradeProfit = decimal.Parse(function.CheckNum(dr["ProfitCreditTradeProfit"].ToString()));
                decimal DebitTradeAmt = decimal.Parse(function.CheckNum(dr["DebitTradeAmt"].ToString()));
                decimal DebitTradeProfit = decimal.Parse(function.CheckNum(dr["DebitTradeProfit"].ToString()));
                db.ProfitRewardExport.Add(new ProfitRewardExport()
                {
                    CreateDate = DateTime.Now,
                    Sort = BrandId,
                    SeoTitle = Month,
                    MakerCode = MakerCode,
                    RealName = RealName,
                    UserLevel = UserLevel,
                    Rank = Rank,
                    DirectFlag = DirectFlag,
                    BrandName = BrandName,
                    CreditTradeAmt = CreditTradeAmt,
                    CreditTradeProfit = CreditTradeProfit,
                    QrCreditTradeAmt = QrCreditTradeAmt,
                    QrCreditTradeProfit = QrCreditTradeProfit,
                    NonQrCreditTradeAmt = NonQrCreditTradeAmt,
                    NonQrCreditTradeProfit = NonQrCreditTradeProfit,
                    HelpCreditTradeAmt = HelpCreditTradeAmt,
                    HelpCreditTradeProfit = HelpCreditTradeProfit,
                    NotHelpCreditTradeAmt = NotHelpCreditTradeAmt,
                    NotHelpCreditTradeProfit = NotHelpCreditTradeProfit,
                    ProfitCreditTradeAmt = ProfitCreditTradeAmt,
                    ProfitCreditTradeProfit = ProfitCreditTradeProfit,
                    DebitTradeAmt = DebitTradeAmt,
                    DebitTradeProfit = DebitTradeProfit,
                });
                if(index % 200 == 0)
                {
                    db.SaveChanges();
                }
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + index, "分润结果检查");
            }
            db.SaveChanges();
            db.Dispose();
        }

        public void ExportSubsidyData()
        {
            string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            WebCMSEntities db = new WebCMSEntities();
            string StartId = function.CheckInt(function.ReadInstance("/PublicParam/ProfitSubsidyDetailId/" + Month + ".txt"));
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
            DataTable dt = OtherMySqlConn.dtable("select u.MakerCode,u.RealName,u.UserLevel,r.Rank,m.KqSnNo,m.MerchantName,(case when SubsidyType=1 then '直营' else '团队' end) as DirectFlag,k.Name,tb.BrandId,CreditTradeAmt,SubsidyProfit from (select SubsidyUserId,MerchantId,BrandId,SubsidyType,sum(CreditTradeAmt) as CreditTradeAmt,sum(SubsidyProfitRate) as SubsidyProfit from ProfitSubsidyDetail where Id>=" + StartId + " and TradeMonth='" + Month + "' GROUP BY SubsidyUserId,MerchantId,BrandId,SubsidyType) tb left join Users u on tb.SubsidyUserId=u.Id LEFT JOIN KqProducts k ON k.Id=tb.BrandId left join PosMerchantInfo m on tb.MerchantId=m.Id left join UserRankWhite r on u.Id=r.Id and r.CreateDate<'" + DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00' and r.UpdateDate>'" + DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00'");
            LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + dt.Rows.Count, "分润结果检查");
            int index = 0;
            foreach(DataRow dr in dt.Rows)
            {
                index += 1;
                string MakerCode = dr["MakerCode"].ToString();
                string RealName = dr["RealName"].ToString();
                int UserLevel = int.Parse(function.CheckInt(dr["UserLevel"].ToString()));
                int Rank = int.Parse(function.CheckInt(dr["Rank"].ToString()));
                string KqSnNo = dr["KqSnNo"].ToString();
                string MerchantName = dr["MerchantName"].ToString();
                string DirectFlag = dr["DirectFlag"].ToString();
                string BrandName = dr["Name"].ToString();
                int BrandId = int.Parse(function.CheckInt(dr["BrandId"].ToString()));
                decimal CreditTradeAmt = decimal.Parse(function.CheckNum(dr["CreditTradeAmt"].ToString()));
                decimal SubsidyProfit = decimal.Parse(function.CheckNum(dr["SubsidyProfit"].ToString()));
                db.ProfitSubsidyExport.Add(new ProfitSubsidyExport()
                {
                    CreateDate = DateTime.Now,
                    Sort = BrandId,
                    SeoTitle = Month,
                    MakerCode = MakerCode,
                    RealName = RealName,
                    UserLevel = UserLevel,
                    Rank = Rank,
                    KqSnNo = KqSnNo,
                    MerchantName = MerchantName,
                    DirectFlag = DirectFlag,
                    BrandName = BrandName,
                    CreditTradeAmt = CreditTradeAmt,
                    SubsidyProfit = SubsidyProfit,
                });
                if(index % 200 == 0)
                {
                    db.SaveChanges();
                }
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + index, "分润结果检查");
            }
            db.SaveChanges();
            db.Dispose();
        }

        public void CheckProfit()
        {
            DateTime now = DateTime.Now;
            string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            WebCMSEntities db = new WebCMSEntities();
            bool checkOp = true;
            int StartId = 0;
            while(checkOp)
            {
                List<int> ids = new List<int>();
                List<ProfitRewardExport> list = db.ProfitRewardExport.Where(m => m.SeoTitle == Month && m.Id > StartId && m.Status == 0).OrderBy(m => m.MakerCode).ThenBy(m => m.DirectFlag).ThenBy(m => m.BrandName).ThenBy(m => m.Id).Take(50).ToList();
                LogHelper.Instance.WriteLog(DateTime.Now.ToString() + ":" + list.Count, "分润结果检查");
                if(list.Count > 0)
                {
                    int index = 0;
                    foreach(ProfitRewardExport sub in list)
                    {
                        index += 1;
                        int BrandId = sub.Sort;
                        string MakerCode = sub.MakerCode;
                        decimal TotalProfit = 0;
                        UserForMakerCode userForMakerCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new UserForMakerCode();
                        int UserId = userForMakerCode.UserId;
                        Users user = db.Users.FirstOrDefault(m => m.Id == UserId);
                        if(user == null)
                        {
                            user = db.Users.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new Users();
                            UserId = user.Id;
                        }
                        string LogString = function.ReadInstance("/ProfitDetailLog/" + Month + "/" + UserId + ".txt");
                        LogString += "创客编号：" + user.MakerCode + "，创客名称：" + user.RealName + "\n";
                        int UserLevel = GetLevel(db, UserId, user.UserLevel);
                        LogString += "创客职级：K" + UserLevel + "\n";
                        LogString += "分润类型：" + sub.DirectFlag + "\n";
                        LogString += "分润品牌：" + sub.BrandName + "\n";
                        if(sub.DirectFlag == "直营")
                        {
                            decimal HelpTradeAmt = 0;
                            decimal NotHelpTradeAmt = 0;
                            decimal ProfitTradeAmt = 0;
                            decimal HelpProfit = 0;
                            decimal NotHelpProfit = 0;
                            decimal ProfitProfit = 0;
                            bool check = db.TradeDaySummary.Any(m => m.UserId == user.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "self" && m.HelpDirectTradeAmt > 0);
                            if(check)
                            {
                                HelpTradeAmt = db.TradeDaySummary.Where(m => m.UserId == user.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "self").Sum(m => m.HelpDirectTradeAmt);
                            }
                            LogString += "扶持期交易额：" + HelpTradeAmt + "\n";
                            check = db.TradeDaySummary.Any(m => m.UserId == user.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "self" && m.NotHelpDirectTradeAmt > 0);
                            if(check)
                            {
                                NotHelpTradeAmt = db.TradeDaySummary.Where(m => m.UserId == user.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "self").Sum(m => m.NotHelpDirectTradeAmt);
                            }
                            LogString += "稳定期交易额：" + NotHelpTradeAmt + "\n";
                            check = db.TradeDaySummary.Any(m => m.UserId == user.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "self" && m.ProfitDirectTradeAmt > 0);
                            if(check)
                            {
                                ProfitTradeAmt = db.TradeDaySummary.Where(m => m.UserId == user.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "self").Sum(m => m.ProfitDirectTradeAmt);
                            }
                            LogString += "盈利期交易额：" + ProfitTradeAmt + "\n";
                            if(HelpTradeAmt > 0)
                            {
                                decimal percent = GetLevelProfit(BrandId, UserLevel, 1);
                                HelpProfit = HelpTradeAmt * percent;
                                LogString += "扶持期分润：" + HelpTradeAmt + " * " + percent + " = " + HelpProfit + "\n";
                            }
                            if(NotHelpTradeAmt > 0)
                            {
                                decimal percent = GetLevelProfit(BrandId, UserLevel, 0);
                                NotHelpProfit = NotHelpTradeAmt * percent;
                                LogString += "稳定期分润：" + NotHelpTradeAmt + " * " + percent + " = " + NotHelpProfit + "\n";
                            }
                            if(ProfitTradeAmt > 0)
                            {
                                decimal percent = GetLevelProfit(BrandId, UserLevel, 2);
                                ProfitProfit = ProfitTradeAmt * percent;
                                LogString += "盈利期分润：" + ProfitTradeAmt + " * " + percent + " = " + ProfitProfit + "\n";
                            }
                            TotalProfit += HelpProfit + NotHelpProfit + ProfitProfit;
                            LogString += "总分润：" + TotalProfit + "\n";
                        }
                        else
                        {
                            var subusers = db.Users.Select(m => new { m.Id, m.ParentUserId, m.AuthFlag }).Where(m => m.ParentUserId == UserId && m.AuthFlag == 1).ToList();
                            LogString += "直推人数：" + subusers.Count + "\n";
                            foreach(var subuser in subusers)
                            {
                                Users suser = db.Users.FirstOrDefault(m => m.Id == subuser.Id) ?? new Users();
                                LogString += "直推创客编号：" + suser.MakerCode + "，直推创客名称：" + suser.RealName + "\n";
                                int sUserLevel = GetLevel(db, subuser.Id, suser.UserLevel);
                                LogString += "直推创客职级：K" + sUserLevel + "\n";
                                if(sUserLevel < UserLevel)
                                {
                                    decimal HelpTradeAmt = 0;
                                    decimal NotHelpTradeAmt = 0;
                                    decimal ProfitTradeAmt = 0;
                                    decimal HelpProfit = 0;
                                    decimal NotHelpProfit = 0;
                                    decimal ProfitProfit = 0;
                                    bool check = db.TradeDaySummary.Any(m => m.UserId == subuser.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team" && m.HelpNonDirectTradeAmt > 0);
                                    if(check)
                                    {
                                        HelpTradeAmt = db.TradeDaySummary.Where(m => m.UserId == subuser.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team").Sum(m => m.HelpNonDirectTradeAmt);
                                    }
                                    LogString += "扶持期交易额：" + HelpTradeAmt + "\n";
                                    check = db.TradeDaySummary.Any(m => m.UserId == subuser.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team" && m.NotHelpNonDirectTradeAmt > 0);
                                    if(check)
                                    {
                                        NotHelpTradeAmt = db.TradeDaySummary.Where(m => m.UserId == subuser.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team").Sum(m => m.NotHelpNonDirectTradeAmt);
                                    }
                                    LogString += "稳定期交易额：" + NotHelpTradeAmt + "\n";
                                    check = db.TradeDaySummary.Any(m => m.UserId == subuser.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team" && m.ProfitNonDirectTradeAmt > 0);
                                    if(check)
                                    {
                                        ProfitTradeAmt = db.TradeDaySummary.Where(m => m.UserId == subuser.Id && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team").Sum(m => m.ProfitNonDirectTradeAmt);
                                    }
                                    LogString += "盈利期交易额：" + ProfitTradeAmt + "\n";

                                    string UserIdString = "," + subuser.Id + ",";
                                    List<Users> busers = db.Users.Where(m => m.ParentNav.Contains(UserIdString) && m.AuthFlag == 1).ToList();
                                    List<ProfitUsers> busernavs = new List<ProfitUsers>();
                                    foreach (var buser in busers)
                                    {
                                        int bUserLevel = GetLevel(db, buser.Id, buser.UserLevel);
                                        if(bUserLevel >= UserLevel)
                                        {
                                            busernavs.Add(new ProfitUsers()
                                            {
                                                UserId = buser.Id,
                                                UserLevel = bUserLevel,
                                                UserNav = buser.ParentNav,
                                                MakerCode = buser.MakerCode,
                                                RealName = buser.RealName,
                                            });
                                        }
                                        if(bUserLevel > sUserLevel)
                                        {
                                            sUserLevel = bUserLevel;
                                        }
                                    }
                                    string LogHelpTradeAmt = HelpTradeAmt.ToString();
                                    string LogNotHelpTradeAmt = NotHelpTradeAmt.ToString();
                                    string LogProfitTradeAmt = ProfitTradeAmt.ToString();
                                    if(busernavs.Count > 0)
                                    {
                                        LogString += "团队中等级超过K" + UserLevel + "：\n";
                                        LogString += "..................\n";
                                        List<string> ParentNavs = new List<string>();
                                        busernavs = busernavs.OrderBy(m => m.UserNav).ToList();
                                        foreach(ProfitUsers busernav in busernavs)
                                        {
                                            bool op = true; //是否满足条件
                                            string ParentNav = busernav.UserNav + "," + busernav.UserId + ",";
                                            foreach (string subNav in ParentNavs)
                                            {
                                                if (ParentNav.StartsWith(subNav) && ParentNav != subNav)
                                                {
                                                    op = false;
                                                }
                                            }
                                            if(op)
                                            {
                                                bool OtherCheck = db.TradeDaySummary.Any(m => m.UserId == busernav.UserId && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team" && m.HelpNonDirectTradeAmt > 0);
                                                decimal OtherHelpTradeAmt = 0;
                                                decimal OtherNotHelpTradeAmt = 0;
                                                decimal OtherProfitTradeAmt = 0;
                                                if(OtherCheck)
                                                {
                                                    OtherHelpTradeAmt = db.TradeDaySummary.Where(m => m.UserId == busernav.UserId && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team").Sum(m => m.HelpNonDirectTradeAmt);
                                                }
                                                OtherCheck = db.TradeDaySummary.Any(m => m.UserId == busernav.UserId && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team" && m.NotHelpNonDirectTradeAmt > 0);
                                                if(OtherCheck)
                                                {
                                                    OtherNotHelpTradeAmt = db.TradeDaySummary.Where(m => m.UserId == busernav.UserId && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team").Sum(m => m.NotHelpNonDirectTradeAmt);
                                                }
                                                OtherCheck = db.TradeDaySummary.Any(m => m.UserId == busernav.UserId && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team" && m.ProfitNonDirectTradeAmt > 0);
                                                if(OtherCheck)
                                                {
                                                    OtherProfitTradeAmt = db.TradeDaySummary.Where(m => m.UserId == busernav.UserId && m.TradeMonth == Month && m.BrandId == BrandId && m.SeoTitle == "team").Sum(m => m.ProfitNonDirectTradeAmt);
                                                }
                                                HelpTradeAmt -= OtherHelpTradeAmt;
                                                NotHelpTradeAmt -= OtherNotHelpTradeAmt;
                                                ProfitTradeAmt -= OtherProfitTradeAmt;
                                                LogString += "\n----创客编号：" + busernav.MakerCode + "，创客名称：" + busernav.RealName + "\n";
                                                LogString += "----创客职级：" + busernav.UserLevel + "\n";
                                                LogString += "----扶持期交易额：" + OtherHelpTradeAmt + "\n";
                                                LogString += "----稳定期交易额：" + OtherNotHelpTradeAmt + "\n";
                                                LogString += "----盈利期交易额：" + OtherProfitTradeAmt + "\n";
                                                if(OtherHelpTradeAmt > 0)
                                                {
                                                    LogHelpTradeAmt += " - " + OtherHelpTradeAmt;
                                                }
                                                if(OtherNotHelpTradeAmt > 0)
                                                {
                                                    LogNotHelpTradeAmt += " - " + OtherNotHelpTradeAmt;
                                                }
                                                if(OtherProfitTradeAmt > 0)
                                                {
                                                    LogProfitTradeAmt += " - " + OtherProfitTradeAmt;
                                                }
                                            }
                                            ParentNavs.Add(ParentNav);
                                        }
                                    }
                                    if(HelpTradeAmt > 0)
                                    {
                                        decimal parentpercent = GetLevelProfit(BrandId, UserLevel, 1);
                                        decimal percent = GetLevelProfit(BrandId, sUserLevel, 1);
                                        HelpProfit = HelpTradeAmt * (parentpercent - percent);
                                        if(LogHelpTradeAmt.Contains("-"))
                                        {
                                            LogHelpTradeAmt = "(" + LogHelpTradeAmt + ")";
                                        }
                                        LogString += "扶持期分润：" + LogHelpTradeAmt + " * (" + parentpercent + " - " + percent + ") = " + HelpProfit + "\n";
                                    }
                                    if(NotHelpTradeAmt > 0)
                                    {
                                        decimal parentpercent = GetLevelProfit(BrandId, UserLevel, 0);
                                        decimal percent = GetLevelProfit(BrandId, sUserLevel, 0);
                                        if(LogNotHelpTradeAmt.Contains("-"))
                                        {
                                            LogNotHelpTradeAmt = "(" + LogNotHelpTradeAmt + ")";
                                        }
                                        NotHelpProfit = NotHelpTradeAmt * (parentpercent - percent);
                                        LogString += "稳定期分润：" + LogNotHelpTradeAmt + " * (" + parentpercent + " - " + percent + ") = " + NotHelpProfit + "\n";
                                    }
                                    if(ProfitTradeAmt > 0)
                                    {
                                        decimal parentpercent = GetLevelProfit(BrandId, UserLevel, 2);
                                        decimal percent = GetLevelProfit(BrandId, sUserLevel, 2);
                                        if(LogProfitTradeAmt.Contains("-"))
                                        {
                                            LogProfitTradeAmt = "(" + LogProfitTradeAmt + ")";
                                        }
                                        ProfitProfit = ProfitTradeAmt * (parentpercent - percent);
                                        LogString += "盈利期分润：" + LogProfitTradeAmt + " * (" + parentpercent + " - " + percent + ") = " + ProfitProfit + "\n";
                                    }
                                    decimal SubTotalProfit = HelpProfit + NotHelpProfit + ProfitProfit;
                                    TotalProfit += SubTotalProfit;
                                    LogString += "总分润：" + SubTotalProfit + "\n";
                                }
                                LogString += "--------------------------------------------------------------\n";
                            }
                        }
                        decimal CheckProfit = sub.CreditTradeProfit - TotalProfit;
                        string Result = "通过";
                        if(Math.Abs(CheckProfit) > 10)
                        {
                            Result = "分润有误";
                        }
                        LogString += "系统分润：" + sub.CreditTradeProfit + "\n";
                        LogString += "核对分润：" + TotalProfit + "\n";
                        LogString += "核对结果：" + Result + "\n";
                        LogString += "===================================================================================\n\n\n";
                        function.WritePage("/ProfitDetailLog/" + Month + "/", UserId + ".txt", LogString);
                        ProfitRewardExport edit = db.ProfitRewardExport.FirstOrDefault(m => m.Id == sub.Id);
                        if(edit != null)
                        {
                            edit.SeoKeyword = TotalProfit.ToString();
                            edit.SeoDescription = Result;
                            edit.Status = 1;
                            db.SaveChanges();
                        }
                        StartId = sub.Id;
                        LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "-" + index, "分润结果检查");
                    }
                }
                else
                {
                    checkOp = false;
                }
            }
            db.Dispose();
        }

        public void CheckSubsidy()
        {
            DateTime now = DateTime.Now;
            string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            WebCMSEntities db = new WebCMSEntities();
            bool op = true;
            int StartId = 0;
            while(op)
            {
                List<ProfitSubsidyExport> list = db.ProfitSubsidyExport.Where(m => m.SeoTitle == Month && m.Id > StartId).OrderBy(m => m.Id).Take(50).ToList();
                if(list.Count > 0)
                {
                    foreach(ProfitSubsidyExport sub in list)
                    {
                        int BrandId = sub.Sort;
                        string MakerCode = sub.MakerCode;
                        UserForMakerCode userForMakerCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new UserForMakerCode();
                        int UserId = userForMakerCode.UserId;
                        Users user = db.Users.FirstOrDefault(m => m.Id == UserId);
                        if(user == null)
                        {
                            user = db.Users.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new Users();
                            UserId = user.Id;
                        }
                        MachineForSnNo machineForSn = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == sub.KqSnNo) ?? new MachineForSnNo();
                        PosMachinesTwo machine = db.PosMachinesTwo.FirstOrDefault(m => m.Id == machineForSn.SnId) ?? new PosMachinesTwo();
                        int UserLevel = GetLevel(db, UserId, user.UserLevel);
                        decimal HelpTradeAmt = 0;
                        bool check = db.PosMerchantTradeSummay.Any(m => m.MerchantId == machine.BindMerchantId && m.TradeMonth == Month && m.BrandId == BrandId && m.TradeAmount > 0);
                        if(check)
                        {
                            HelpTradeAmt = db.PosMerchantTradeSummay.Where(m => m.MerchantId == machine.BindMerchantId && m.TradeMonth == Month && m.BrandId == BrandId).Sum(m => m.TradeAmount);
                        }
                        decimal percent = GetLevelProfit(BrandId, UserLevel, 1);
                        decimal HelpProfit = (0.001M - percent) * HelpTradeAmt;
                        decimal CheckProfit = sub.SubsidyProfit - HelpProfit;
                        string Result = "通过";
                        if(Math.Abs(CheckProfit) > 0.01M)
                        {
                            Result = "补贴有误";
                        }
                        ProfitSubsidyExport edit = db.ProfitSubsidyExport.FirstOrDefault(m => m.Id == sub.Id);
                        if(edit != null)
                        {
                            edit.SeoKeyword = HelpProfit.ToString();
                            edit.SeoDescription = Result;
                            edit.Status = 1;
                            db.SaveChanges();
                        }
                        StartId = sub.Id;
                    }
                }
                else
                {
                    op = false;
                }
            }
            db.Dispose();
        }

        //获取创客当前等级
        private int GetLevel(WebCMSEntities db, int UserId, int UserLevel)
        {
            DateTime now = DateTime.Now;
            DateTime ThisMonth = DateTime.Parse(DateTime.Now.ToString("yyyy-MM") + "-01 00:00:00");
            UserRankWhite rank = db.UserRankWhite.FirstOrDefault(m => m.Id == UserId && m.CreateDate < ThisMonth && m.UpdateDate > now);
            if (rank != null)
            {
                if (rank.Rank > UserLevel)
                {
                    UserLevel = rank.Rank;
                }
            }
            return UserLevel;
        }

        //获取等级分润比例
        private decimal GetLevelProfit(int BrandId, int UserLevel, int Help)
        {
            int LevelKindId = ProfitHelperV2.Instance.GetLevelKindId(BrandId, Help, 1);
            ProfitObjectLevels objlevel = RedisDbconn.Instance.Get<ProfitObjectLevels>("pobjlv" + LevelKindId + ":" + UserLevel); //获取当前等级参数
            if (objlevel != null)
            {
                return objlevel.Percents;
            }
            return 0;
        }
    }
}