using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Data;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MySystem.PxcModels;
using System.Threading;
using Library;
using LitJson;

namespace MySystem.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Error()
        {
            string isapi = Request.Headers["Api"].ToString();
            if (isapi != "1")
            {
                if (Response.StatusCode == 500)
                {
                    return Redirect("/public/errpage/pc/500.html");
                }
                else if (Response.StatusCode == 502)
                {
                    return Redirect("/public/errpage/pc/502.html");
                }
                else if (Response.StatusCode == 404)
                {
                    return Redirect("/public/errpage/pc/404.html");
                }
            }
            return View();
        }


        private static object o = new object();
        public string addmer(string mid, int k = 0)
        {
            MerchantConfirmService.Instance.Start(mid, k);
            return "ok";
        }

        public string setqrcode(int uid = 0)
        {
            return "ok";
        }

        public string userqrcode(int uid)
        {
            WebCMSEntities db = new WebCMSEntities();
            Users user = db.Users.FirstOrDefault(m => m.Id == uid);
            if (user != null)
            {
                MakeReferenceQrCodeService.Instance.Start(user.Id.ToString());
                return "ok";
            }
            db.Dispose();
            return "fail";
        }

        public string getqrcode(int uid, int pid)
        {
            WebCMSEntities db = new WebCMSEntities();
            Users user = db.Users.FirstOrDefault(m => m.Id == uid);
            if (user != null)
            {
                return MakeReferenceQrCodeService.Instance.MergeQrCode(user, pid);
            }
            db.Dispose();
            return "fail";
        }

        private void th1()
        {
            Thread th = new Thread(th1do);
            th.IsBackground = true;
            th.Start();
        }
        private void th1do()
        {
            WebCMSEntities db = new WebCMSEntities();
            Users user = db.Users.FirstOrDefault(m => m.Id == 2);
            if (user != null)
            {
                user.SeoTitle = "111111";
                Thread.Sleep(5000);
                user.SeoDescription = "222222";
                db.SaveChanges();
            }
            db.Dispose();
        }
        private void th2()
        {
            Thread th = new Thread(th2do);
            th.IsBackground = true;
            th.Start();
        }
        private void th2do()
        {
            Thread.Sleep(2000);
            WebCMSEntities db = new WebCMSEntities();
            Users user = db.Users.FirstOrDefault(m => m.Id == 2);
            if (user != null)
            {
                user.SeoKeyword = "看看有没有值写入";
                db.SaveChanges();
            }
            db.Dispose();
        }

        // 补激活奖励
        public string setmeruser(string date)
        {
            StatService.Instance.dosomething1(date);
            return "ok";
        }
        // 补发小盟主15000返现
        public string LeaderBack(int oid)
        {
            WebCMSEntities db = new WebCMSEntities();
            Orders order = db.Orders.FirstOrDefault(m => m.Id == oid);
            if(order != null)
            {
                AlipayPayBack2Service.Instance.LeaderBack(db, order);
            }
            db.Dispose();
            return "ok";
        }
        public string chkactprize(int Id = 0)
        {
            if (Id > 0)
            {
                StatService.Instance.dosomething3(Id);
            }
            return "ok";
        }
        public string chkactprize2(int Id = 0)
        {
            if (Id > 0)
            {
                StatService.Instance.activePrizeWithoutDeposit(Id);
            }
            return "ok";
        }

        public string mutilactprize()
        {
            List<int> ids = new List<int>();
            WebCMSEntities db = new WebCMSEntities();
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            foreach (int id in ids)
            {
                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == id);
                if (pos != null)
                {
                    SpModels.ActivateRecord act = spdb.ActivateRecord.FirstOrDefault(m => m.SnNo == pos.PosSn && m.SeoTitle != "0" && !string.IsNullOrEmpty(m.SeoTitle));
                    if (act != null)
                    {
                        pos.SeoKeyword = act.SeoTitle;
                        db.SaveChanges();
                        StatService.Instance.dosomething3(pos.Id);
                    }
                }
            }
            db.Dispose();
            spdb.Dispose();
            return "ok";
        }

        public string scanBind()
        {
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
            var Binds = spdb.BindRecord.Select(m => new { m.Id, m.CreateTime, m.Status, m.MerNo, m.MerSnNo }).OrderBy(m => m.Id).ToList();
            foreach (var Bind in Binds)
            {
                var tran = db.Database.BeginTransaction();
                try
                {
                    PxcModels.MachineForSnNo posFor = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == Bind.MerSnNo) ?? new PxcModels.MachineForSnNo();
                    PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == posFor.SnId);
                    if (pos != null)
                    {
                        if (pos.BindingState == 0)
                        {
                            pos.BindingState = 1;
                            pos.BindingTime = Bind.CreateTime;
                            PxcModels.MachineForMerNo merFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == Bind.MerNo);
                            if (merFor == null)
                            {
                                merFor = db.MachineForMerNo.Add(new PxcModels.MachineForMerNo()
                                {
                                    MerNo = Bind.MerNo,
                                    SnId = pos.Id,
                                }).Entity;
                            }
                            db.SaveChanges();
                            tran.Commit();
                            function.WriteLog(pos.PosSn, "补充绑定数据");
                        }
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n" + Bind.Id, "同步SP绑定数据到MAIN异常");
                }
                tran.Dispose();
            }
            spdb.SaveChanges();
            spdb.Dispose();
            db.SaveChanges();
            db.Dispose();
            return "ok";
        }

        public string scanMerchant()
        {
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
            var Mers = spdb.Merchants.OrderBy(m => m.Id).ToList();
            foreach (var Mer in Mers)
            {
                var tran = db.Database.BeginTransaction();
                try
                {
                    PxcModels.MachineForMerNo posFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == Mer.MerNo) ?? new PxcModels.MachineForMerNo();
                    PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == posFor.SnId) ?? new PxcModels.PosMachinesTwo();
                    if (pos.BindingState == 1)
                    {
                        PxcModels.Users user = db.Users.FirstOrDefault(m => m.Id == pos.UserId) ?? new PxcModels.Users();
                        int TopUserId = 0;
                        if (!string.IsNullOrEmpty(user.ParentNav))
                        {
                            TopUserId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                        }
                        int BrandId = int.Parse(Mer.ProductType);
                        if (Mer.MerNo.StartsWith("M900"))
                        {
                            BrandId = 3;
                        }
                        bool check = db.PosMerchantInfo.Any(m => m.KqMerNo == Mer.MerNo);
                        if (!check)
                        {
                            PxcModels.PosMerchantInfo add = db.PosMerchantInfo.Add(new PxcModels.PosMerchantInfo()
                            {
                                CreateDate = Mer.CreateTime,
                                UpdateDate = Mer.UpdateTime,
                                TopUserId = TopUserId,
                                MerUserType = user.MerchantType,
                                BrandId = BrandId,
                                SnStoreId = pos.StoreId,
                                SnType = pos.PosSnType,
                                UserId = pos.UserId,
                                MgrName = Mer.AgentName,
                                MerStatus = 1,
                                KqSnNo = Mer.SnNo,
                                KqMerNo = Mer.MerNo,
                                MerIdcardNo = Mer.MerIdcardNo,
                                MerRealName = Mer.MerRealName,
                                MerchantMobile = Mer.MerMobile,
                                MerchantName = Mer.MerName,
                                MerchantNo = Mer.MerNo.Length > 16 ? Mer.MerNo.Substring(0, 16) : Mer.MerNo,
                            }).Entity;
                            db.SaveChanges();
                            pos.BindMerchantId = add.Id;
                            db.SaveChanges();
                            tran.Commit();
                            function.WriteLog(Mer.MerNo, "补充商户数据");
                        }
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n" + Mer.Id, "同步SP商户数据到MAIN异常");
                }
                tran.Dispose();
            }
            spdb.Dispose();
            db.Dispose();
            return "ok";
        }

        public string scanTrade()
        {
            SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
            PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
            IQueryable<SpModels.TradeRecord> trades = spdb.TradeRecord.OrderBy(m => m.Id);
            foreach (SpModels.TradeRecord trade in trades.ToList())
            {
                bool op = true;
                if (trade.SerEntryMode == "N")
                {
                    if (trade.TradeAmount == 9900 || trade.TradeAmount == 19900 || trade.TradeAmount == 29900)
                    {
                        op = false;
                        PxcModels.MachineForMerNo posFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == trade.MerNo) ?? new PxcModels.MachineForMerNo();
                        PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == posFor.SnId);
                        if (pos != null)
                        {
                            if (trade.SerEntryMode == "N" && trade.ProductType == "1")
                            {
                                pos.SeoKeyword = trade.TradeAmount.ToString("f2");
                                db.SaveChanges();
                            }
                        }
                    }
                }
                if (op)
                {
                    PxcModels.MachineForMerNo posFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == trade.MerNo) ?? new PxcModels.MachineForMerNo();
                    PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == posFor.SnId);
                    if (pos != null)
                    {
                        if (pos.BindMerchantId > 0)
                        {
                            PxcModels.Users user = db.Users.FirstOrDefault(m => m.Id == pos.UserId) ?? new PxcModels.Users();
                            int TopUserId = 0;
                            if (!string.IsNullOrEmpty(user.ParentNav))
                            {
                                TopUserId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                            }
                            bool check = db.TradeRecord.Any(m => m.RecordNo == trade.TradeSerialNo);
                            if (!check)
                            {
                                decimal TradeAmount = trade.TradeAmount;
                                int BankCardType = -1;
                                int QrPayFlag = 0;
                                if (pos.BrandId == 1 || pos.BrandId == 3)
                                {
                                    TradeAmount = TradeAmount / 100;
                                    BankCardType = int.Parse(trade.BankCardType);
                                    if (trade.TradeType == "02") QrPayFlag = 1;
                                }
                                else if (pos.BrandId == 2)
                                {
                                    if (trade.TradeType == "CREDIT_BY_CARD")
                                    {
                                        BankCardType = 1;
                                    }
                                    else if (trade.TradeType == "DEBIT_BY_CARD")
                                    {
                                        BankCardType = 0;
                                    }
                                    if (trade.TradeType == "CLOUD_PAY") QrPayFlag = 1;
                                }
                                int BrandId = int.Parse(trade.ProductType);
                                if (trade.MerNo.StartsWith("M900"))
                                {
                                    BrandId = 3;
                                }
                                db.TradeRecord.Add(new PxcModels.TradeRecord()
                                {
                                    CreateDate = trade.CreateDate,
                                    UpdateDate = trade.UpdateDate,
                                    RecordNo = trade.TradeSerialNo, //单号
                                    UserId = pos.UserId, //创客
                                    MerchantId = pos.BindMerchantId, //商户
                                    MerNo = trade.MerNo, //渠道商户编号
                                    MerHelpFlag = 0, //是否属于扶持周期内商户
                                    HelpMonthCount = 0, //扶持第几个月
                                    MerBuddyType = user.MerchantType, //商户创客类型
                                    SnNo = trade.TradeSnNo, //渠道SN号
                                    // TradeDate = DateTime.Parse(trade.TradeTime), //交易日期
                                    TradeSerialNo = trade.ChannelSerial, //交易流水号
                                    TradeAmount = TradeAmount, //交易金额
                                    BankCardType = BankCardType, //银行卡类型
                                    QrPayFlag = QrPayFlag, //云闪付标识
                                    BrandId = BrandId, //品牌
                                    Remark = trade.Remark, //备注
                                    TopUserId = TopUserId, //顶级创客
                                    MerUserId = pos.UserId, //商户直属创客
                                    ParentNav = user.ParentNav,
                                });
                                if (BankCardType == 1)
                                {
                                    pos.CreditTrade += TradeAmount;
                                }
                                else if (BankCardType == 0)
                                {
                                    pos.DebitCardTrade += TradeAmount;
                                }
                                else if (pos.CreditTrade >= 1000 && pos.ActivationState == 0 && pos.BindingTime > DateTime.Now.AddDays(-20))
                                {
                                    // pos.IsPurchase = 0;
                                    pos.ActivationState = 1;
                                    pos.ActivationTime = DateTime.Now;
                                    PxcModels.PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                                    if (merchant != null)
                                    {
                                        merchant.ActiveStatus = 1;
                                        merchant.MerStandardDate = DateTime.Now;
                                        db.SaveChanges();
                                    }
                                }
                                db.SaveChanges();
                                function.WriteLog(trade.Id.ToString(), "补充交易数据");
                            }
                        }
                    }
                }
            }
            spdb.Dispose();
            db.Dispose();
            return "ok";
        }

        // public string add100()
        // {
        //     WebCMSEntities db = new WebCMSEntities();
        //     List<int> uids = new List<int>();
        //     uids.Add(1053);
        //     foreach (int uid in uids)
        //     {
        //         int ParentUserId = uid;
        //         int machineCount = db.PosMachinesTwo.Count(m => m.UserId == ParentUserId && m.PosSnType == 0); //判断是否拥有3台兑换机
        //         int ActiveCount = db.PosMachinesTwo.Count(m => m.UserId == ParentUserId && m.ActivationState == 1); //判断是否拥有3台激活机（不限购买或赠送）
        //         if (machineCount + ActiveCount >= 3)
        //         {
        //             UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == ParentUserId);
        //             if (account == null)
        //             {
        //                 account = db.UserAccount.Add(new UserAccount()
        //                 {
        //                     Id = ParentUserId,
        //                     UserId = ParentUserId,
        //                 }).Entity;
        //                 db.SaveChanges();
        //             }
        //             decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
        //             decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
        //             decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
        //             account.BalanceAmount += 100;
        //             account.TotalAmount += 100;
        //             decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
        //             decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
        //             decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
        //             UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
        //             {
        //                 CreateDate = DateTime.Now,
        //                 UpdateDate = DateTime.Now,
        //                 UserId = ParentUserId, //创客
        //                 ChangeType = 112, //变动类型
        //                 ChangeAmount = 100, //变更金额
        //                 BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
        //                 AfterTotalAmount = AfterTotalAmount, //变更后总金额
        //                 BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
        //                 AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
        //                 BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
        //                 AfterBalanceAmount = AfterBalanceAmount, //变更后余额
        //             }).Entity;
        //             db.SaveChanges();

        //             //推荐下单上级获得30天的机具循环天数
        //             var posList = db.PosMachinesTwo.Select(m => new { m.Id, m.UserId, m.BindingState, m.RecycEndDate }).Where(m => m.UserId == ParentUserId && m.BindingState == 0 && m.RecycEndDate != null).ToList();
        //             foreach (var subPos in posList)
        //             {
        //                 PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == subPos.Id);
        //                 if (pos != null)
        //                 {
        //                     pos.RecycEndDate = pos.RecycEndDate.Value.AddDays(30);
        //                 }
        //             }
        //             db.SaveChanges();
        //         }
        //     }
        //     db.Dispose();
        //     return "finish";
        // }

        //交易不到1000的机具，顶级姓名-代理姓名-客户姓名-客户电话-开机日期-SN // TODO:做到BS后台导出，按绑定时间查
        public IActionResult PosTable()
        {
            WebCMSEntities db = new WebCMSEntities();
            List<PosMachinesTwo> poses = db.PosMachinesTwo.Where(m => m.CreditTrade < 1000 && m.BindingState == 1).ToList();
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
            foreach (PosMachinesTwo pos in poses)
            {
                PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId) ?? new PosMerchantInfo();
                Users user = db.Users.FirstOrDefault(m => m.Id == pos.UserId) ?? new Users();
                Users puser = db.Users.FirstOrDefault(m => m.Id == user.ParentUserId) ?? new Users();
                Users ppuser = db.Users.FirstOrDefault(m => m.Id == puser.ParentUserId) ?? new Users();
                Dictionary<string, string> item = new Dictionary<string, string>();
                string TopRealName = "";
                string TopMakerCode = "";
                string TopMobile = "";
                string ParentNav = user.ParentNav;
                if (!string.IsNullOrEmpty(ParentNav))
                {
                    string[] navlist = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    if (navlist.Length > 1)
                    {
                        int TopId = int.Parse(function.CheckInt(navlist[1]));
                        Users tuser = db.Users.FirstOrDefault(m => m.Id == TopId) ?? new Users();
                        TopRealName = tuser.RealName;
                        TopMakerCode = tuser.MakerCode;
                        TopMobile = tuser.Mobile;
                    }
                }
                item.Add("TopRealName", TopRealName); //顶级姓名
                item.Add("TopMakerCode", TopMakerCode); //顶级编号
                item.Add("UpUpRealName", ppuser.RealName); //上上级姓名
                item.Add("UpRealName", puser.RealName); //上级姓名
                item.Add("RealName", user.RealName); //代理姓名
                item.Add("MakerCode", user.MakerCode); //代理编号
                item.Add("Mobile", user.Mobile); //代理手机号
                item.Add("MerchantName", merchant.MerchantName); //客户姓名
                item.Add("MerchantMobile", merchant.MerchantMobile); //客户电话
                item.Add("OpenTime", pos.BindingTime == null ? "" : pos.BindingTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); //开机日期
                item.Add("Sn", pos.PosSn); //SN
                list.Add(item);
            }
            db.Dispose();
            ViewBag.list = list;
            return View();
        }
        
        public string resetpos(int uid, int kind)
        {
            WebCMSEntities db = new WebCMSEntities();
            string IdBrand = uid + "_" + kind;
            UserMachineData machineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
            if (machineData == null)
            {
                machineData = db.UserMachineData.Add(new UserMachineData()
                {
                    IdBrand = IdBrand
                }).Entity;
                db.SaveChanges();
            }
            machineData.BindCount = db.PosMachinesTwo.Count(m => m.Status > -1 && m.BuyUserId == uid && m.BrandId == kind && m.BindingState == 1);
            machineData.UnBindCount = db.PosMachinesTwo.Count(m => m.Status > -1 && m.BuyUserId == uid && m.BrandId == kind && m.BindingState == 0);
            machineData.TotalMachineCount = machineData.BindCount + machineData.UnBindCount;
            db.SaveChanges();
            db.Dispose();
            return "finish";
        }

        // 更新分仓库存
        public string resetstorestock()
        {
            WebCMSEntities db = new WebCMSEntities();
            DataTable dt = dbconn.dtable("select s.Id,LaveNum,count(p.Id) as CurLaveNum from StoreHouse s left join PosMachinesTwo p on s.Id=p.StoreId and s.BrandId=p.BrandId and p.UserId=0 group by s.Id HAVING LaveNum!=count(p.Id)");
            foreach (DataRow dr in dt.Rows)
            {
                int Id = int.Parse(function.CheckInt(dr["Id"].ToString()));
                int CurLaveNum = int.Parse(function.CheckInt(dr["CurLaveNum"].ToString()));
                StoreHouse store = db.StoreHouse.FirstOrDefault(m => m.Id == Id);
                if (store != null)
                {
                    store.LaveNum = CurLaveNum;
                    db.SaveChanges();
                }
            }
            db.Dispose();
            return "ok";
        }
        public string resetstorestock2(int id)
        {
            WebCMSEntities db = new WebCMSEntities();
            DataTable dt = dbconn.dtable("select Id,LaveNum,(select count(Id) from PosMachinesTwo where StoreId=s.Id and UserId=0) as CurLaveNum from StoreHouse s where Id=" + id);
            foreach (DataRow dr in dt.Rows)
            {
                int Id = int.Parse(function.CheckInt(dr["Id"].ToString()));
                int CurLaveNum = int.Parse(function.CheckInt(dr["CurLaveNum"].ToString()));
                StoreHouse store = db.StoreHouse.FirstOrDefault(m => m.Id == Id);
                if (store != null)
                {
                    store.LaveNum = CurLaveNum;
                    db.SaveChanges();
                }
            }
            db.Dispose();
            return "ok";
        }

        public string chkpwd(string pwd)
        {
            return function.MD532(pwd);
        }

        //重置本月团队交易额
        public string resetMonthTrade()
        {

            return "";
        }

        public string traderecord(int kind, int id = 0)
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
            if (kind == 1)
            {
                OtherMySqlConn.op("delete from TradeRecordTest;insert into TradeRecordTest (Sort,QueryCount,Status,Version,CreateDate,UpdateDate,CreateMan,UpdateMan,SeoTitle,SeoKeyword,SeoDescription,MerUserId,TopUserId,Remark,BrandId,DirectFlag,CapFlag,QrPayFlag,BankCardType,TradeAmount,TradeSerialNo,ClearDate,TradeDate,SnNo,MerBuddyType,HelpMonthCount,MerHelpFlag,MerNo,MerchantId,UserId,RecordNo) select Sort,QueryCount,Status,Version,CreateDate,UpdateDate,CreateMan,UpdateMan,SeoTitle,SeoKeyword,SeoDescription,MerUserId,TopUserId,Remark,BrandId,DirectFlag,CapFlag,QrPayFlag,BankCardType,TradeAmount,TradeSerialNo,ClearDate,TradeDate,SnNo,MerBuddyType,HelpMonthCount,MerHelpFlag,MerNo,MerchantId,UserId,RecordNo from TradeRecord order by CreateDate;");
            }
            else if (kind == 2)
            {
                OtherMySqlConn.op("delete from TradeRecord where Id<" + id + ";insert into TradeRecord (Id,Sort,QueryCount,Status,Version,CreateDate,UpdateDate,CreateMan,UpdateMan,SeoTitle,SeoKeyword,SeoDescription,MerUserId,TopUserId,Remark,BrandId,DirectFlag,CapFlag,QrPayFlag,BankCardType,TradeAmount,TradeSerialNo,ClearDate,TradeDate,SnNo,MerBuddyType,HelpMonthCount,MerHelpFlag,MerNo,MerchantId,UserId,RecordNo) select Id,Sort,QueryCount,Status,Version,CreateDate,UpdateDate,CreateMan,UpdateMan,SeoTitle,SeoKeyword,SeoDescription,MerUserId,TopUserId,Remark,BrandId,DirectFlag,CapFlag,QrPayFlag,BankCardType,TradeAmount,TradeSerialNo,ClearDate,TradeDate,SnNo,MerBuddyType,HelpMonthCount,MerHelpFlag,MerNo,MerchantId,UserId,RecordNo from TradeRecordTest order by Id;");
            }
            // OtherMySqlConn.connstr = ;
            return "ok";
        }

        public string test()
        {
            string result = "ok";
            OtherMySqlConn.connstr = "server=47.109.31.237;port=3306;user=KxsMainServer;password=Rw2imhXQQt5ODWIF;database=KxsMainServer;charset=utf8;";
            DataTable dt = OtherMySqlConn.dtable("select * from ProfitSubsidyDetail where TradeMonth='202204'");
            WebCMSEntities db = new WebCMSEntities();
            foreach (DataRow dr in dt.Rows)
            {
                int BrandId = int.Parse(function.CheckInt(dr["BrandId"].ToString()));
                int MerchantId = int.Parse(function.CheckInt(dr["MerchantId"].ToString()));
                int SubsidyUserId = int.Parse(function.CheckInt(dr["SubsidyUserId"].ToString()));
                int SubsidyType = int.Parse(function.CheckInt(dr["SubsidyType"].ToString()));
                ulong MerHelpFlag = ulong.Parse(function.CheckInt(dr["MerHelpFlag"].ToString()));
                decimal SubsidyProfitRate = decimal.Parse(function.CheckNum(dr["SubsidyProfitRate"].ToString()));
                decimal CreditTradeAmt = decimal.Parse(function.CheckNum(dr["CreditTradeAmt"].ToString()));
                decimal QrCreditTradeAmt = decimal.Parse(function.CheckNum(dr["QrCreditTradeAmt"].ToString()));
                decimal NonQrCreditTradeAmt = decimal.Parse(function.CheckNum(dr["NonQrCreditTradeAmt"].ToString()));
                decimal CreditProfitRate = decimal.Parse(function.CheckNum(dr["CreditProfitRate"].ToString()));
                decimal SubsidyProfit = decimal.Parse(function.CheckNum(dr["SubsidyProfit"].ToString()));
                string TradeMonth = dr["TradeMonth"].ToString();
                string SnNo = dr["SnNo"].ToString();
                string MerNo = dr["MerNo"].ToString();
                string RecordNo = dr["RecordNo"].ToString();

                MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == SnNo) ?? new MachineForSnNo();
                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId) ?? new PosMachinesTwo();
                PosMerchantInfo merchant = db.PosMerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new PosMerchantInfo();
                ProfitSubsidyDetail item = db.ProfitSubsidyDetail.FirstOrDefault(m => m.SubsidyUserId == SubsidyUserId && m.TradeMonth == TradeMonth && m.MerchantId == MerchantId && m.SnNo == SnNo);
                if (item == null)
                {
                    db.ProfitSubsidyDetail.Add(new ProfitSubsidyDetail()
                    {
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now,
                        RecordNo = RecordNo, //流水号
                        BrandId = BrandId, //品牌
                        ProductName = RelationClass.GetKqProductBrandInfo(BrandId), //产品名称
                        TradeMonth = TradeMonth, //交易月份
                        MerchantId = MerchantId, //商户
                        MerNo = MerNo, //渠道商户编号
                        SnNo = SnNo, //渠道SN号
                        MerRegTime = pos.BindingTime, //渠道注册时间
                        MerStandardDate = merchant.MerStandardDate, //商户激活时间
                        BelongUserId = merchant.UserId, //商户归属人
                        MerHelpFlag = MerHelpFlag, //是否属于扶持周期内商户
                        SubsidyUserId = SubsidyUserId, //补贴人
                        SubsidyType = SubsidyType, //分润补贴类型
                        SubsidyProfitRate = SubsidyProfitRate, //创客活动期内直营商户分润万分之十
                        CreditTradeAmt = CreditTradeAmt, //商户贷记卡交易总金额
                        QrCreditTradeAmt = QrCreditTradeAmt, //商户(云闪付)贷记卡交易总金额
                        NonQrCreditTradeAmt = NonQrCreditTradeAmt, //商户(非云闪付)贷记卡交易总金额
                        CreditProfitRate = CreditProfitRate, //(非云闪付)贷记卡交易分润比例
                        SubsidyProfit = SubsidyProfit, //商户(非云闪付)贷记卡交易分润补贴金额
                    });
                    // db.SaveChanges();
                    result += "增加--SubsidyUserId：" + SubsidyUserId + ";SnNo" + SnNo + ";SubsidyProfit" + SubsidyProfit + ";";
                }
                else
                {
                    if (item.SubsidyProfit < SubsidyProfit)
                    {
                        item.SubsidyProfitRate = SubsidyProfitRate; //创客活动期内直营商户分润万分之十
                        item.SubsidyProfit = SubsidyProfit; //商户(非云闪付)贷记卡交易分润补贴金额
                        result += "更新--SubsidyUserId：" + SubsidyUserId + ";SnNo" + SnNo + ";SubsidyProfit" + SubsidyProfit + ";";
                        // db.SaveChanges();
                    }
                }
            }
            // OtherMySqlConn.connstr = ;
            db.Dispose();
            return result;
        }

        public string test2()
        {
            string result = "ok";
            OtherMySqlConn.connstr = "server=47.108.231.170;port=3306;user=KxsMainServer;password=Rw2imhXQQt5ODWIF;database=KxsMainServer;charset=utf8;";
            DataTable dt = OtherMySqlConn.dtable("select SubsidyUserId,BrandId,sum(SubsidyProfitRate) as SubsidyProfit from ProfitSubsidyDetail where TradeMonth='202204' and SubsidyUserId>0 GROUP BY SubsidyUserId,BrandId");
            WebCMSEntities db = new WebCMSEntities();
            DateTime checkDate = DateTime.Parse("2022-05-20 00:00:00");
            foreach (DataRow dr in dt.Rows)
            {
                int BrandId = int.Parse(function.CheckInt(dr["BrandId"].ToString()));
                int SubsidyUserId = int.Parse(function.CheckInt(dr["SubsidyUserId"].ToString()));
                decimal SubsidyProfit = decimal.Parse(function.CheckNum(dr["SubsidyProfit"].ToString()));
                UserAccountRecord userAccountRecord = db.UserAccountRecord.FirstOrDefault(m => m.Id > 86538 && m.CreateDate > checkDate && m.UserId == SubsidyUserId && m.ProductType == BrandId && m.ChangeType == 111);
                if (userAccountRecord == null)
                {
                    UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == SubsidyUserId);
                    if (account == null)
                    {
                        account = db.UserAccount.Add(new UserAccount()
                        {
                            Id = SubsidyUserId,
                            UserId = SubsidyUserId,
                        }).Entity;
                        db.SaveChanges();
                    }
                    decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                    decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                    decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                    // account.BalanceAmount += SubsidyProfit;
                    // account.TotalAmount += SubsidyProfit;
                    decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                    decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                    decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                    userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
                    {
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now,
                        UserId = SubsidyUserId, //创客
                        ProductType = BrandId,
                        ChangeType = 111, //变动类型
                        ChangeAmount = SubsidyProfit, //变更金额
                        BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                        AfterTotalAmount = AfterTotalAmount, //变更后总金额
                        BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                        AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                        BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                        AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                        Remark = "直拓商户补贴",
                    }).Entity;
                    db.SaveChanges();
                }
                else
                {
                    userAccountRecord.ChangeAmount = SubsidyProfit;
                    db.SaveChanges();
                }
            }
            // OtherMySqlConn.connstr = ;
            db.Dispose();
            return result;
        }

        // 大盟主标记扫描
        public string leaderflag()
        {
            WebCMSEntities db = new WebCMSEntities();
            List<int> ids = new List<int>();
            // List<PosCouponRecord> records = db.PosCouponRecord.Where(m => m.FromUserId == 597).ToList();
            // foreach(PosCouponRecord record in records)
            // {
            //     ids.Add(record.PosCouponId);
            // }
            ids.Add(6843);
            List<PosCoupons> coupons = db.PosCoupons.Where(m => ids.Contains(m.Id) && m.IsUse == 1).ToList();
            foreach (PosCoupons coupon in coupons)
            {
                PosSns.Add(coupon.ExchangeCode);
            }
            foreach (PosCoupons coupon in coupons)
            {
                ChildNo(db, coupon.ExchangeCode, coupon.ExchangeCode, coupon.LeaderUserId);
            }
            // db.SaveChanges();
            db.Dispose();
            return "ok";
        }
        List<string> nos = new List<string>();
        private void ChildNo(WebCMSEntities db, string RootCheckNo, string CheckNo, int LeaderUserId)
        {
            MachineApply apply = db.MachineApply.FirstOrDefault(m => m.SwapSnExpand.Contains(CheckNo));
            if(apply != null)
            {
                int len = 0;
                string[] SnList = apply.SwapSnExpand.TrimEnd('\n').Split('\n');
                foreach(string sn in SnList)
                {
                    if(PosSns.Contains(sn.Split(':')[0]) || nos.Contains(sn.Split(':')[0]))
                    {
                        len += 1;
                    }
                }
                Orders order = db.Orders.FirstOrDefault(m => m.Id == apply.QueryCount);
                if(order != null)
                {
                    if(!string.IsNullOrEmpty(order.SnNos))
                    {
                        if(order.SnNos.Contains(","))
                        {
                            string[] SwapSnExpands = order.SnNos.TrimEnd(',').Split(',');
                            int index = 0;
                            foreach(string no in SwapSnExpands)
                            {
                                if(!nos.Contains(no) && index < len)
                                {
                                    index += 1;
                                    nos.Add(no);
                                    ChildNo(db, RootCheckNo, no, LeaderUserId);
                                }
                            }
                        }
                        else
                        {
                            string[] SwapSnExpands = order.SnNos.TrimEnd('\n').Split('\n');
                            int index = 0;
                            foreach(string no in SwapSnExpands)
                            {
                                if(!nos.Contains(no) && index < len)
                                {
                                    index += 1;
                                    nos.Add(no);
                                    ChildNo(db, RootCheckNo, no, LeaderUserId);
                                }
                            }
                        }
                    }
                    else
                    {
                        MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == CheckNo) ?? new MachineForSnNo();
                        PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == forSnNo.SnId);
                        if(pos != null)
                        {
                            // pos.LeaderUserId = LeaderUserId;
                            // Library.function.WriteLog(LeaderUserId + ":" + pos.PosSn + ":" + apply.SwapSnExpand.TrimEnd('\n').Split('\n').Length, "大盟主奖励标记机具");
                            Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                            Library.function.WriteLog(pos.PosSn + ":" + RootCheckNo + ":" + user.MakerCode + ":" + user.RealName, "大盟主奖励标记机具");
                        }
                    }
                }
            }
            else
            {
                MachineForSnNo forSnNo = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == CheckNo) ?? new MachineForSnNo();
                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m=>m.Id == forSnNo.SnId);
                if(pos != null)
                {
                    // pos.LeaderUserId = LeaderUserId;
                    // Library.function.WriteLog(LeaderUserId + ":" + pos.PosSn, "大盟主奖励标记机具");
                    Users user = db.Users.FirstOrDefault(m => m.Id == pos.BuyUserId) ?? new Users();
                    Library.function.WriteLog(pos.PosSn + ":" + RootCheckNo + ":" + user.MakerCode + ":" + user.RealName, "大盟主奖励标记机具");
                }
            }
        }
        List<string> PosSns = new List<string>();
        public string ScanNos()
        {
            PosSns = new List<string>();
            PosSns.Add("00005002681889125851");
            WebCMSEntities db = new WebCMSEntities();
            foreach(string PosSn in PosSns)
            {
                ChildNo(db, PosSn, PosSn, 0);
            }
            db.Dispose();
            return "ok";
        }
        

        //补推荐奖励
        public string AddDirectPrice(int oid = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            List<int> uids = new List<int>(); //领取过的下单创客
            IQueryable<Orders> orders = db.Orders.Where(m => m.Status > 1 && m.UserId > 1 && m.TotalPrice % 600 == 0 && m.Sort == 0);
            if(oid > 0)
            {
                orders = orders.Where(m => m.Id == oid);
            }
            foreach (Orders order in orders.ToList())
            {
                if(!uids.Contains(order.UserId))
                {
                    bool checkPrize = db.UserAccountRecord.Any(m => m.QueryCount == oid && m.ChangeType == 112);
                    if(checkPrize)
                    {
                        uids.Add(order.UserId);
                    }
                    else
                    {
                        OrderProduct pro = db.OrderProduct.FirstOrDefault(m => m.OrderId == oid) ?? new OrderProduct();
                        if (pro.ProductId == 10 || pro.ProductId == 11)
                        {
                            Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId);
                            if (user != null)
                            {
                                bool directPrize = false; //直推奖标记
                                int ParentUserId = user.ParentUserId;
                                List<int> proids = new List<int>();
                                proids.Add(10);
                                proids.Add(11);
                                while (ParentUserId > 0)
                                {
                                    Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId) ?? new Users();
                                    int machineCount = db.PosMachinesTwo.Count(m => m.BuyUserId == ParentUserId && m.PosSnType == 0 && m.ActivationState == 0); //判断是否拥有3台兑换机
                                    int ActiveCount = db.PosMachinesTwo.Count(m => m.BuyUserId == ParentUserId && m.ActivationState == 1); //判断是否拥有3台激活机（不限购买或赠送）
                                    int couponCount = db.PosCoupons.Count(m => m.UserId == ParentUserId && m.IsUse == 0); //判断是否拥有3张券
                                    if ((machineCount + ActiveCount + couponCount >= 3 || puser.LeaderLevel > 0) && !directPrize)
                                    {
                                        function.WriteLog("满足条件", "推荐下单奖励监控日志");
                                        if (puser.LeaderLevel == 0) // 非盟主直推奖励，每个创客第一次下单，上级可得
                                        {
                                            List<int> oids = new List<int>();
                                            var orderpros = db.OrderProduct.Select(m => new { m.OrderId, m.UserId, m.ProductId }).Where(m => m.UserId == order.UserId && proids.Contains(m.ProductId)).ToList();
                                            foreach (var orderpro in orderpros)
                                            {
                                                oids.Add(orderpro.OrderId);
                                            }
                                            bool check = db.Orders.Any(m => oids.Contains(m.Id) && m.Status > 0);
                                            if (check)
                                            {
                                                // AlipayPayBack2Service.Instance.DirectPrize(db, order.Id, ParentUserId, pro.ProductCount);
                                                function.WriteLog(order.Id + "," + ParentUserId + "," + pro.ProductCount, "没发的推荐奖励");
                                                directPrize = true;
                                            }
                                        }
                                        else
                                        {
                                            // 盟主直推奖励，可以每次下单获得
                                            // AlipayPayBack2Service.Instance.DirectPrize(db, order.Id, ParentUserId, pro.ProductCount);
                                            function.WriteLog(order.Id + "," + ParentUserId + "," + pro.ProductCount + "--盟主", "没发的推荐奖励");
                                            directPrize = true;
                                        }

                                        //推荐下单上级获得30天的机具循环天数
                                        var posList = db.PosMachinesTwo.Select(m => new { m.Id, m.UserId, m.BindingState, m.RecycEndDate }).Where(m => m.UserId == ParentUserId && m.BindingState == 0 && m.RecycEndDate != null).ToList();
                                        foreach (var subPos in posList)
                                        {
                                            PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == subPos.Id);
                                            if (pos != null)
                                            {
                                                pos.RecycEndDate = pos.RecycEndDate.Value.AddDays(30);
                                            }
                                        }
                                        db.SaveChanges();
                                    }
                                    if(directPrize)
                                    {
                                        ParentUserId = 0;
                                    }
                                    else
                                    {
                                        ParentUserId = puser.ParentUserId;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return "ok";
        }

        public string checkLeaderOrder(int OrderId)
        {
            WebCMSEntities db = new WebCMSEntities();
            Orders order = db.Orders.FirstOrDefault(m => m.Id == OrderId);
            if (order != null)
            {
                OrderProduct pro = db.OrderProduct.FirstOrDefault(m => m.OrderId == OrderId);
                if (pro != null)
                {
                    //推荐下单奖励
                    if (pro.ProductId == 10 || pro.ProductId == 11)
                    {
                        bool checkPrize = db.UserAccountRecord.Any(m => m.QueryCount == OrderId && m.ChangeType == 112);
                        function.WriteLog("OrderId:" + OrderId, "推荐下单奖励监控日志");
                        function.WriteLog("checkPrize:" + checkPrize, "推荐下单奖励监控日志");
                        if (!checkPrize)
                        {
                            Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId);
                            if (user != null)
                            {
                                bool directPrize = false; //直推奖标记
                                bool buyPrize = false; //返100购机奖励标记
                                int leaderFlag = 0; //返600备用金标记
                                if(user.LeaderLevel > 0)
                                {
                                    UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == order.UserId) ?? new UserAccount();
                                    if(acccount.LeaderReserve >= order.TotalPrice)
                                    {
                                        if(order.PayMode == 4)
                                        {
                                            //扣减备用金
                                            AlipayPayBack2Service.Instance.OpReserve(db, order, order.UserId, order.TotalPrice, 2, 0, "商城购机");
                                            //返回到余额
                                            // OpAccount(db, order, order.UserId, order.TotalPrice / pro.ProductCount, pro.ProductCount);
                                        }
                                    }
                                    //获得100元奖励
                                    AlipayPayBack2Service.Instance.OpAccount(db, order, order.UserId, 100, pro.ProductCount);
                                    //推荐奖励
                                    AlipayPayBack2Service.Instance.DirectPrize(db, order.Id, order.UserId, pro.ProductCount);
                                    //推荐下单上级获得30天的机具循环天数
                                    var posList = db.PosMachinesTwo.Select(m => new { m.Id, m.UserId, m.BindingState, m.RecycEndDate }).Where(m => m.UserId == order.UserId && m.BindingState == 0 && m.RecycEndDate != null).ToList();
                                    foreach (var subPos in posList)
                                    {
                                        PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == subPos.Id);
                                        if (pos != null)
                                        {
                                            pos.RecycEndDate = pos.RecycEndDate.Value.AddDays(30);
                                        }
                                    }
                                    db.SaveChanges();
                                    if(user.LeaderLevel != 2)
                                    {
                                        int PUserId = user.ParentUserId;
                                        while(PUserId > 0)
                                        {
                                            Users puser = db.Users.FirstOrDefault(m => m.Id == PUserId) ?? new Users();
                                            if(puser.LeaderLevel == 2)
                                            {
                                                UserAccount acc = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id) ?? new UserAccount();
                                                if(acc.LeaderReserve >= order.TotalPrice)
                                                {
                                                    //扣减备用金
                                                    AlipayPayBack2Service.Instance.OpReserve(db, order, puser.Id, order.TotalPrice, 2, order.UserId, "购机奖励");
                                                    //返回到余额
                                                    AlipayPayBack2Service.Instance.OpAccount(db, order, puser.Id, order.TotalPrice / pro.ProductCount, pro.ProductCount);
                                                }
                                                PUserId = 0;
                                            }
                                            else
                                            {
                                                PUserId = puser.ParentUserId;
                                            }
                                        }
                                    }
                                    return "自己就是盟主，发放成功";
                                }
                                int ParentUserId = user.ParentUserId;
                                // List<int> proids = new List<int>();
                                // proids.Add(10);
                                // proids.Add(11);
                                while(ParentUserId > 0)
                                {
                                    Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId) ?? new Users();
                                    int machineCount = db.PosMachinesTwo.Count(m => m.BuyUserId == ParentUserId && m.PosSnType == 0 && m.ActivationState == 0); //判断是否拥有3台兑换机
                                    int ActiveCount = db.PosMachinesTwo.Count(m => m.BuyUserId == ParentUserId && m.ActivationState == 1); //判断是否拥有3台激活机（不限购买或赠送）
                                    int couponCount = db.PosCoupons.Count(m => m.UserId == ParentUserId && m.IsUse == 0); //判断是否拥有3张券
                                    if ((machineCount + ActiveCount + couponCount >= 3 || puser.LeaderLevel > 0) && !directPrize)
                                    {
                                        // 盟主直推奖励，可以每次下单获得
                                        AlipayPayBack2Service.Instance.DirectPrize(db, order.Id, ParentUserId, pro.ProductCount);
                                        directPrize = true;

                                        //推荐下单上级获得30天的机具循环天数
                                        var posList = db.PosMachinesTwo.Select(m => new { m.Id, m.UserId, m.BindingState, m.RecycEndDate }).Where(m => m.UserId == ParentUserId && m.BindingState == 0 && m.RecycEndDate != null).ToList();
                                        foreach (var subPos in posList)
                                        {
                                            PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == subPos.Id);
                                            if (pos != null)
                                            {
                                                pos.RecycEndDate = pos.RecycEndDate.Value.AddDays(30);
                                            }
                                        }
                                        db.SaveChanges();
                                    }
                                    if(puser.LeaderLevel > 0)
                                    {
                                        UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id) ?? new UserAccount();
                                        if(acccount.LeaderReserve >= order.TotalPrice && !buyPrize)
                                        {
                                            //购机奖励
                                            AlipayPayBack2Service.Instance.OpAccount(db, order, puser.Id, 100, pro.ProductCount);
                                            buyPrize = true;
                                        }
                                        if(acccount.LeaderReserve >= order.TotalPrice && puser.LeaderLevel > leaderFlag)
                                        {
                                            //扣减备用金
                                            AlipayPayBack2Service.Instance.OpReserve(db, order, puser.Id, order.TotalPrice, 2, order.UserId, "购机奖励");
                                            //返回到余额
                                            AlipayPayBack2Service.Instance.OpAccount(db, order, puser.Id, order.TotalPrice / pro.ProductCount, pro.ProductCount);
                                            leaderFlag = puser.LeaderLevel;
                                        }
                                    }
                                    ParentUserId = puser.ParentUserId;
                                }
                                return "找到上级盟主，发放成功";
                            }
                        }
                    }
                }
            }
            return "失败";
        }
    
    
        public string setdeposit()
        {
            // List<string> ordernos = new List<string>();
            // ordernos.Add("17343379");
            string content = "";
            // foreach(string orderno in ordernos)
            // {
            //     content += SetDepositPostService.Instance.QueryFee(orderno) + "\n";
            // }
            // List<string> snnos = new List<string>();
            // foreach(string snno in snnos)
            // {
            //     content += SetDepositPostService.Instance.ModifyFee(snno, 0.0006M) + "\n";
            // }
            // content = SetDepositPostService.Instance.SetFeeForSft("38888910", "0.63");
            // content = SetDepositPostService.Instance.SetFeeForBrand("00003202D9625450004213", bzConfigId, yhConfigId, surfeeConfigId, "");
            return content;
        }

        public string putdata()
        {
            WebCMSEntities db = new WebCMSEntities();
            var list = db.PosMachinesFeeChangeRecord.Where(m => m.Sort == 2 && m.Status == 0).ToList();
            foreach(var sub in list)
            {
                Users user = db.Users.FirstOrDefault(m => m.Id == sub.UserId) ?? new Users();
                string info = "{\"RecordId\":\"" + sub.Id + "\",\"PosId\":\"" + sub.PosId + "\",\"Fee\": \"0.6\",\"Kind\": \"2\",\"OpMan\": \"" + user.MakerCode + "\"}";
                RedisDbconn.Instance.AddList("SetDepositQueue", info);
            }
            db.Dispose();
            return "ok";
        }
    

        public string test3()
        {
            WebCMSEntities db = new WebCMSEntities();
            StoreApplyHelper.Instance.DoSomething(db, 152335);
            // AlipayPayBack2Service.Instance.DoOrderV2(db, 139620);
            // PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == sn);
            // if(pos != null)
            // {
            //     //发放大盟主奖励
            //     if(pos.LeaderUserId > 0)
            //     {
            //         RedisDbconn.Instance.AddList("LeaderPrizeQueue", pos.Id);
            //     }
            //     //发放运营中心奖励
            //     if(pos.OpId > 0)
            //     {
            //         RedisDbconn.Instance.AddList("OperatePrizeQueue", pos.Id);
            //         AlipayPayBack2Service.Instance.ActReserveBack(pos.OpId, pos.OpReserve1, pos.OpReserve2, pos.OpReserve3);
            //     }
            // }
            // db.Dispose();
            return "ok";
        }
    
        public string test5()
        {
            WebCMSEntities db = new WebCMSEntities();
            string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            string PreMonth = DateTime.Now.AddMonths(-2).ToString("yyyyMM");
            string minId = "0";
            string connstr = Library.ConfigurationManager.AppSettings["Pxc1SqlConnStr"].ToString();
            DataTable minIdDt = CustomerSqlConn.dtable("select min(Id) from ProfitRewardRecord where TradeMonth='" + PreMonth + "'", connstr);
            if(minIdDt.Rows.Count > 0)
            {
                minId = minIdDt.Rows[0][0].ToString();
            }
            ResetSmallStoreHelper.Instance.DoMethod(db, PreMonth, minId, "10115");
            db.Dispose();
            return "ok";
        }

        public string test6()
        {
            return "ok";
        }

        public string sethkfee()
        {
            string bzConfigId = "", yhConfigId = "", surfeeConfigId = "";
            int Kind = 2;
            WebCMSEntities db = new WebCMSEntities();
            PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == "00005702832513011041") ?? new PosMachinesTwo();
            if(pos.BrandId == 8)
            {
                if(Kind == 1)
                {
                    bzConfigId = "684753829778436096";
                    yhConfigId = "684754046342934528";
                    surfeeConfigId = "570331704834170880";
                }
                else
                {
                    bzConfigId = "585167132691009536";
                    yhConfigId = "579355312831074304";
                    surfeeConfigId = "570331704834170880";
                }
            }
            else
            {
                if(Kind == 1)
                {
                    bzConfigId = "691739824478494720";
                    yhConfigId = "691740128238383104";
                    surfeeConfigId = "574600660289888256";
                }
                else
                {
                    bzConfigId = "584068951081226240";
                    yhConfigId = "584070145207963648";
                    surfeeConfigId = "574600660289888256";
                }
            }
            string content = SetDepositPostService.Instance.HKSetFeeForBrand(pos.PosSn, bzConfigId, yhConfigId, surfeeConfigId, pos.BrandId);
            return content;
        }
    
    
    
    
    
    
    
        public string add600(int OrderId = 0)
        {
            WebCMSEntities db = new WebCMSEntities();
            List<int> couponIds = new List<int>();
            couponIds.Add(74648);
            couponIds.Add(74649);
            couponIds.Add(74650);
            Orders order = db.Orders.FirstOrDefault(m => m.Id == OrderId) ?? new Orders();
            OrderProduct pro = db.OrderProduct.FirstOrDefault(m => m.OrderId == OrderId) ?? new OrderProduct();
            if (pro.ProductId == 10 || pro.ProductId == 11)
            {
                bool checkPrize = db.UserAccountRecord.Any(m => m.QueryCount == OrderId && m.ChangeType == 112);
                function.WriteLog("OrderId:" + OrderId, "推荐下单奖励监控日志");
                function.WriteLog("checkPrize:" + checkPrize, "推荐下单奖励监控日志");
                if (checkPrize)
                {
                    Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId);
                    if (user != null)
                    {
                        if(user.LeaderLevel > 0 || user.UserType == 1) //盟主或运营中心
                        {
                            //获得100元奖励
                            AlipayPayBack2Service.Instance.OpAccount(db, order, order.UserId, 100, pro.ProductCount);
                        }
                    }
                }
                else
                {
                    Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId);
                    if (user != null)
                    {
                        bool directPrize = false; //直推奖标记
                        bool bigLeaderPrize = false; //大盟主券标记
                        bool operateFlag = false; //运营中心标记
                        bool buyPrize = false; //返100购机奖励标记或返100购机奖励标记-运营中心
                        int leaderFlag = 0; //返600备用金标记
                        if(user.LeaderLevel > 0 || user.UserType == 1) //盟主或运营中心
                        {
                            if(user.LeaderLevel > 0)
                            {
                                UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == order.UserId) ?? new UserAccount();
                                if(acccount.LeaderReserve >= order.TotalPrice)
                                {
                                    if(order.PayMode == 4)
                                    {
                                        //扣减备用金
                                        AlipayPayBack2Service.Instance.OpReserve(db, order, order.UserId, order.TotalPrice, 0, 0, "商城购机(储备金支付)");
                                    }
                                }
                            }
                            //获得100元奖励
                            AlipayPayBack2Service.Instance.OpAccount(db, order, order.UserId, 100, pro.ProductCount);
                            //推荐奖励
                            AlipayPayBack2Service.Instance.DirectPrize(db, order.Id, order.UserId, pro.ProductCount);
                            //推荐下单上级获得30天的机具循环天数(盟主自己得)
                            var posList = db.PosMachinesTwo.Select(m => new { m.Id, m.UserId, m.BindingState, m.RecycEndDate }).Where(m => m.UserId == order.UserId && m.BindingState == 0 && m.RecycEndDate != null).ToList();
                            foreach (var subPos in posList)
                            {
                                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == subPos.Id);
                                if (pos != null)
                                {
                                    pos.RecycEndDate = pos.RecycEndDate.Value.AddDays(30);
                                }
                            }
                            db.SaveChanges();
                            if(order.PayMode == 4 && user.LeaderLevel > 0) //使用盟主储蓄金,并且是盟主
                            {
                                if(user.UserType == 1)
                                {
                                    if(couponIds.Count > 0)
                                    {
                                        UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == user.Id) ?? new UserAccount();
                                        foreach(int couponId in couponIds)
                                        {
                                            PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                                            if(coupon != null)
                                            {
                                                if(acccount.LeaderReserve >= 400 * pro.ProductCount)
                                                {
                                                    coupon.LeaderUserId = user.Id;
                                                }
                                                coupon.OpId = user.Id;
                                            }
                                        }
                                    }
                                    db.SaveChanges();
                                }
                                else
                                {
                                    //寻找最近运营中心额度大于0的运营中心
                                    int PUserId = user.Id;
                                    bool OperateFlag = true;
                                    bool OncePrizeFlag1 = true;
                                    while(PUserId > 0)
                                    {
                                        Users puser = db.Users.FirstOrDefault(m => m.Id == PUserId);
                                        if(puser != null)
                                        {
                                            if(puser.UserType == 1 && OperateFlag == true) //运营中心
                                            {
                                                if(couponIds.Count > 0)
                                                {
                                                    UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == order.UserId) ?? new UserAccount();
                                                    foreach(int couponId in couponIds)
                                                    {
                                                        PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                                                        if(coupon != null)
                                                        {
                                                            if(acccount.LeaderReserve >= 400 * pro.ProductCount)
                                                            {
                                                                coupon.LeaderUserId = user.Id;
                                                            }
                                                            coupon.OpId = puser.Id;
                                                        }
                                                    }
                                                    db.SaveChanges();
                                                    if(acccount.LeaderReserve >= 400 * pro.ProductCount && OncePrizeFlag1)
                                                    {
                                                        //扣减备用金
                                                        AlipayPayBack2Service.Instance.OpReserve(db, order, order.UserId, 400 * pro.ProductCount, 2, 0, "商城购机");
                                                        //返回到余额
                                                        AlipayPayBack2Service.Instance.OpLeaderAccount(db, order, order.UserId, 400, pro.ProductCount);
                                                        OncePrizeFlag1 = false;
                                                    }
                                                    OperateFlag = false;
                                                }
                                            }
                                            PUserId = puser.ParentUserId;
                                        }
                                        else
                                        {
                                            PUserId = 0;
                                        }
                                    }
                                }
                            }
                            else if(order.PayMode == 4 && user.UserType == 1) //使用盟主储蓄金,并且是运营中心
                            {
                                if(couponIds.Count > 0)
                                {
                                    foreach(int couponId in couponIds)
                                    {
                                        PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                                        if(coupon != null)
                                        {
                                            coupon.OpId = user.Id;
                                        }
                                    }
                                }
                                db.SaveChanges();
                                //寻找最近储蓄金充足的大盟主
                                int PUserId = user.Id;
                                bool LeaderFlag = true;
                                bool OncePrizeFlag2 = true;
                                while(PUserId > 0)
                                {
                                    Users puser = db.Users.FirstOrDefault(m => m.Id == PUserId);
                                    if(puser != null)
                                    {
                                        if(puser.LeaderLevel == 2 && LeaderFlag == true) //大盟主
                                        {
                                            if(couponIds.Count > 0)
                                            {
                                                UserAccount pacccount = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id) ?? new UserAccount();
                                                foreach(int couponId in couponIds)
                                                {
                                                    PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                                                    if(coupon != null && pacccount.LeaderReserve >= 400 * pro.ProductCount)
                                                    {
                                                        coupon.LeaderUserId = puser.Id;
                                                    }
                                                }
                                                db.SaveChanges();
                                                UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == order.UserId) ?? new UserAccount();
                                                if(acccount.LeaderReserve >= 400 * pro.ProductCount && OncePrizeFlag2)
                                                {
                                                    //扣减备用金
                                                    AlipayPayBack2Service.Instance.OpReserve(db, order, order.UserId, 400 * pro.ProductCount, 2, 0, "商城购机");
                                                    //返回到余额
                                                    AlipayPayBack2Service.Instance.OpLeaderAccount(db, order, order.UserId, 400, pro.ProductCount);
                                                    OncePrizeFlag2 = false;
                                                }
                                                LeaderFlag = false;
                                            }
                                        }
                                        PUserId = puser.ParentUserId;
                                    }
                                    else
                                    {
                                        PUserId = 0;
                                    }
                                }
                            }
                            else
                            {
                                //寻找最近储蓄金充足的大盟主及最近运营中心额度大于0的运营中心（含自身）
                                int PUserId = user.Id;
                                int LeaderFlag = 0;
                                bool OperateFlag = true;
                                bool OncePrizeFlag3 = true;
                                while(PUserId > 0)
                                {
                                    Users puser = db.Users.FirstOrDefault(m => m.Id == PUserId);
                                    if(puser != null)
                                    {
                                        if(puser.LeaderLevel > 0 && puser.LeaderLevel > LeaderFlag && LeaderFlag < 2) //大盟主
                                        {
                                            if(couponIds.Count > 0)
                                            {
                                                if(puser.LeaderLevel == 2)
                                                {
                                                    UserAccount pacccount = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id) ?? new UserAccount();
                                                    foreach(int couponId in couponIds)
                                                    {
                                                        PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                                                        if(coupon != null && pacccount.LeaderReserve >= 400 * pro.ProductCount)
                                                        {
                                                            coupon.LeaderUserId = puser.Id;
                                                        }
                                                    }
                                                    db.SaveChanges();
                                                }
                                                UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id) ?? new UserAccount();
                                                if(acccount.LeaderReserve >= 400 * pro.ProductCount && OncePrizeFlag3)
                                                {
                                                    //扣减备用金
                                                    AlipayPayBack2Service.Instance.OpReserve(db, order, puser.Id, 400 * pro.ProductCount, 2, 0, "商城购机");
                                                    //返回到余额
                                                    AlipayPayBack2Service.Instance.OpLeaderAccount(db, order, puser.Id, 400, pro.ProductCount);
                                                    LeaderFlag = puser.LeaderLevel;
                                                    OncePrizeFlag3 = false;
                                                }
                                            }
                                        }
                                        if(puser.UserType == 1 && OperateFlag == true) //运营中心
                                        {
                                            if(couponIds.Count > 0)
                                            {
                                                foreach(int couponId in couponIds)
                                                {
                                                    PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                                                    if(coupon != null)
                                                    {
                                                        coupon.OpId = puser.Id;
                                                    }
                                                }
                                                db.SaveChanges();
                                                OperateFlag = false;
                                            }
                                        }
                                        PUserId = puser.ParentUserId;
                                    }
                                    else
                                    {
                                        PUserId = 0;
                                    }
                                }
                            }
                            return "ok";
                        }
                        int ParentUserId = user.ParentUserId;
                        // List<int> proids = new List<int>();
                        // proids.Add(10);
                        // proids.Add(11);
                        // 普通创客购买600一组的机具券
                        bool OncePrizeFlag4 = true;
                        while(ParentUserId > 0)
                        {
                            Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId) ?? new Users();
                            int machineCount = db.PosMachinesTwo.Count(m => m.BuyUserId == ParentUserId && m.PosSnType == 0 && m.ActivationState == 0); //判断是否拥有3台兑换机
                            int ActiveCount = db.PosMachinesTwo.Count(m => m.BuyUserId == ParentUserId && m.ActivationState == 1); //判断是否拥有3台激活机（不限购买或赠送）
                            int couponCount = db.PosCoupons.Count(m => m.UserId == ParentUserId && m.IsUse == 0); //判断是否拥有3张券
                            function.WriteLog("MakerCode:" + puser.MakerCode, "推荐下单奖励监控日志");
                            function.WriteLog("machineCount:" + machineCount, "推荐下单奖励监控日志");
                            function.WriteLog("ActiveCount:" + ActiveCount, "推荐下单奖励监控日志");
                            if ((machineCount + ActiveCount + couponCount >= 3 || puser.LeaderLevel > 0) && !directPrize)
                            {
                                AlipayPayBack2Service.Instance.DirectPrize(db, order.Id, ParentUserId, pro.ProductCount);
                                directPrize = true;

                                //推荐下单上级获得30天的机具循环天数
                                var posList = db.PosMachinesTwo.Select(m => new { m.Id, m.UserId, m.BindingState, m.RecycEndDate }).Where(m => m.UserId == ParentUserId && m.BindingState == 0 && m.RecycEndDate != null).ToList();
                                foreach (var subPos in posList)
                                {
                                    PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == subPos.Id);
                                    if (pos != null)
                                    {
                                        pos.RecycEndDate = pos.RecycEndDate.Value.AddDays(30);
                                    }
                                }
                                db.SaveChanges();
                            }
                            if(puser.LeaderLevel > 0)
                            {
                                UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id) ?? new UserAccount();
                                if(acccount.LeaderReserve >= order.TotalPrice && !buyPrize)
                                {
                                    //购机奖励
                                    AlipayPayBack2Service.Instance.OpAccount(db, order, puser.Id, 100, pro.ProductCount);
                                    buyPrize = true;
                                }
                                if(acccount.LeaderReserve >= 400 * pro.ProductCount && puser.LeaderLevel > leaderFlag && leaderFlag < 2 && OncePrizeFlag4)
                                {
                                    //扣减备用金
                                    AlipayPayBack2Service.Instance.OpReserve(db, order, puser.Id, 400 * pro.ProductCount, 2, order.UserId, "购机奖励");
                                    //返回到余额
                                    AlipayPayBack2Service.Instance.OpLeaderAccount(db, order, puser.Id, 400, pro.ProductCount);
                                    leaderFlag = puser.LeaderLevel;
                                    OncePrizeFlag4 = false;
                                }
                                //如果是大盟主，则标记大盟主标签
                                if(couponIds.Count > 0 && puser.LeaderLevel == 2 && acccount.LeaderReserve >= order.TotalPrice && !bigLeaderPrize)
                                {
                                    foreach(int couponId in couponIds)
                                    {
                                        PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                                        if(coupon != null)
                                        {
                                            coupon.LeaderUserId = puser.Id;
                                        }
                                    }
                                    db.SaveChanges();
                                    bigLeaderPrize = true;
                                }
                            }
                            if(puser.UserType == 1)
                            {
                                UserAccount acccount = db.UserAccount.FirstOrDefault(m => m.Id == puser.Id) ?? new UserAccount();
                                if(!buyPrize)
                                {
                                    //购机奖励
                                    AlipayPayBack2Service.Instance.ChangeAccount(db, order, puser.Id, 100 * pro.ProductCount, 120);
                                    buyPrize = true;
                                }
                                //标记标签
                                if(couponIds.Count > 0 && !operateFlag)
                                {
                                    foreach(int couponId in couponIds)
                                    {
                                        PosCoupons coupon = db.PosCoupons.FirstOrDefault(m => m.Id == couponId);
                                        if(coupon != null)
                                        {
                                            coupon.OpId= puser.Id;
                                        }
                                    }
                                    db.SaveChanges();
                                    operateFlag = true;
                                }
                            }
                            ParentUserId = puser.ParentUserId;
                        }
                    }
                }
                function.WriteLog("\r\n\r\n", "推荐下单奖励监控日志");
            }
            db.Dispose();
            return "ok";
        }
    
    }
}