using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mall.Common;
using Mall.Common.Plugin;
using Mall.Model.Entity.User;
using Mall.Model.Extend.User;
using Mall.Repository;
using Mall.Repository.User;
using Mall.Repository.Product;
using Mall.Model.Extend.Product;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Mall.Model.Entity.MarketingCenter;

namespace Mall.Module.User
{
    /// <summary>
    /// 商户用户公共处理层
    /// </summary>
    public class UserCommonModule
    {
        /// <summary>
        /// 分销基础配置
        /// </summary>
        private readonly RB_Distributor_BasicsRepository distributor_BasicsRepository = new RB_Distributor_BasicsRepository();
        /// <summary>
        /// 分销自定义设置
        /// </summary>
        private readonly RB_Distributor_CustomRepository distributor_CustomRepository = new RB_Distributor_CustomRepository();
        /// <summary>
        /// 分类样式
        /// </summary>
        private readonly RB_Product_CategoryStyleRepository product_CategoryStyleRepository = new RB_Product_CategoryStyleRepository();
        /// <summary>
        /// 推荐设置
        /// </summary>
        private readonly RB_Product_RecommendRepository product_RecommendRepository = new RB_Product_RecommendRepository();
        /// <summary>
        /// 支付信息
        /// </summary>
        private readonly RB_Goods_Online_TradeRepository goods_Online_TradeRepository = new RB_Goods_Online_TradeRepository();
        /// <summary>
        /// 订单信息
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();

        /// <summary>
        /// 订单商品信息
        /// </summary>
        private readonly RB_Goods_OrderDetailRepository goodsOrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 会员信息
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 分销商
        /// </summary>
        private readonly RB_Distributor_InfoRepository distributor_InfoRepository = new RB_Distributor_InfoRepository();
        /// <summary>
        /// vip购买返佣
        /// </summary>
        private readonly RB_VipBuy_CommissionRepository vipBuy_CommissionRepository = new RB_VipBuy_CommissionRepository();
        /// <summary>
        /// vip购买记录
        /// </summary>
        private readonly RB_Vip_BuyRepository vip_BuyRepository = new RB_Vip_BuyRepository();
        /// <summary>
        /// 粉象vip购买返佣金额
        /// </summary>
        private readonly RB_Distributor_FXCommissionRepository distributor_FXCommissionRepository = new RB_Distributor_FXCommissionRepository();
        /// <summary>
        /// 粉象返佣等级
        /// </summary>
        private readonly RB_Distributor_FXGradeRepository distributor_FXGradeRepository = new RB_Distributor_FXGradeRepository();


        private readonly MiniProgramMsgModule appletWeChatModule = new MiniProgramMsgModule();

        /// <summary>
        /// vip购买仓储层
        /// </summary>
        private readonly RB_Vip_BuyRepository vipBuyRepository = new RB_Vip_BuyRepository();

        private Repository.MarketingCenter.RB_DiscountCouponRepository discountCouponRepository = new Repository.MarketingCenter.RB_DiscountCouponRepository();
        private Repository.User.RB_Member_CouponRepository memberCouponRepository = new Repository.User.RB_Member_CouponRepository();


        /// <summary>
        /// 初始化分销基础配置
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public bool InitializeDistributorBasicsInfo(int TenantId, int MallBaseId)
        {
            var OModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (OModel == null)
            {
                string GradeEntranceImage = new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("InitializeImages")["GradeEntranceImage"];
                return distributor_BasicsRepository.Insert(new RB_Distributor_Basics()
                {
                    Id = 0,
                    ApplicationProtocol = "",
                    ApplyFor = Common.Enum.User.DistributorApplyForEnum.TX,
                    BackgroundImage = 0,
                    CreateDate = DateTime.Now,
                    DailyWithdrawalLimit = -1,
                    DistributorCommissionType = 1,
                    DistributorCondition = Common.Enum.User.DistributorConditionEnum.WTJ,
                    DistributorTier = 1,
                    GradeEntrance = 1,
                    GradeEntranceImage = GradeEntranceImage,
                    IndexImage = 0,
                    InPurchasing = 1,
                    MallBaseId = MallBaseId,
                    MinimumWithdrawalLimit = 50,
                    OneCommission = 0,
                    ReferralsCondition = Common.Enum.User.DistrbutorReferralsEnum.SCDJ,
                    TenantId = TenantId,
                    ThreeCommission = 0,
                    TwoCommission = 0,
                    UpdateDate = DateTime.Now,
                    UserNotes = "",
                    WithdrawFee = 0,
                    WithdrawWay = "[" + (int)Common.Enum.User.DistrbutorWithdrawWayEnum.ZDDK + "]",
                    IsCommissionResidue = 2,
                    HpReferralsGradeAudit = 2,
                    IsWithdrawAll = 2,
                    IsEnableFXGrade = 2
                }) > 0;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 初始化分销自定义
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool InitializeDistributorCustomInfo(int TenantId, int MallBaseId)
        {
            var OModel = distributor_CustomRepository.GetList(new RB_Distributor_Custom_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (OModel == null)
            {
                return distributor_CustomRepository.Insert(new RB_Distributor_Custom()
                {
                    Id = 0,
                    ApplicationAgreement = "分销申请协议",
                    HeadImage = Common.Config.GetFileUrl("/Upload/Set/1587968479000.png"),
                    BottomImage = Common.Config.GetFileUrl("/Upload/Set/1587968716000.png"),
                    ButtonColor = "#FF4544",
                    ButtonFilletPX = 40,
                    ButtonText = "申请成为分销商",
                    ButtonTextColor = "#FFFFFF",
                    DistributionApplication = "分销申请",
                    DistributionCommissionName = "分销佣金",
                    DistributionCommissionImage = Common.Config.GetFileUrl("/Upload/Set/1587968503000.png"),
                    DistributionOrderName = "分销订单",
                    DistributionOrderImage = Common.Config.GetFileUrl("/Upload/Set/1587968517000.png"),
                    WithdrawDetialsName = "提现明细",
                    WithdrawDetialsImage = Common.Config.GetFileUrl("/Upload/Set/1587968599000.png"),
                    MyTeamName = "我的团队",
                    MyTeamImage = Common.Config.GetFileUrl("/Upload/Set/1587968613000.png"),
                    PromoteQRCodeName = "推广二维码",
                    PromoteQRCodeImage = Common.Config.GetFileUrl("/Upload/Set/1587968626000.png"),
                    ReferrerName = "推荐人",
                    CommissionForWithdrawalName = "可提现佣金",
                    WithdrawDepositName = "提现",
                    CommissionWithdrawnName = "已提现佣金",
                    OutstandingCommissionName = "未结算佣金",
                    DistributorName = "分销商",
                    CommissionTobePaidName = "待打款佣金",
                    UserNotesName = "用户须知",
                    IWantToWithdrawName = "我要提现",
                    WithdrawalAmountName = "提现金额",
                    WithdrawalWayName = "提现方式",
                    OneDistributionName = "一级分销名称",
                    TwoDistributionName = "二级分销名称",
                    ThreeDistributionName = "三级分销名称",
                    CreateDate = DateTime.Now,
                    MallBaseId = MallBaseId,
                    TenantId = TenantId,
                    UpdateDate = DateTime.Now
                }) > 0;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 初始化分类样式
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public bool InitializeCategoryStyleInfo(int TenantId, int MallBaseId)
        {
            var OModel = product_CategoryStyleRepository.GetList(new RB_Product_CategoryStyle_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (OModel == null)
            {
                return product_CategoryStyleRepository.Insert(new Model.Entity.Product.RB_Product_CategoryStyle()
                {
                    CategoryNum = 1,
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = MallBaseId,
                    RowNum = 1,
                    Style = 1,
                    TenantId = TenantId,
                    Type = 1,
                    UpdateDate = DateTime.Now
                }) > 0;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 初始化商品推荐设置
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public bool InitializeProductRecommendInfo(int TenantId, int MallBaseId)
        {
            var oModel = product_RecommendRepository.GetList(new RB_Product_Recommend_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (oModel == null)
            {
                return product_RecommendRepository.Insert(new Model.Entity.Product.RB_Product_Recommend()
                {
                    Id = 0,
                    CommentProductIds = "",
                    CommentRecommentStatus = 1,
                    CreateDate = DateTime.Now,
                    DetailRecommendNum = 6,
                    DetailRecommendStatus = 1,
                    IsCommentRecommend = 2,
                    IsOrderRecommend = 2,
                    MallBaseId = MallBaseId,
                    OrderCompleteStatus = 1,
                    OrderProductIds = "",
                    TenantId = TenantId,
                    UpdateDate = DateTime.Now
                }) > 0;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 新增微信支付后增加
        /// </summary>
        /// <param name="UserId">用户id</param>
        /// <param name="OrderId">订单id</param>
        /// <param name="Out_Trade_No">订单号</param>
        /// <param name="Transaction_Id">交易单号</param>
        /// <param name="PayWay">支付方式</param>
        /// <param name="PayType">支付类型</param>
        /// <param name="Money">金额</param>
        /// <param name="Pay_Result">状态</param>
        /// <returns></returns>
        public bool InsertOrderPayInfo(int UserId, int OrderId, string Out_Trade_No, string Transaction_Id, Common.Enum.Goods.OrderPayTypeEnum PayWay, string PayType, decimal Money, DateTime Time_End, int Pay_Result)
        {
            var umodel = member_UserRepository.GetEntity(UserId);
            if (umodel == null)
            {
                return false;
            }

            //判断订单状态是否是待支付  2020-06-16 Add By:W
            var oldOrder = goods_OrderRepository.GetEntity(OrderId);
            if (oldOrder == null)
            {
                return false;
            }
            if (oldOrder.OrderStatus != Common.Enum.Goods.OrderStatusEnum.NonPayment)
            {
                return false;
            }
            if (oldOrder.Income != Money)
            {
                return false;
            }

            //获取订单商品
            var orderGoodsList = goodsOrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend { TenantId = oldOrder.TenantId, MallBaseId = oldOrder.MallBaseId, OrderId = oldOrder.OrderId });

            bool flag = goods_Online_TradeRepository.Insert(new Model.Entity.Product.RB_Goods_Online_Trade()
            {
                Id = 0,
                User_Id = UserId,
                FinanceId = 0,
                CreateDate = DateTime.Now,
                IsRefund = 2,
                MallBaseId = umodel.MallBaseId,
                Money = Money,
                OrderId = OrderId,
                Out_Trade_No = Out_Trade_No,
                PayType = PayType,
                PayWay = PayWay,
                Pay_Date = Time_End,
                Pay_Result = Pay_Result,
                RefundMoney = 0,
                RefundStatus = 0,
                RefundTrade_Order = "",
                Remarks = umodel.Name + "(id:" + UserId + ")",
                TenantId = umodel.TenantId,
                Transaction_Id = Transaction_Id,
                Type = 1
            }) > 0;
            if (flag)
            {
                //更新订单信息
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods_Order_Extend.OrderStatus),Common.Enum.Goods.OrderStatusEnum.WaitSendGoods},
                    { nameof(RB_Goods_Order_Extend.MerchantsNo),Out_Trade_No},
                    { nameof(RB_Goods_Order_Extend.PaymentTime),Time_End},
                    { nameof(RB_Goods_Order_Extend.PaymentWay),Common.Enum.Goods.OrderPaymentTypeEnum.OnlinePayment}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order_Extend.OrderId),
                          FiledValue=OrderId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                goods_OrderRepository.Update(keyValues, wheres);
                //下线
                if (umodel.DownlineCondition == Common.Enum.User.DistrbutorReferralsEnum.SCFK && umodel.IsBeDownline == 2)
                {
                    //首次下单成为下线
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                        {nameof(RB_Member_User_Extend.SuperiorId),umodel.WaitSuperiorId },
                        {nameof(RB_Member_User_Extend.IsBeDownline),1 },
                        {nameof(RB_Member_User_Extend.BeDownlineDate),DateTime.Now },
                    };
                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Member_User_Extend.Id),
                                  FiledValue=umodel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                    member_UserRepository.Update(keyValues1, wheres1);
                }

                //2020-08-04 add by:W 购买并支付自动发放优惠券
                var couponList = discountCouponRepository.GetSelfmotionCouponList(new Model.Extend.MarketingCenter.RB_DiscountCoupon_Extend { TenantId = oldOrder.TenantId, MallBaseId = oldOrder.MallBaseId, UserId = oldOrder.UserId ?? 0, TriggerType = 2 });
                if (couponList != null && couponList.Any(x => x.TotalNum == -1 || ((x.TotalNum - x.ReceiveNum) > 0)))//存在满足条件的优惠券可以发放
                {
                    bool isReceive = false;
                    //查询已发放的优惠券信息
                    var memberCouponList = memberCouponRepository.GetAutoMemberCouponPageList(new RB_Member_DiscountCoupon_Extend { UserId = oldOrder.UserId, GetType =2, TenantId = oldOrder.TenantId, MallBaseId = oldOrder.MallBaseId });
                    foreach (var item in couponList.Where(x => x.TotalNum == -1 || ((x.TotalNum - x.ReceiveNum) > 0)))//判断当前优惠券是否已超过领取数
                    {
                        int membercouponCoun = memberCouponList.Where(x => x.CouponId == item.ID).Count();
                        if (!isReceive && membercouponCoun < item.GrantNum)//此次没有领取，并且当前优惠券没有超过领取数量
                        {
                            var trans = memberCouponRepository.DbTransaction;
                            try
                            {
                                RB_Member_DiscountCoupon nowMemberCoupon = new RB_Member_DiscountCoupon
                                {
                                    Id = 0,
                                    TenantId = oldOrder.TenantId,
                                    MallBaseId = oldOrder.MallBaseId,
                                    Status = 0,
                                    CreateDate = System.DateTime.Now,
                                    UserId = oldOrder.UserId,
                                    Description = item.TriggerType == 1 ? "分享自动发放优惠券" : (item.TriggerType == 2 ? "购买并付款自动发放优惠券" : "新人领劵自动发放优惠券"),
                                    Remarks = item.TriggerType == 1 ? "分享" : (item.TriggerType == 2 ? "购买并付款" : "新人领劵"),
                                    UseState = 0,
                                    CouponId = item.ID,
                                    StartDate = item.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon ? System.DateTime.Now : item.StartDate,
                                    EndDate = item.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon ? System.DateTime.Now.AddDays(item.IndateDay) : item.EndDate,
                                    GetType = item.TriggerType,
                                    UseType = item.UseType,
                                    MinConsumePrice = item.MinConsumePrice,
                                    DiscountsPrice = item.DiscountsPrice,
                                    MaxDiscountsPrice = item.MaxDiscountsPrice,
                                    CouponType = item.CouponType,
                                    Name = item.Name
                                };

                                isReceive = memberCouponRepository.Insert(nowMemberCoupon, trans) > 0;
                                if (isReceive)//更新当前优惠券的领取数量
                                {
                                    Dictionary<string, object> cols1;

                                    if (item.TotalNum != -1)
                                    {
                                        cols1 = new Dictionary<string, object>()
                                    {
                                        { nameof(RB_DiscountCoupon.ReceiveNum),item.ReceiveNum+1},
                                        { nameof(RB_DiscountCoupon.TotalNum),item.TotalNum - 1},
                                        { nameof(RB_DiscountCoupon.UpdateDate),DateTime.Now},
                                    };
                                    }
                                    else
                                    {
                                        cols1 = new Dictionary<string, object>()
                                    {
                                        { nameof(RB_DiscountCoupon.ReceiveNum),item.ReceiveNum+1},
                                        { nameof(RB_DiscountCoupon.UpdateDate),DateTime.Now},
                                    };
                                    }
                                    List<WhereHelper> wheres1 = new List<WhereHelper>()
                                {
                                    new WhereHelper(){
                                            FiledName=nameof(RB_DiscountCoupon.ID),
                                            FiledValue=item.ID,
                                            OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                            FiledName=nameof(RB_DiscountCoupon.TenantId),
                                            FiledValue=item.TenantId,
                                            OperatorEnum=OperatorEnum.Equal
                                    },
                                    new WhereHelper(){
                                            FiledName=nameof(RB_DiscountCoupon.MallBaseId),
                                            FiledValue=item.MallBaseId,
                                            OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                    discountCouponRepository.Update(cols1, wheres1, trans);
                                }
                                memberCouponRepository.DBSession.Commit();
                                return true;
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Write(ex, "AutoCoupon");
                                memberCouponRepository.DBSession.Rollback("AutoCoupon");
                                return false;
                            }
                        }
                    }
                }

                //赠送粉象等级(+VIP返佣)  ld 2020-08-03
                var FXCOrder = oldOrder.RefMapperTo<RB_Goods_Order_Extend>();
                FXCOrder.DetailList = orderGoodsList;
                System.Threading.Tasks.Task.Run(() => InsertPresentFXGradeCommission(FXCOrder, Out_Trade_No, Transaction_Id, PayWay, oldOrder.UserId ?? 0, oldOrder.OrderId));

                //发送订阅消息
                string goodsName = orderGoodsList.FirstOrDefault().GoodsName;
                if (orderGoodsList.Count > 1)
                {
                    if (goodsName.Length > 6)
                    {
                        goodsName = goodsName.Substring(0, 6);
                    }
                    goodsName += "等" + orderGoodsList.Count + "件";
                }
                else
                {
                    if (goodsName.Length > 10)
                    {
                        goodsName = goodsName.Substring(0, 10);
                    }
                }
                appletWeChatModule.SendOrderSucceedMsg(oldOrder.TenantId, oldOrder.MallBaseId, umodel.OpenId, oldOrder.OrderNo, oldOrder.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss"), (oldOrder.Income ?? 0).ToString(), goodsName);
            }
            return flag;
        }

        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="OrderId"></param>
        public void TestFxGradeCommission(int OrderId) {
            var oldOrder = goods_OrderRepository.GetEntity<RB_Goods_Order_Extend>(OrderId);
            //获取订单商品
            var orderGoodsList = goodsOrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend { TenantId = oldOrder.TenantId, MallBaseId = oldOrder.MallBaseId, OrderId = oldOrder.OrderId });
            oldOrder.DetailList = orderGoodsList;
            System.Threading.Tasks.Task.Run(() => InsertPresentFXGradeCommission(oldOrder, oldOrder.MerchantsNo, "", Common.Enum.Goods.OrderPayTypeEnum.WeChatPay, oldOrder.UserId ?? 0, oldOrder.OrderId));
        }


        /// <summary>
        /// 赠送粉象等级(并返VIP佣金)
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="umodel"></param>
        /// <param name="OrderId"></param>
        private void InsertPresentFXGradeCommission(RB_Goods_Order_Extend demodel,string Out_Trade_No,string Transaction_Id, Common.Enum.Goods.OrderPayTypeEnum PayWay, int UserId, int OrderId)
        {
            var basicModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if ((basicModel?.IsEnableFXGrade ?? 2) == 1)
            {
                var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = UserId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                if (disModel == null)
                {
                    LogHelper.Write("该用户分销商等级不存在，UserId:" + UserId);
                }
                if (demodel.DetailList.Where(x => x.PresentFXGrade > 0).Any() && disModel != null)
                {
                    var vipblist = vip_BuyRepository.GetVipBuyList(new RB_Vip_Buy_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, ReOrderId = OrderId });
                    if (vipblist.Any()) {
                        //已存在返佣记录了
                        return;
                    }
                    var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    var VIPModel = FXList.Where(x => x.IsGuest == 3).FirstOrDefault();
                    List<int> GradeList = new List<int>();//等级列表
                    int VIPMonths = 0;//vip赠送月份
                    int VIPBuyNum = 0;//vip购买数量 返佣时  需乘以该数量
                    foreach (var item in demodel.DetailList)
                    {
                        if (item.PresentFXGrade > 0)
                        {
                            //有赠送粉象等级
                            GradeList.Add(item.PresentFXGrade ?? 0);
                            if (item.PresentFXGrade == (VIPModel?.Id ?? 0))
                            {
                                VIPMonths += (item.PresentFXMonth ?? 0) * (item.Number ?? 0);
                                VIPBuyNum += (item.Number ?? 0);
                            }
                        }
                    }
                    if (GradeList.Any())
                    {
                        //判断等级 取最高级别
                        int MaxGradeId = 0;
                        int MaxGrade = 0;
                        if (GradeList.Distinct().Count() > 1)
                        {
                            //说明有两种级别  取最高的
                            foreach (var item in GradeList.Distinct())
                            {
                                var fxmodel = FXList.Where(x => x.Id == item).FirstOrDefault();
                                MaxGrade = (fxmodel.Grade ?? 0) > MaxGrade ? (fxmodel.Grade ?? 0) : MaxGrade;
                            }
                            MaxGradeId = FXList.Where(x => x.Grade == MaxGrade).FirstOrDefault()?.Id ?? 0;
                        }
                        else
                        {
                            MaxGradeId = GradeList.FirstOrDefault();
                            var fxmodel = FXList.Where(x => x.Id == MaxGradeId).FirstOrDefault();
                            MaxGrade = (fxmodel.Grade ?? 0) > MaxGrade ? (fxmodel.Grade ?? 0) : MaxGrade;
                        }
                        var oldGrade = FXList.Where(x => x.Id == disModel.FXGradeId).FirstOrDefault()?.Grade ?? 0;

                        try
                        {
                            bool UpdateGrade = false;
                            if (MaxGradeId > 0 && MaxGrade >= oldGrade && MaxGradeId == (VIPModel?.Id ?? 0))
                            {
                                UpdateGrade = true;
                                string MaxGradeName = FXList.Where(x => x.Id == MaxGradeId).FirstOrDefault()?.GradeName ?? "";
                                //vip 
                                var VipExpiryDate = DateTime.Now.AddMonths(VIPMonths);
                                if (VIPMonths >= 1)
                                {
                                    VipExpiryDate = Convert.ToDateTime(VipExpiryDate.AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));
                                }
                                if (MaxGrade == oldGrade && disModel.VipExpiryDate.HasValue)
                                {
                                    if (disModel.VipExpiryDate > DateTime.Now)
                                    {
                                        VipExpiryDate = disModel.VipExpiryDate.Value.AddMonths(VIPMonths);
                                    }
                                }
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>
                                    {
                                        { nameof(RB_Distributor_Info_Extend.FXGradeId), MaxGradeId },
                                        { nameof(RB_Distributor_Info_Extend.VipExpiryDate), VipExpiryDate }
                                    };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                              FiledValue=disModel.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                bool gflag = distributor_InfoRepository.Update(keyValues1, wheres1);
                                if (gflag)
                                {
                                    //新增vip赠送记录表
                                    Random R1 = new Random();
                                    int Rstr1 = R1.Next(111, 999);
                                    string OrderNo1 = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr1;
                                    int vipBuyId = vip_BuyRepository.Insert(new Model.Entity.User.RB_Vip_Buy()
                                    {
                                        CreateDate = DateTime.Now,
                                        ExpiryDate = VipExpiryDate,
                                        GradeId = MaxGradeId,
                                        GradeName = MaxGradeName,
                                        Id = 0,
                                        MallBaseId = demodel.MallBaseId,
                                        MerchantsNo = Out_Trade_No,
                                        Money = demodel.Income ?? 0,
                                        OrderNo = OrderNo1,
                                        PayState = 1,
                                        PayTime = DateTime.Now,
                                        PayWay = 1,
                                        Remark = "下单赠送，订单号：" + demodel.OrderNo + "(" + OrderId + ")",
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        UserId = UserId,
                                        ReOrderId = OrderId,
                                        ReOrderNum = demodel.OrderNo
                                    });
                                    if (vipBuyId > 0)
                                    {
                                        //插入返佣信息
                                        InsertVipBuyCommissionForPresent(UserId, vipBuyId, VIPBuyNum, disModel, FXList);
                                    }
                                }
                            }
                            else if (MaxGradeId > 0 && MaxGrade > oldGrade)
                            {
                                UpdateGrade = true;
                                string MaxGradeName = FXList.Where(x => x.Id == MaxGradeId).FirstOrDefault()?.GradeName ?? "";
                                //比vip高级
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>
                                    {
                                        { nameof(RB_Distributor_Info_Extend.FXGradeId), MaxGradeId }
                                    };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                              FiledValue=disModel.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                bool gflag = distributor_InfoRepository.Update(keyValues1, wheres1);
                                if (gflag)
                                {
                                    //新增vip赠送记录表
                                    Random R1 = new Random();
                                    int Rstr1 = R1.Next(111, 999);
                                    string OrderNo1 = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr1;
                                    int vipBuyId = vip_BuyRepository.Insert(new Model.Entity.User.RB_Vip_Buy()
                                    {
                                        CreateDate = DateTime.Now,
                                        ExpiryDate = null,
                                        GradeId = MaxGradeId,
                                        GradeName = MaxGradeName,
                                        Id = 0,
                                        MallBaseId = demodel.MallBaseId,
                                        MerchantsNo = Out_Trade_No,
                                        Money = demodel.Income ?? 0,
                                        OrderNo = OrderNo1,
                                        PayState = 1,
                                        PayTime = DateTime.Now,
                                        PayWay = 1,
                                        Remark = "下单赠送，订单号：" + demodel.OrderNo + "(" + OrderId + ")",
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        UserId = UserId,
                                        ReOrderId = OrderId,
                                        ReOrderNum = demodel.OrderNo
                                    });
                                    if (vipBuyId > 0)
                                    {
                                        //插入返佣信息
                                        InsertVipBuyCommissionForPresent(UserId, vipBuyId, VIPBuyNum, disModel, FXList);
                                    }
                                }
                            }
                            else if(MaxGradeId > 0) {
                                string MaxGradeName = FXList.Where(x => x.Id == MaxGradeId).FirstOrDefault()?.GradeName ?? "";
                                //新增vip赠送记录表
                                Random R1 = new Random();
                                int Rstr1 = R1.Next(111, 999);
                                string OrderNo1 = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr1;
                                int vipBuyId = vip_BuyRepository.Insert(new Model.Entity.User.RB_Vip_Buy()
                                {
                                    CreateDate = DateTime.Now,
                                    ExpiryDate = null,
                                    GradeId = MaxGradeId,
                                    GradeName = MaxGradeName,
                                    Id = 0,
                                    MallBaseId = demodel.MallBaseId,
                                    MerchantsNo = Out_Trade_No,
                                    Money = demodel.Income ?? 0,
                                    OrderNo = OrderNo1,
                                    PayState = 1,
                                    PayTime = DateTime.Now,
                                    PayWay = 1,
                                    Remark = "下单赠送，订单号：" + demodel.OrderNo + "(" + OrderId + ")",
                                    Status = 0,
                                    TenantId = demodel.TenantId,
                                    UserId = UserId,
                                    ReOrderId = OrderId,
                                    ReOrderNum = demodel.OrderNo
                                });
                                if (vipBuyId > 0)
                                {
                                    //插入返佣信息
                                    InsertVipBuyCommissionForPresent(UserId, vipBuyId, VIPBuyNum, disModel, FXList);
                                }
                            }
                            if (UpdateGrade)
                            {
                                FXAutoUpgradeUserDistributorGrade(UserId, demodel.TenantId, demodel.MallBaseId);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "InsertPresentFXGrade赠送粉象分销等级失败，OrderId：" + OrderId);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 下单赠送VIP返佣
        /// </summary>
        /// <param name="BuyUserId"></param>
        /// <param name="OrderId">Vip订单id</param>
        /// <param name="Out_Trade_No"></param>
        /// <param name="Transaction_Id"></param>
        /// <param name="PayWay"></param>
        /// <param name="VIPBuyNum"></param>
        /// <param name="VIPBuyId"></param>
        /// <param name="disModel"></param>
        /// <param name="FXList"></param>
        /// <returns></returns>
        public bool InsertVipBuyCommissionForPresent(int BuyUserId, int OrderId, int VIPBuyNum, RB_Distributor_Info_Extend disModel, List<RB_Distributor_FXGrade_Extend> FXList)
        {
            bool flag = false;
            try
            {
                int TenantId = 0; int MallBaseId = 0;
                var uModel = member_UserRepository.GetEntity(BuyUserId);
                if (uModel == null)
                {
                    return false;
                }

                //判断订单状态是否是待支付 
                var model = vipBuyRepository.GetEntity(OrderId);
                if (model == null)
                {
                    return false;
                }
                
                TenantId = model.TenantId;
                MallBaseId = model.MallBaseId;
                var trans = vipBuyRepository.DbTransaction;

                
                //粉象等级列表
                var VipModel = FXList.Where(x => x.IsGuest == 3).FirstOrDefault();
                if (VipModel == null) { vipBuyRepository.DBSession.Rollback(); return false; }
                var PTModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
                if (PTModel == null) { vipBuyRepository.DBSession.Rollback(); return false; }
                //vip购买返佣金额列表
                var FXCList = distributor_FXCommissionRepository.GetFXCommissionList(new RB_Distributor_FXCommission_Extend() { TenantId = TenantId, MallBaseId = MallBaseId });
                if (disModel != null)
                {
                    // 2020-08-03 ld  暂屏蔽 所有人都能购买 反VIP
                    //if (disModel.FXGradeId != VipModel.Id && disModel.FXGradeId != PTModel.Id)
                    //{
                    //    vipBuyRepository.DBSession.Rollback();
                    //    return false;
                    //}
                    //求其上级
                    var pmodel = member_UserRepository.GetEntity(uModel.SuperiorId);
                    if (pmodel == null) { vipBuyRepository.DBSession.Rollback(); return false; }
                    var dispModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = pmodel.Id, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                    if (dispModel != null)
                    {
                        var pfxModel = FXList.Where(x => x.Id == dispModel.FXGradeId).FirstOrDefault();
                        if (pfxModel == null) { vipBuyRepository.DBSession.Rollback(); return false; }
                        if (pfxModel.Grade < VipModel.Grade)
                        {
                            vipBuyRepository.DBSession.Rollback();
                            return false;//其上级不是vip   直接后面的全部不提
                        }
                        //查询出当前用户的所有上级
                        string UserIds = member_UserRepository.GetMemberParentIdStr(pmodel.Id);
                        var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = UserIds, TenantId = TenantId, MallBaseId = MallBaseId });
                        //查询出用户的所有分销信息
                        var dlist = distributor_InfoRepository.GetListForSingle(new RB_Distributor_Info_Extend() { UserIds = UserIds, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited, TenantId = TenantId, MallBaseId = MallBaseId });
                        foreach (var item in dlist)
                        {
                            item.Grade = FXList.Where(x => x.Id == item.FXGradeId).FirstOrDefault()?.Grade ?? 0;
                        }

                        //返佣
                        List<RB_VipBuy_Commission> gocList = new List<RB_VipBuy_Commission>();
                        List<Model.Entity.Product.FXOrderCommissionNumModel> fxNumList = new List<Model.Entity.Product.FXOrderCommissionNumModel>();
                        int UserId = pmodel.Id;
                        int Num = 1;
                        while (UserId > 0)
                        {
                            var numodel = ulist.Where(x => x.Id == UserId).FirstOrDefault();
                            if (numodel == null)
                            {
                                UserId = 0;
                                break;
                            }

                            var d2Model = dlist.Where(x => x.UserId == numodel.Id).FirstOrDefault();
                            if (d2Model == null)
                            {
                                UserId = 0;
                                break;
                            }
                            var FXGModel = FXList.Where(x => x.Id == d2Model.FXGradeId).FirstOrDefault();
                            if (FXGModel == null)
                            {
                                UserId = 0;
                                break;
                            }

                            if (!fxNumList.Any())
                            {
                                //第一个人  拿直推vip
                                var fxcModel = FXCList.Where(x => x.FXGradeId == FXGModel.Id && x.CommissionGradeId == VipModel.Id && x.GradeType == 1).FirstOrDefault();
                                fxNumList.Add(new Model.Entity.Product.FXOrderCommissionNumModel()
                                {
                                    GradeId = FXGModel.Id,
                                    Grade = FXGModel.Grade ?? 0,
                                    Money = fxcModel?.CommissionPrice ?? 0,
                                    Sort = Num,
                                    IsSelfBuy = 2
                                });
                                gocList.Add(new RB_VipBuy_Commission()
                                {
                                    Id = 0,
                                    Commission = fxcModel?.CommissionPrice ?? 0,
                                    CreateDate = DateTime.Now,
                                    Grade = FXGModel.Id,
                                    IsRemit = 0,
                                    MallBaseId = MallBaseId,
                                    OrderId = OrderId,
                                    Remark = "下单赠送VIP",
                                    TenantId = TenantId,
                                    Type = 1,
                                    UpdateDate = DateTime.Now,
                                    UserId = UserId
                                });
                                Num++;
                                UserId = numodel.SuperiorId ?? 0;
                            }
                            else
                            {
                                //后面的拿间接vip  或者其他
                                int MaxGrade = fxNumList.Max(x => x.Grade);
                                if (FXGModel.Grade < MaxGrade)
                                {
                                    //后面的全部不返佣
                                    UserId = 0;
                                    break;
                                }
                                int MaxGradeNum = fxNumList.Where(x => x.Grade == FXGModel.Grade).Count();
                                int MaxGradeId = fxNumList.Where(x => x.Grade == MaxGrade).FirstOrDefault()?.GradeId ?? 0;
                                if ((FXGModel.SiblingRebatesNum ?? 0) + 1 > MaxGradeNum)
                                {
                                    decimal DcommionMoney = 0;
                                    if (MaxGradeNum >= 1 && MaxGrade == VipModel.Id)
                                    {
                                        //拿间接vip
                                        var fxcModel = FXCList.Where(x => x.FXGradeId == FXGModel.Id && x.CommissionGradeId == VipModel.Id && x.GradeType == 2).FirstOrDefault();
                                        DcommionMoney = fxcModel?.CommissionPrice ?? 0;
                                    }
                                    else if (FXGModel.Grade > VipModel.Grade)
                                    {
                                        if (MaxGrade == VipModel.Id)
                                        {
                                            var fxcModel = FXCList.Where(x => x.FXGradeId == FXGModel.Id && x.CommissionGradeId == MaxGradeId && x.GradeType == 2).FirstOrDefault();
                                            DcommionMoney = fxcModel?.CommissionPrice ?? 0;
                                        }
                                        else
                                        {
                                            var fxcModel = FXCList.Where(x => x.FXGradeId == FXGModel.Id && x.CommissionGradeId == MaxGradeId && x.GradeType == 1).FirstOrDefault();
                                            DcommionMoney = fxcModel?.CommissionPrice ?? 0;
                                        }
                                    }

                                    fxNumList.Add(new Model.Entity.Product.FXOrderCommissionNumModel()
                                    {
                                        GradeId = FXGModel.Id,
                                        Grade = FXGModel.Grade ?? 0,
                                        Money = DcommionMoney,
                                        Sort = Num,
                                        IsSelfBuy = 2
                                    });
                                    gocList.Add(new RB_VipBuy_Commission()
                                    {
                                        Id = 0,
                                        Commission = DcommionMoney,
                                        CreateDate = DateTime.Now,
                                        Grade = FXGModel.Id,
                                        IsRemit = 0,
                                        MallBaseId = MallBaseId,
                                        OrderId = OrderId,
                                        Remark = "下单赠送VIP",
                                        TenantId = TenantId,
                                        Type = 1,
                                        UpdateDate = DateTime.Now,
                                        UserId = UserId
                                    });
                                    Num++;
                                    UserId = numodel.SuperiorId ?? 0;
                                }
                                else
                                {
                                    UserId = 0;
                                    //该等级的已提完了  看是否可以直接找到下一个等级的
                                    var fx2List = dlist.Where(x => x.Grade > MaxGrade).ToList();
                                    if (fx2List.Any())
                                    {
                                        //说明是有下一级的
                                        for (var i = 0; i < ulist.Count; i++)
                                        {
                                            var n1umodel = ulist.Where(x => x.Id == (numodel.SuperiorId ?? 0)).FirstOrDefault();
                                            if (n1umodel == null)
                                            {
                                                UserId = 0;
                                                break;
                                            }
                                            var dis1Model = dlist.Where(x => x.UserId == n1umodel.Id).FirstOrDefault();
                                            var FXG2Model = new RB_Distributor_FXGrade_Extend();
                                            if (dis1Model == null)
                                            {
                                                UserId = 0;
                                                break;
                                            }
                                            FXG2Model = FXList.Where(x => x.Id == dis1Model.FXGradeId).FirstOrDefault();
                                            if (FXG2Model == null)
                                            {
                                                UserId = 0;
                                                break;
                                            }

                                            if (FXG2Model.Grade < MaxGrade)
                                            {
                                                //后面的全部不返佣
                                                UserId = 0;
                                                break;
                                            }
                                            else if (FXG2Model.Grade > MaxGrade)
                                            {
                                                //已找到上级  继续返佣
                                                UserId = n1umodel.Id;
                                                break;
                                            }
                                            else
                                            {
                                                UserId = 0;
                                                numodel = n1umodel;//继续查找下一级
                                            }
                                        }
                                    }

                                }
                            }
                        }

                        if (gocList.Any())
                        {
                            string FUserIds = string.Join(",", gocList.Select(x => x.UserId).Distinct());
                            //最后再次查询分销商 便于返佣金
                            var fdlist = distributor_InfoRepository.GetListForSingle(new RB_Distributor_Info_Extend() { UserIds = FUserIds, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited, TenantId = TenantId, MallBaseId = MallBaseId });

                            foreach (var qitem in gocList)
                            {
                                if (qitem.Commission > 0)
                                {
                                    qitem.Commission = (qitem.Commission ?? 0) * VIPBuyNum;//乘以购买的份数
                                    flag = vipBuy_CommissionRepository.Insert(qitem, trans) > 0;
                                    if (flag)
                                    {
                                        //分销商增加相应的佣金
                                        var numodel = ulist.Where(x => x.Id == qitem.UserId).FirstOrDefault();
                                        var fmodel = fdlist.Where(x => x.UserId == (numodel?.Id ?? 0)).FirstOrDefault();
                                        if (fmodel != null)
                                        {
                                            //分销商增加佣金
                                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                                    { nameof(RB_Distributor_Info.TotalCommission),(fmodel.TotalCommission??0)+(qitem.Commission??0)},
                                                    { nameof(RB_Distributor_Info.CommissionWithdrawal),(fmodel.CommissionWithdrawal??0)+(qitem.Commission??0)},
                                                };
                                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                            FiledName=nameof(RB_Distributor_Info.Id),
                                                            FiledValue=fmodel.Id,
                                                            OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                            distributor_InfoRepository.Update(keyValues, wheres, trans);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                vipBuyRepository.DBSession.Commit();

                //购买vip之后  其上级验证  如果满足升级  将自动升级为更高级别的分销商
                FXAutoUpgradeUserDistributorGrade(BuyUserId, TenantId, MallBaseId);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "InsertVipBuyCommission2");
                vipBuyRepository.DBSession.Rollback();
                return false;
            }
        }

        #region VIP购买
        /// <summary>
        /// 新增vip购买返佣
        /// </summary>
        /// <param name="OrderId">vip购买单号id</param>
        /// <param name="BuyUserId">购买人</param>
        /// <returns></returns>
        //public bool InsertVipBuyCommission(int OrderId, int BuyUserId,int IsFristBuy,int TenantId,int MallBaseId)
        public bool InsertVipBuyCommission(int BuyUserId, int OrderId, string Out_Trade_No, string Transaction_Id, Common.Enum.Goods.OrderPayTypeEnum PayWay, decimal Money, DateTime Time_End)
        {
            bool flag = false;
            try
            {
                int IsFristBuy = 0; int TenantId = 0; int MallBaseId = 0;

                var uModel = member_UserRepository.GetEntity(BuyUserId);
                if (uModel == null)
                {
                    return false;
                }
                //判断订单状态是否是待支付 
                var buyList = vipBuyRepository.GetVipBuyList(new RB_Vip_Buy_Extend { UserId = BuyUserId });

                //获取会员分销商的信息
                var distributorModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend { TenantId = uModel.TenantId, MallBaseId = uModel.MallBaseId, UserId = uModel.Id }).FirstOrDefault();
                if (distributorModel == null)
                {
                    return false;
                }
                if (buyList.Where(x => x.PayState == 1).Count() == 0)
                {
                    IsFristBuy = 1;
                }
                var model = buyList.Where(x => x.Id == OrderId).FirstOrDefault();
                if (model == null)
                {
                    return false;
                }
                if (model.PayState != 0)
                {
                    return false;
                }
                if (model.Money != Money)
                {
                    return false;
                }
                TenantId = model.TenantId;
                MallBaseId = model.MallBaseId;
                var trans = vipBuyRepository.DbTransaction;

                //判断返佣的过期时间
                if (distributorModel.VipExpiryDate.HasValue)
                {
                    if (distributorModel.VipExpiryDate.Value > System.DateTime.Now && distributorModel.FXGradeId == model.GradeId)
                    {
                        int year = model.ExpiryDate.Value.Year - model.CreateDate.Year;
                        distributorModel.VipExpiryDate = Convert.ToDateTime(distributorModel.VipExpiryDate.Value.AddYears((year == 0 ? 1 : year)).AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));
                    }
                    else
                    {
                        distributorModel.VipExpiryDate = model.ExpiryDate;
                    }
                }
                else
                {
                    distributorModel.VipExpiryDate = model.ExpiryDate;
                }

                //2020-07-17 Add By:W 
                Dictionary<string, object> keyValuesVip = new Dictionary<string, object>() {
                                        { nameof(RB_Vip_Buy.PayTime),Time_End},
                                        { nameof(RB_Vip_Buy.PayState),1},
                                        { nameof(RB_Vip_Buy.MerchantsNo),Out_Trade_No},
                                         { nameof(RB_Vip_Buy.ExpiryDate), distributorModel.VipExpiryDate }
                                    };
                List<WhereHelper> wheresVip = new List<WhereHelper>() {
                                        new WhereHelper{
                                            FiledName=nameof(RB_Vip_Buy.Id),
                                            FiledValue=OrderId,
                                            OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                flag = vipBuyRepository.Update(keyValuesVip, wheresVip, trans);//更新会员购买记录 2020-07-17 Add By: W End



                //2020-07-20 Add By:W 
                Dictionary<string, object> keyValuesDistributor = new Dictionary<string, object>() {
                                        { nameof(RB_Distributor_Info.VipExpiryDate),distributorModel.VipExpiryDate},
                                         { nameof(RB_Distributor_Info.FXGradeId),model.GradeId}
                                    };
                List<WhereHelper> wheresDistributor = new List<WhereHelper>() {
                                        new WhereHelper{
                                            FiledName=nameof(RB_Distributor_Info.Id),
                                            FiledValue=distributorModel.Id,
                                            OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                distributor_InfoRepository.Update(keyValuesDistributor, wheresDistributor, trans);//更新会员分销商vip过期时间 2020-07-20 Add By: W End


                //获取用户当前分销商
                var basicModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
                if (basicModel.IsEnableFXGrade == 1)
                {

                    if (uModel == null) { vipBuyRepository.DBSession.Rollback(); return false; }
                    //粉象等级列表
                    var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = TenantId, MallBaseId = MallBaseId });
                    var VipModel = FXList.Where(x => x.IsGuest == 3).FirstOrDefault();
                    if (VipModel == null) { vipBuyRepository.DBSession.Rollback(); return false; }
                    var PTModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
                    if (PTModel == null) { vipBuyRepository.DBSession.Rollback(); return false; }
                    //vip购买返佣金额列表
                    var FXCList = distributor_FXCommissionRepository.GetFXCommissionList(new RB_Distributor_FXCommission_Extend() { TenantId = TenantId, MallBaseId = MallBaseId });
                    var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = BuyUserId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                    if (disModel != null)
                    {
                        if (disModel.FXGradeId != VipModel.Id && disModel.FXGradeId != PTModel.Id)
                        {
                            vipBuyRepository.DBSession.Rollback();
                            return false;
                        }
                        //求其上级
                        var pmodel = member_UserRepository.GetEntity(uModel.SuperiorId);
                        if (pmodel == null) { vipBuyRepository.DBSession.Rollback(); return false; }
                        var dispModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = pmodel.Id, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                        if (dispModel != null)
                        {
                            var pfxModel = FXList.Where(x => x.Id == dispModel.FXGradeId).FirstOrDefault();
                            if (pfxModel == null) { vipBuyRepository.DBSession.Rollback(); return false; }
                            if (pfxModel.Grade < VipModel.Grade)
                            {
                                vipBuyRepository.DBSession.Rollback();
                                return false;//其上级不是vip   直接后面的全部不提
                            }
                            //查询出当前用户的所有上级
                            string UserIds = member_UserRepository.GetMemberParentIdStr(pmodel.Id);
                            var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = UserIds, TenantId = TenantId, MallBaseId = MallBaseId });
                            //查询出用户的所有分销信息
                            var dlist = distributor_InfoRepository.GetListForSingle(new RB_Distributor_Info_Extend() { UserIds = UserIds, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited, TenantId = TenantId, MallBaseId = MallBaseId });
                            foreach (var item in dlist)
                            {
                                item.Grade = FXList.Where(x => x.Id == item.FXGradeId).FirstOrDefault()?.Grade ?? 0;
                            }

                            //返佣
                            List<RB_VipBuy_Commission> gocList = new List<RB_VipBuy_Commission>();
                            List<Model.Entity.Product.FXOrderCommissionNumModel> fxNumList = new List<Model.Entity.Product.FXOrderCommissionNumModel>();
                            int UserId = pmodel.Id;
                            int Num = 1;
                            while (UserId > 0)
                            {
                                var numodel = ulist.Where(x => x.Id == UserId).FirstOrDefault();
                                if (numodel == null)
                                {
                                    UserId = 0;
                                    break;
                                }

                                var d2Model = dlist.Where(x => x.UserId == numodel.Id).FirstOrDefault();
                                if (d2Model == null)
                                {
                                    UserId = 0;
                                    break;
                                }
                                var FXGModel = FXList.Where(x => x.Id == d2Model.FXGradeId).FirstOrDefault();
                                if (FXGModel == null)
                                {
                                    UserId = 0;
                                    break;
                                }

                                if (!fxNumList.Any())
                                {
                                    //第一个人  拿直推vip
                                    var fxcModel = FXCList.Where(x => x.FXGradeId == FXGModel.Id && x.CommissionGradeId == VipModel.Id && x.GradeType == 1).FirstOrDefault();
                                    fxNumList.Add(new Model.Entity.Product.FXOrderCommissionNumModel()
                                    {
                                        GradeId = FXGModel.Id,
                                        Grade = FXGModel.Grade ?? 0,
                                        Money = fxcModel?.CommissionPrice ?? 0,
                                        Sort = Num,
                                        IsSelfBuy = 2
                                    });
                                    gocList.Add(new RB_VipBuy_Commission()
                                    {
                                        Id = 0,
                                        Commission = fxcModel?.CommissionPrice ?? 0,
                                        CreateDate = DateTime.Now,
                                        Grade = FXGModel.Id,
                                        IsRemit = 0,
                                        MallBaseId = MallBaseId,
                                        OrderId = OrderId,
                                        Remark = IsFristBuy == 1 ? "下线购买vip返佣" : "下线续费vip返佣",
                                        TenantId = TenantId,
                                        Type = 1,
                                        UpdateDate = DateTime.Now,
                                        UserId = UserId
                                    });
                                    Num++;
                                    UserId = numodel.SuperiorId ?? 0;
                                }
                                else
                                {
                                    //后面的拿间接vip  或者其他
                                    int MaxGrade = fxNumList.Max(x => x.Grade);
                                    if (FXGModel.Grade < MaxGrade)
                                    {
                                        //后面的全部不返佣
                                        UserId = 0;
                                        break;
                                    }
                                    int MaxGradeNum = fxNumList.Where(x => x.Grade == FXGModel.Grade).Count();
                                    int MaxGradeId = fxNumList.Where(x => x.Grade == MaxGrade).FirstOrDefault()?.GradeId ?? 0;
                                    if ((FXGModel.SiblingRebatesNum ?? 0) + 1 > MaxGradeNum)
                                    {
                                        decimal DcommionMoney = 0;
                                        if (MaxGradeNum >= 1 && MaxGrade == VipModel.Id)
                                        {
                                            //拿间接vip
                                            var fxcModel = FXCList.Where(x => x.FXGradeId == FXGModel.Id && x.CommissionGradeId == VipModel.Id && x.GradeType == 2).FirstOrDefault();
                                            DcommionMoney = fxcModel?.CommissionPrice ?? 0;
                                        }
                                        else if (FXGModel.Grade > VipModel.Grade)
                                        {
                                            if (MaxGrade == VipModel.Id)
                                            {
                                                var fxcModel = FXCList.Where(x => x.FXGradeId == FXGModel.Id && x.CommissionGradeId == MaxGradeId && x.GradeType == 2).FirstOrDefault();
                                                DcommionMoney = fxcModel?.CommissionPrice ?? 0;
                                            }
                                            else
                                            {
                                                var fxcModel = FXCList.Where(x => x.FXGradeId == FXGModel.Id && x.CommissionGradeId == MaxGradeId && x.GradeType == 1).FirstOrDefault();
                                                DcommionMoney = fxcModel?.CommissionPrice ?? 0;
                                            }
                                        }

                                        fxNumList.Add(new Model.Entity.Product.FXOrderCommissionNumModel()
                                        {
                                            GradeId = FXGModel.Id,
                                            Grade = FXGModel.Grade ?? 0,
                                            Money = DcommionMoney,
                                            Sort = Num,
                                            IsSelfBuy = 2
                                        });
                                        gocList.Add(new RB_VipBuy_Commission()
                                        {
                                            Id = 0,
                                            Commission = DcommionMoney,
                                            CreateDate = DateTime.Now,
                                            Grade = FXGModel.Id,
                                            IsRemit = 0,
                                            MallBaseId = MallBaseId,
                                            OrderId = OrderId,
                                            Remark = IsFristBuy == 1 ? "下线购买vip返佣" : "下线续费vip返佣",
                                            TenantId = TenantId,
                                            Type = 1,
                                            UpdateDate = DateTime.Now,
                                            UserId = UserId
                                        });
                                        Num++;
                                        UserId = numodel.SuperiorId ?? 0;
                                    }
                                    else
                                    {
                                        UserId = 0;
                                        //该等级的已提完了  看是否可以直接找到下一个等级的
                                        var fx2List = dlist.Where(x => x.Grade > MaxGrade).ToList();
                                        if (fx2List.Any())
                                        {
                                            //说明是有下一级的
                                            for (var i = 0; i < ulist.Count; i++)
                                            {
                                                var n1umodel = ulist.Where(x => x.Id == (numodel.SuperiorId ?? 0)).FirstOrDefault();
                                                if (n1umodel == null)
                                                {
                                                    UserId = 0;
                                                    break;
                                                }
                                                var dis1Model = dlist.Where(x => x.UserId == n1umodel.Id).FirstOrDefault();
                                                var FXG2Model = new RB_Distributor_FXGrade_Extend();
                                                if (dis1Model == null)
                                                {
                                                    UserId = 0;
                                                    break;
                                                }
                                                FXG2Model = FXList.Where(x => x.Id == dis1Model.FXGradeId).FirstOrDefault();
                                                if (FXG2Model == null)
                                                {
                                                    UserId = 0;
                                                    break;
                                                }

                                                if (FXG2Model.Grade < MaxGrade)
                                                {
                                                    //后面的全部不返佣
                                                    UserId = 0;
                                                    break;
                                                }
                                                else if (FXG2Model.Grade > MaxGrade)
                                                {
                                                    //已找到上级  继续返佣
                                                    UserId = n1umodel.Id;
                                                    break;
                                                }
                                                else
                                                {
                                                    UserId = 0;
                                                    numodel = n1umodel;//继续查找下一级
                                                }
                                            }
                                        }

                                    }
                                }
                            }

                            if (gocList.Any())
                            {
                                string FUserIds = string.Join(",", gocList.Select(x => x.UserId).Distinct());
                                //最后再次查询分销商 便于返佣金
                                var fdlist = distributor_InfoRepository.GetListForSingle(new RB_Distributor_Info_Extend() { UserIds = FUserIds, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited, TenantId = TenantId, MallBaseId = MallBaseId });

                                foreach (var qitem in gocList)
                                {
                                    if (qitem.Commission > 0)
                                    {
                                        flag = vipBuy_CommissionRepository.Insert(qitem, trans) > 0;
                                        if (flag)
                                        {
                                            //分销商增加相应的佣金
                                            var numodel = ulist.Where(x => x.Id == qitem.UserId).FirstOrDefault();
                                            var fmodel = fdlist.Where(x => x.UserId == (numodel?.Id ?? 0)).FirstOrDefault();
                                            if (fmodel != null)
                                            {
                                                //分销商增加佣金
                                                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                                        { nameof(RB_Distributor_Info.TotalCommission),(fmodel.TotalCommission??0)+(qitem.Commission??0)},
                                                        { nameof(RB_Distributor_Info.CommissionWithdrawal),(fmodel.CommissionWithdrawal??0)+(qitem.Commission??0)},
                                                    };
                                                List<WhereHelper> wheres = new List<WhereHelper>() {
                                                        new WhereHelper(){
                                                             FiledName=nameof(RB_Distributor_Info.Id),
                                                              FiledValue=fmodel.Id,
                                                               OperatorEnum=OperatorEnum.Equal
                                                        }
                                                    };
                                                distributor_InfoRepository.Update(keyValues, wheres, trans);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                vipBuyRepository.DBSession.Commit();

                if (basicModel.IsEnableFXGrade == 1)
                {
                    //购买vip之后  其上级验证  如果满足升级  将自动升级为更高级别的分销商
                    System.Threading.Tasks.Task.Run(() => FXAutoUpgradeUserDistributorGrade(BuyUserId, TenantId, MallBaseId));
                }
                return true;
            }
            catch (Exception ex)
            {

                LogHelper.Write(ex, "InsertVipBuyCommission");
                vipBuyRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 自动升级粉象分销商等级
        /// </summary>
        /// <param name="BuyUserId"></param>
        /// <returns></returns>
        public bool FXAutoUpgradeUserDistributorGrade(int BuyUserId, int TenantId, int MallBaseId)
        {
            try
            {
                var umodel = member_UserRepository.GetEntity(BuyUserId);
                if (umodel == null) { return false; }
                if (umodel.SuperiorId > 0)
                {
                    //粉象等级列表
                    var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = TenantId, MallBaseId = MallBaseId });
                    var dispmodel = distributor_InfoRepository.GetListForSingle(new RB_Distributor_Info_Extend() { UserId = umodel.SuperiorId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited, TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
                    if (dispmodel == null) { return false; }
                    var fxpmodel = FXList.Where(x => x.Id == (dispmodel.FXGradeId ?? 0)).FirstOrDefault();
                    var fxNext = FXList.Where(x => x.Grade > fxpmodel.Grade).OrderBy(x => x.Grade).FirstOrDefault();
                    if (fxpmodel != null && fxNext != null && fxNext.IsUpgrade == 1 && fxNext.UpgradeNum > 0 && fxNext.UpgradeId > 0)
                    {
                        //查询当前父级用户是否满足升级
                        var gmodel = FXList.Where(x => x.Id == fxNext.UpgradeId).FirstOrDefault();
                        //获取其下级数量
                        var upFXList = FXList.Where(x => x.Grade >= gmodel.Grade).ToList();
                        int MeetNum = 0;
                        //已发展等级
                        if (upFXList.Any())
                        {
                            string FXGradeIds = string.Join(",", upFXList.Select(x => x.Id));
                            MeetNum = member_UserRepository.GetUserReferralsForFX(new RB_Member_User_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, SuperiorId = umodel.SuperiorId, FXGradeIds = FXGradeIds });
                        }
                        if ((fxNext.UpgradeNum ?? 0) <= MeetNum)
                        {
                            //可以升级咯
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Distributor_Info.FXGradeId),fxNext.Id},
                                { nameof(RB_Distributor_Info.Remark),dispmodel.Remark+" ;分销商满足升级条件："+(fxNext.UpgradeNum ?? 0)+"位"+(gmodel.GradeName??"")+"下线，已自动升级为"+(fxNext.GradeName??"")},
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                    FiledName=nameof(RB_Distributor_Info.Id),
                                    FiledValue=dispmodel.Id,
                                    OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            bool flag = distributor_InfoRepository.Update(keyValues, wheres);
                            if (flag)
                            {
                                //继续找其上级的上级
                                //查询出当前用户的所有上级
                                var upmodel = member_UserRepository.GetEntity(umodel.SuperiorId);
                                if (upmodel.SuperiorId > 0)
                                {
                                    string UserIds = member_UserRepository.GetMemberParentIdStr(upmodel.Id);
                                    var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = UserIds, TenantId = TenantId, MallBaseId = MallBaseId });
                                    //查询出用户的所有分销信息
                                    var dlist = distributor_InfoRepository.GetListForSingle(new RB_Distributor_Info_Extend() { UserIds = UserIds, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited, TenantId = TenantId, MallBaseId = MallBaseId });
                                    int PId = upmodel.SuperiorId ?? 0;
                                    for (var i = 1; i < ulist.Count(); i++)
                                    {
                                        if (PId <= 0) { break; }
                                        var uppmodel = ulist.Where(x => x.Id == PId).FirstOrDefault();
                                        if (uppmodel == null) { break; }
                                        var disppmodel = dlist.Where(x => x.UserId == uppmodel.Id).FirstOrDefault();
                                        if (disppmodel == null) { break; }
                                        var fxppmodel = FXList.Where(x => x.Id == (disppmodel.FXGradeId ?? 0)).FirstOrDefault();
                                        if (fxppmodel == null) { break; }
                                        var fxpNext = FXList.Where(x => x.Grade > fxppmodel.Grade).OrderBy(x => x.Grade).FirstOrDefault();
                                        if (fxppmodel != null && fxpNext != null && fxpNext.IsUpgrade == 1 && fxpNext.UpgradeNum > 0 && fxpNext.UpgradeId > 0)
                                        {
                                            //查询当前父级用户是否满足升级
                                            var gpmodel = FXList.Where(x => x.Id == fxpNext.UpgradeId).FirstOrDefault();
                                            //获取其下级数量
                                            var upFXpList = FXList.Where(x => x.Grade >= gpmodel.Grade).ToList();
                                            int pMeetNum = 0;
                                            //已发展等级
                                            if (upFXpList.Any())
                                            {
                                                string FXGradeIds = string.Join(",", upFXpList.Select(x => x.Id));
                                                pMeetNum = member_UserRepository.GetUserReferralsForFX(new RB_Member_User_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, SuperiorId = uppmodel.Id, FXGradeIds = FXGradeIds });
                                            }
                                            if ((fxpNext.UpgradeNum ?? 0) <= pMeetNum)
                                            {
                                                //上级可以升级咯
                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                    { nameof(RB_Distributor_Info.FXGradeId),fxpNext.Id},
                                                    { nameof(RB_Distributor_Info.Remark),disppmodel.Remark+" ;分销商满足升级条件："+(fxpNext.UpgradeNum ?? 0)+"位"+(gpmodel.GradeName??"")+"下线，已自动升级为"+(fxpNext.GradeName??"")},
                                                };
                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                        FiledName=nameof(RB_Distributor_Info.Id),
                                                        FiledValue=disppmodel.Id,
                                                        OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                                distributor_InfoRepository.Update(keyValues1, wheres1);
                                            }
                                            else
                                            {
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            break;
                                        }

                                        PId = uppmodel.SuperiorId ?? 0;
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "FXAutoUpgradeUserDistributorGrade自动升级失败，BuyUserId：" + BuyUserId);
                return false;
            }
        }
        #endregion
    }
}
