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;
using VT.FW.DB;
using Mall.Repository.GuideCar;
using Mall.Common.Enum;
using Mall.ThirdCore.Message;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Coffee;
using Mall.Common.Enum.User;
using Mall.Repository.Education;

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_OrderCommissionRepository goods_OrderCommissionRepository = new RB_Goods_OrderCommissionRepository();
        /// <summary>
        /// 订单商品信息
        /// </summary>
        private readonly RB_Goods_OrderDetailRepository goodsOrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 售后订单列表
        /// </summary>
        private readonly RB_Goods_OrderAfterSaleRepository goods_OrderAfterSaleRepository = new RB_Goods_OrderAfterSaleRepository();
        /// <summary>
        /// 会员信息
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 用户积分
        /// </summary>
        private readonly RB_Member_IntegralRepository member_IntegralRepository = new RB_Member_IntegralRepository();
        /// <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();
        /// <summary>
        /// 司导-基础
        /// </summary>
        private readonly RB_GuideCar_BaseRepository guideCar_BaseRepository = new RB_GuideCar_BaseRepository();
        /// <summary>
        /// 司导-导游
        /// </summary>
        private readonly RB_GuideCar_GuideRepository guideCar_GuideRepository = new RB_GuideCar_GuideRepository();
        /// <summary>
        /// 司导-车辆
        /// </summary>
        private readonly RB_GuideCar_CarRepository guideCar_CarRepository = new RB_GuideCar_CarRepository();
        /// <summary>
        /// 小程序基础
        /// </summary>
        private readonly RB_MallBaseRepository mallBaseRepository = new RB_MallBaseRepository();
        /// <summary>
        /// 推荐供应商返佣
        /// </summary>
        private readonly RB_Goods_OrderIntroductionRepository goods_OrderIntroductionRepository = new RB_Goods_OrderIntroductionRepository();
        /// <summary>
        /// 微店
        /// </summary>
        private readonly RB_SmallShops_InfoRepository smallShops_InfoRepository = new RB_SmallShops_InfoRepository();
        /// <summary>
        /// 微店佣金
        /// </summary>
        private readonly RB_SmallShops_CommissionRepository smallShops_CommissionRepository = new RB_SmallShops_CommissionRepository();

        private readonly MiniProgramMsgModule appletWeChatModule = new MiniProgramMsgModule();

        private readonly RB_WeChatPublicAccountModule weChatPublicAccountModule = new RB_WeChatPublicAccountModule();

        /// <summary>
        /// vip购买仓储层
        /// </summary>
        private readonly RB_Vip_BuyRepository vipBuyRepository = new RB_Vip_BuyRepository();
        /// <summary>
        ///  不可开发票商品信息记录表  
        ///</summary>
        private readonly RB_Invoice_RecordDetailRepository invoiceRecordDetailRepository = new RB_Invoice_RecordDetailRepository();
        /// <summary>
        /// 会员购买仓储层
        /// </summary>
        private readonly RB_Member_BuyRepository memberBuyRepository = new RB_Member_BuyRepository();
        /// <summary>
        /// 管理通知
        /// </summary>
        private readonly RB_Message_NoticeRepository message_NoticeRepository = new RB_Message_NoticeRepository();
        /// <summary>
        /// 咖啡劵
        /// </summary>
        private readonly RB_Member_CoffeeCouponsRepository member_CoffeeCouponsRepository = new RB_Member_CoffeeCouponsRepository();
        /// <summary>
        /// 咖啡劵消费记录
        /// </summary>
        private readonly RB_Member_CoffeeLogRepository member_CoffeeLogRepository = new RB_Member_CoffeeLogRepository();
        /// <summary>
        /// 教育商品订单
        /// </summary>
        private readonly RB_EduGoods_OrderRepository eduGoods_OrderRepository = new RB_EduGoods_OrderRepository();
        /// <summary>
        /// 教育商品订单明细
        /// </summary>
        private readonly RB_EduGoods_OrderDetailRepository eduGoods_OrderDetailRepository = new RB_EduGoods_OrderDetailRepository();
        /// <summary>
        /// 教育商品
        /// </summary>
        private readonly RB_EduGoodsRepository eduGoodsRepository = new RB_EduGoodsRepository();
        /// <summary>
        /// 用户关联
        /// </summary>
        private readonly RB_Education_EduSellRepository education_EduSellRepository = new RB_Education_EduSellRepository();
        /// <summary>
        /// 财务单据配置
        /// </summary>
        private readonly RB_Finance_ConfigRepository finance_ConfigRepository = new RB_Finance_ConfigRepository();
        /// <summary>
        /// 资产出库申请
        /// </summary>
        private readonly Mall.Repository.Property.RB_Supplies_StockOutApplyForRepository supplies_StockOutApplyForRepository = new Mall.Repository.Property.RB_Supplies_StockOutApplyForRepository();
        /// <summary>
        /// 出库申请明细
        /// </summary>
        private readonly Mall.Repository.Property.RB_Supplies_StockOutApplyForDetailRepository supplies_StockOutApplyForDetailRepository = new Mall.Repository.Property.RB_Supplies_StockOutApplyForDetailRepository();
        /// <summary>
        /// 教育创建人
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();



        /// <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,
                    IsEnableNoSuperiorFY = 1
                }) > 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,
                    DetailRecommendSame = 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)
            {
                var guidebaseModel = guideCar_BaseRepository.GetList(new Model.Extend.GuideCar.RB_GuideCar_Base_Extend() { TenantId = oldOrder.TenantId, MallBaseId = oldOrder.MallBaseId }).FirstOrDefault();
                //更新订单信息
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { 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}
                };
                if (guidebaseModel != null && guidebaseModel.IsConfirm == 2 && oldOrder.OrderClassify == 1)
                {
                    keyValues.Add(nameof(RB_Goods_Order_Extend.OrderStatus), Common.Enum.Goods.OrderStatusEnum.WaitReceiving);
                    keyValues.Add(nameof(RB_Goods_Order_Extend.DeliveryTime), DateTime.Now);
                }
                else if (oldOrder.OrderClassify == 2 || oldOrder.VersionSource == 1 || oldOrder.OrderEduType == 1)
                {
                    //if (oldOrder.OrderEduType == 2)
                    //教育订单  下单后  直接完成   无法取消订单   无法申请售后
                    keyValues.Add(nameof(RB_Goods_Order_Extend.OrderStatus), Common.Enum.Goods.OrderStatusEnum.Completed);
                    keyValues.Add(nameof(RB_Goods_Order_Extend.DeliveryTime), DateTime.Now);
                    keyValues.Add(nameof(RB_Goods_Order_Extend.ReceivingTime), DateTime.Now);
                    keyValues.Add(nameof(RB_Goods_Order_Extend.FinishTime), DateTime.Now);
                }
                else if (oldOrder.OrderClassify == 3)
                {
                    keyValues.Add(nameof(RB_Goods_Order_Extend.OrderStatus), Common.Enum.Goods.OrderStatusEnum.WaitReceiving);
                    keyValues.Add(nameof(RB_Goods_Order_Extend.DeliveryTime), DateTime.Now);
                }
                else if (oldOrder.OrderEduType == 2) {
                    if (oldOrder.DeliveryMethod == Common.Enum.Goods.OrderDeliveryMethodEnum.ExpressDistribution)
                    {
                        keyValues.Add(nameof(RB_Goods_Order_Extend.OrderStatus), Common.Enum.Goods.OrderStatusEnum.WaitSendGoods);
                    }
                    else if (oldOrder.DeliveryMethod == Common.Enum.Goods.OrderDeliveryMethodEnum.VerificationShop)
                    {
                        keyValues.Add(nameof(RB_Goods_Order_Extend.OrderStatus), Common.Enum.Goods.OrderStatusEnum.WaitReceiving);
                        keyValues.Add(nameof(RB_Goods_Order_Extend.DeliveryTime), DateTime.Now);
                    }
                }
                else
                {
                    keyValues.Add(nameof(RB_Goods_Order_Extend.OrderStatus), Common.Enum.Goods.OrderStatusEnum.WaitSendGoods);
                    //2020-11-10 Add By:W  start
                    try
                    {
                        if (orderGoodsList != null && orderGoodsList.Any(x => x.IsNoTax == 1))//有不可以开发票的商品 新增记录更新缓存
                        {
                            decimal totalPrice = orderGoodsList.Where(x => x.IsNoTax == 1).Sum(x => (x.Final_Price ?? 0) + (x.FreightMoney ?? 0));
                            if (totalPrice > 0)
                            {
                                foreach (var item in orderGoodsList.Where(x => x.IsNoTax == 1))
                                {
                                    invoiceRecordDetailRepository.Insert(new Model.Entity.Product.RB_Invoice_RecordDetail
                                    {
                                        TenantId = item.TenantId,
                                        MallBaseId = item.MallBaseId,
                                        ID = 0,
                                        Type = 1,
                                        CreateDate = DateTime.Now,
                                        Name = item.GoodsName,
                                        OrderId = item.OrderId ?? 0,
                                        OrderDetailId = item.Id,
                                        GoodsPrice = item.Final_Price ?? 0,
                                        Unit_Price = item.Unit_Price,
                                        Number = item.Number,
                                        FreightMoney = item.FreightMoney ?? 0
                                    });
                                }
                                //获取缓存信息
                                TransactionPriceInfo transactionPriceInfo = CacheManager.User.UserReidsCache.GetTransactionPriceInfo(oldOrder.MallBaseId);
                                if (transactionPriceInfo == null)
                                {
                                    transactionPriceInfo = new TransactionPriceInfo
                                    {
                                        TenantId = oldOrder.TenantId,
                                        MallBaseId = oldOrder.MallBaseId,
                                        TotalPrice = totalPrice
                                    };
                                }
                                else
                                {
                                    transactionPriceInfo.TotalPrice += totalPrice;
                                }
                                CacheManager.User.UserReidsCache.TransactionPriceSet(CacheKey.UserModuleCacheKeyConfig.Transaction_Price_ + oldOrder.MallBaseId, transactionPriceInfo, Config.JwtExpirTime);
                            };
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteInfo("不开发票商品记录或者缓存失败:" + ex.ToString());
                    }
                    //2020-11-10 Add By:W End
                }
                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);
                }

                #region 注释发放优惠券
                ////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;
                //            }
                //        }
                //    }
                //}
                #endregion

                //赠送粉象等级(+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, oldOrder.UserId ?? 0, oldOrder.OrderId));

                if (oldOrder.OrderClassify == 2)
                {
                    //教育订单付款后订单状态为已完成  直接返佣
                    InsertOrderCommissionCompleted(oldOrder.RefMapperTo<RB_Goods_Order_Extend>());
                }
                if (oldOrder.VersionSource == 1 && orderGoodsList != null && orderGoodsList.Any(x => x.ClassId > 0))//教育订单并且订单商品是教育erp同步过来的
                {
                    System.Threading.Tasks.Task.Run(() => Synchro(orderGoodsList, oldOrder));

                }

                #region 咖啡劵
                if (oldOrder.OrderEduType == 1 || oldOrder.OrderEduType == 2) {
                    try
                    {
                        if (oldOrder.OrderEduType == 1)
                        {
                            //获取我的咖啡劵信息
                            int BuyNum = orderGoodsList.Sum(x => (x.Number ?? 0) + x.PresentCoffeeNum);
                            var ccmodel = member_CoffeeCouponsRepository.GetList(new Model.Extend.Coffee.RB_Member_CoffeeCoupons_Extend() { MallBaseId = oldOrder.MallBaseId, UserId = oldOrder.UserId ?? 0 }).FirstOrDefault();
                            if (ccmodel == null)
                            {
                                member_CoffeeCouponsRepository.Insert(new Model.Entity.Coffee.RB_Member_CoffeeCoupons()
                                {
                                    Id = 0,
                                    CreateDate = DateTime.Now,
                                    FreeNum = 0,
                                    MallBaseId = oldOrder.MallBaseId,
                                    SurplusBugNum = BuyNum,
                                    TotalBuyNum = BuyNum,
                                    UpdateDate = DateTime.Now,
                                    UserId = oldOrder.UserId ?? 0
                                });
                            }
                            else
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(Model.Extend.Coffee.RB_Member_CoffeeCoupons_Extend.TotalBuyNum), ccmodel.TotalBuyNum + BuyNum },
                                { nameof(Model.Extend.Coffee.RB_Member_CoffeeCoupons_Extend.SurplusBugNum), ccmodel.SurplusBugNum + BuyNum },
                                { nameof(Model.Extend.Coffee.RB_Member_CoffeeCoupons_Extend.UpdateDate), DateTime.Now},
                            };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName = nameof(Model.Extend.Coffee.RB_Member_CoffeeCoupons_Extend.Id),
                                      FiledValue = ccmodel.Id,
                                       OperatorEnum =OperatorEnum.Equal
                                }
                            };
                                member_CoffeeCouponsRepository.Update(keyValues1, wheres1);
                            }
                            foreach (var qitem in orderGoodsList)
                            {
                                //开始插入 咖啡劵
                                member_CoffeeLogRepository.Insert(new Model.Entity.Coffee.RB_Member_CoffeeLog()
                                {
                                    Id = 0,
                                    BuyType = 0,
                                    Code = "",
                                    CreateBy = 0,
                                    CreateDate = DateTime.Now,
                                    MallBaseId = oldOrder.MallBaseId,
                                    Number = (qitem.Number ?? 0) + qitem.PresentCoffeeNum,
                                    OrderId = oldOrder.OrderId,
                                    Remark = "购买" + qitem.GoodsName + qitem.Number + "杯+赠送" + qitem.PresentCoffeeNum + "杯",
                                    Type = 1,
                                    UserId = oldOrder.UserId ?? 0
                                });
                            }
                        }
                        
                        //开始 异步 同步咖啡劵订单至教育erp  并生成财务单据
                        System.Threading.Tasks.Task.Run(() =>
                        {
                            try
                            {
                                EduGoodsOrderInsert(Out_Trade_No, Transaction_Id, Time_End, umodel, oldOrder, orderGoodsList);
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Write(ex, "InsertOrderPayInfo_TBcoffeegoods2");
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Write(ex, "InsertOrderPayInfo_TBcoffeegoods");
                    }
                }
                #endregion

                //发送订阅消息
                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);
                    }
                }
                try
                {
                    if (oldOrder.TenantId == 16 && oldOrder.MallBaseId == 6)
                    {
                        weChatPublicAccountModule.SendOrderSucceedMsg(oldOrder.TenantId, oldOrder.MallBaseId, oldOrder.OrderNo, oldOrder.CreateDate.Value.ToString("MM月dd日 HH时mm分"), umodel.Name, goodsName);
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, "InsertOrderPayInfo");
                }
                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);

                if (guidebaseModel != null && guidebaseModel.IsConfirm == 2 && oldOrder.OrderClassify == 1)
                {
                    //发送短信通知导游接单
                    int IsNormalServer = Convert.ToInt32(Config.IsNormalServer);//为正式才发送短信
                    if (IsNormalServer == 1 && (guidebaseModel?.IsConfirm ?? 0) == 2)
                    {
                        foreach (var item in orderGoodsList)
                        {
                            if (item.GuideId > 0)
                            {
                                //查询导游信息
                                var guideModel = guideCar_GuideRepository.GetEntity(item.GuideId ?? 0);
                                var carModel = guideCar_CarRepository.GetEntity(item.CarId ?? 0);
                                if (guideModel != null && carModel != null && !string.IsNullOrEmpty(guideModel.Telephone))
                                {
                                    string Telephone = guideModel.Telephone;
                                    MobileCodeTypeEnum mobileCodeType = MobileCodeTypeEnum.GuideMsg;//导游通知
                                    if (ValidateHepler.IsMobileNumber(Telephone))
                                    {
                                        object PhoneMessage = new
                                        {
                                            oldOrder.OrderNo,
                                            Name = oldOrder.Consignee,
                                            oldOrder.Mobile,
                                            TripDate = item.TripSTime.Value.ToString("yyyy-MM-dd HH:mm") + " " + ((item.UseDay ?? 0) == Convert.ToDecimal(0.5) ? "半" : Convert.ToInt32(item.UseDay ?? 0).ToString()) + "日",
                                            Address = oldOrder.ShoppingAddress,
                                            item.Number
                                        };
                                        SMSService.SendMsg(Telephone, PhoneMessage, EnumHelper.GetEnumName(mobileCodeType));
                                    }

                                    #region 给客人通知
                                    try
                                    {
                                        if (ValidateHepler.IsMobileNumber(oldOrder.Mobile))
                                        {
                                            MobileCodeTypeEnum mobileCodeType1 = MobileCodeTypeEnum.SDClientMsg;//客人通知
                                            object PhoneMessage = new
                                            {
                                                oldOrder.OrderNo,
                                                TripTime = item.TripSTime.Value.ToString("yyyy-MM-dd HH:mm") + " " + ((item.UseDay ?? 0) == Convert.ToDecimal(0.5) ? "半" : Convert.ToInt32(item.UseDay ?? 0).ToString()) + "日",
                                                guideModel.Name,
                                                Tel = Telephone
                                            };
                                            SMSService.SendMsg(oldOrder.Mobile, PhoneMessage, EnumHelper.GetEnumName(mobileCodeType1));
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                }

                #region 管理端通知
                message_NoticeRepository.Insert(new RB_Message_Notice()
                {
                    Id = 0,
                    CreateDate = DateTime.Now,
                    IsLook = 2,
                    MallBaseId = umodel.MallBaseId,
                    OrderNo = oldOrder.OrderNo,
                    SourceId = oldOrder.OrderId,
                    TenantId = umodel.TenantId,
                    Type = 1,
                    UserId = umodel.Id
                });
                #endregion
            }
            return flag;
        }

        /// <summary>
        /// 插入教育商品 + 生成财务单据
        /// </summary>
        /// <param name="Out_Trade_No"></param>
        /// <param name="Transaction_Id"></param>
        /// <param name="Time_End"></param>
        /// <param name="umodel"></param>
        /// <param name="oldOrder"></param>
        /// <param name="orderGoodsList"></param>
        private void EduGoodsOrderInsert(string Out_Trade_No, string Transaction_Id, DateTime Time_End, RB_Member_User umodel, Model.Entity.Product.RB_Goods_Order oldOrder, List<RB_Goods_OrderDetail_Extend> orderGoodsList)
        {            
            //获取用户关联信息
            var glModel = education_EduSellRepository.GetEducationStuList(new Model.Extend.Education.RB_Education_EduSell_Extend() { MallBaseId = oldOrder.MallBaseId, UserId = oldOrder.UserId ?? 0 }, true).FirstOrDefault();
            int eduOrderId = eduGoods_OrderRepository.Insert(new Model.Entity.Coffee.RB_Goods_Order()
            {
                OrderId = 0,
                OrderType = oldOrder.OrderEduType,
                MallOrderId = oldOrder.OrderId,
                OrderNo = oldOrder.OrderNo,
                UserType = glModel == null ? 3 : glModel.Type,
                AccountId = glModel?.EduSellId ?? 0,
                UserId = oldOrder.UserId ?? 0,
                UserName = umodel.Name,
                OrderSource = (int)(oldOrder.OrderSource ?? UserSourceEnum.WeiXin),
                PaymentWay = (int)(oldOrder.PaymentWay ?? Mall.Common.Enum.Goods.OrderPaymentTypeEnum.OnlinePayment),
                PreferPrice = oldOrder.Income ?? 0,
                Income = (decimal)oldOrder.Income,
                Fee = orderGoodsList.Sum(x => x.ServiceCharge),
                Remark = "",
                OrderStatus = 2,
                PaymentTime = DateTime.Now,
                CancelTime = null,
                CostMoney = 0,//暂时=0  出库后回调更新此金额  此大于0的话  无法取消订单了
                Status = 0,
                Group_Id = 100000,
                MallBaseId = oldOrder.MallBaseId,
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now
            });
            if (eduOrderId > 0)
            {
                string mgoodsIds = string.Join(",", orderGoodsList.Select(x => x.GoodsId).Distinct());
                var eduGoodsList = eduGoodsRepository.GetList(new Model.Extend.Education.RB_Goods_ViewModel() { MallBaseId = oldOrder.MallBaseId, MallGoodsIds = mgoodsIds });
                foreach (var detailModel in orderGoodsList)
                {
                    var eduGoodsModel = eduGoodsList.Where(x => x.Id == detailModel.GoodsId).FirstOrDefault();
                    eduGoods_OrderDetailRepository.Insert(new Model.Entity.Coffee.RB_Goods_OrderDetail()
                    {
                        Id = 0,
                        OrderId = eduOrderId,
                        MallOrderId = oldOrder.OrderId,
                        MallOrderDetailId = detailModel.Id,
                        GoodsId = eduGoodsModel?.Id ?? 0,
                        MallGoodsId = detailModel.GoodsId ?? 0,
                        GoodsName = detailModel.GoodsName,
                        CoverImage = detailModel.CoverImage,
                        Unit_Price = detailModel.Unit_Price ?? 0,
                        PreferPrice = detailModel.Final_Price ?? 0,
                        Number = detailModel.Number ?? 0,
                        Income = detailModel.Final_Price ?? 0,
                        Fee = detailModel.ServiceCharge,
                        CostMoney = detailModel.CostMoney ?? 0,
                        Status = 0,
                        Group_Id = 100000,
                        MallBaseId = oldOrder.MallBaseId,
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now,
                        MaterialId = detailModel.MaterialId,
                        FreightMoney = detailModel.FreightMoney ?? 0
                    });
                }
            }

            #region 推送企业微信
            if (oldOrder.OrderEduType == 2)
            {
                string GoodsName = orderGoodsList.FirstOrDefault()?.GoodsName ?? "";
                if (orderGoodsList.Count() > 1)
                {
                    GoodsName += "等" + orderGoodsList.Count() + "件商品";
                }
                var pushMessage = new
                {
                    Msg = new
                    {
                        GoodsName,
                        OrderNo = oldOrder.OrderNo + "(" + oldOrder.OrderId + ")",
                        Money = oldOrder.Income,
                        OrderTime = Time_End.ToString("yyyy-MM-dd HH:mm"),
                        GroupId = 100000
                    }
                };
                try
                {
                    string apiResult1 = HttpHelper.HttpPost(Config.ReadConfigKey("EduPushOrderProperty"), JsonHelper.Serialize(pushMessage), "");
                    LogHelper.WriteInfo("推送企业微信结果：" + apiResult1);
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "EduPushOrderProperty");
                }
            }
            #endregion

            #region 财务配置
            Model.Entity.Education.RB_Finance_Config financeConfig = null;
            if (oldOrder.OrderEduType == 1)
            {
                financeConfig = finance_ConfigRepository.GetList(new Model.Entity.Education.RB_Finance_Config { Group_Id = 100000, Type = Common.Enum.Education.FinanceConfigTypeEnum.EduCoffee }).FirstOrDefault();
            }
            else if (oldOrder.OrderEduType == 2)
            {
                financeConfig = finance_ConfigRepository.GetList(new Model.Entity.Education.RB_Finance_Config { Group_Id = 100000, Type = Common.Enum.Education.FinanceConfigTypeEnum.EduProperty }).FirstOrDefault();
            }
            if (financeConfig == null)
            {
                LogHelper.WriteInfo("活动财务配置不存在");
                return;
            }
            int CreateBy = financeConfig.CreateBy;// 看学生  甲鹤用户  谁是制单人 （全都使用配置的）
            string DeptName = accountRepository.GetDeptmentName(financeConfig.UpdateBy);// updateBy 存部门
            var userInfo = accountRepository.GetEmployeeListRepository(new Model.Extend.Education.Employee_ViewModel { Id = CreateBy, Group_Id = financeConfig.Group_Id }).ToList().FirstOrDefault();
            #endregion

            #region 出库申请
            string Remark = "甲鹤用户：" + umodel.Name;
            if (glModel != null)
            {
                if (glModel.Type == 1)
                {
                    var uInfo = accountRepository.GetEmployeeListRepository(new Model.Extend.Education.Employee_ViewModel { Id = glModel.EduSellId, Group_Id = financeConfig.Group_Id }).FirstOrDefault();
                    Remark = "甲鹤内部：" + (uInfo?.EmployeeName ?? "");
                }
                else if (glModel.Type == 2)
                {
                    //查询一下学生名称
                    var stuMdoel = accountRepository.GetStudentExt(new Model.Extend.Education.RB_Account_ViewModel() { Group_Id = financeConfig.Group_Id, Id = glModel.EduSellId, AccountType = 4 }).FirstOrDefault();
                    Remark = "甲鹤学生：" + stuMdoel.AccountName;
                }
            }
            if (oldOrder.OrderEduType == 2)
            {
                //创建资产出库申请单
                int applyId = supplies_StockOutApplyForRepository.Insert(new Model.Entity.Property.RB_Supplies_StockOutApplyFor()
                {
                    Id = 0,
                    TotalNumber = orderGoodsList.Sum(x => x.Number ?? 0),
                    Remark = "甲鹤小程序（" + Remark + "），相关订单号：" + oldOrder.OrderNo + "(" + oldOrder.OrderId + ")",
                    Status = 0,
                    RB_Branch_Id = userInfo.School_Id,
                    RB_Group_Id = userInfo.Group_Id,
                    CreateBy = financeConfig.CreateBy,
                    CreateDate = DateTime.Now,
                    UpdateBy = financeConfig.CreateBy,
                    UpdateDate = DateTime.Now,
                    FinanceIds = "[]",
                    StockOutStatus = 1,
                    AuditStatus = 1,
                    AuditRemark = "",
                    AuditEmpId = 0,
                    Type = 2,
                    MallOrderId = oldOrder.OrderId,
                    MallRelevance = JsonHelper.Serialize(orderGoodsList.Select(x => new
                    {
                        ECOrderId = x.OrderId,
                        ECOrderDetailId = x.Id
                    }))
                });
                if (applyId > 0) {
                    //插入明细
                    foreach (var item in orderGoodsList)
                    {
                        supplies_StockOutApplyForDetailRepository.Insert(new Model.Entity.Property.RB_Supplies_StockOutApplyForDetail()
                        {
                            Id = 0,
                            ApplyForId = applyId,
                            ClassId = 0,
                            ClassName = "",
                            CourseName = "",
                            CreateBy = financeConfig.CreateBy,
                            CreateDate = DateTime.Now,
                            Number = item.Number??0,
                            RB_Branch_Id = userInfo.School_Id,
                            RB_Group_Id = userInfo.Group_Id,
                            Status = 0,
                            StockOutNum = 0,
                            SuppliesId = item.MaterialId,
                            UpdateBy = financeConfig.CreateBy,
                            UpdateDate = DateTime.Now,
                            SchoolId = userInfo.School_Id,
                            SchoolName = userInfo.SchoolName
                        });
                    }
                }
            }
            #endregion

            #region 开始创建收款单据
            #region 财务单据数据组装
            List<object> ECList = new List<object>();
            var detailList = new List<object>();
            foreach (var item in orderGoodsList) {
                detailList.Add(new
                {
                    CostTypeId = financeConfig?.CostTypeId ?? 0,
                    Number = 1,
                    OriginalMoney = Convert.ToDecimal(item.Final_Price ?? 0),
                    UnitPrice = Convert.ToDecimal(item.Final_Price ?? 0),
                    Remark = item.GoodsName + " ，数量：" + (item.Number ?? 0) + "，订单号：" + Out_Trade_No
                });
                if (item.FreightMoney > 0) {
                    detailList.Add(new
                    {
                        CostTypeId = financeConfig?.School_Id ?? 0,//暂存 运费ID
                        Number = 1,
                        OriginalMoney = Convert.ToDecimal(item.FreightMoney ?? 0),
                        UnitPrice = Convert.ToDecimal(item.FreightMoney ?? 0),
                        Remark = item.GoodsName + " ，数量：" + (item.Number ?? 0) + "，订单号：" + Out_Trade_No
                    });
                }
                ECList.Add(new
                {
                    ECOrderId = item.OrderId,
                    ECOrderDetailId = item.Id
                });
            }

            var financeObj = new
            {
                IsPublic = 1,
                BType = 1,
                AccountId = financeConfig?.ClientID ?? 0,
                WBMoney = Convert.ToDecimal(oldOrder.Income ?? 0) -(orderGoodsList.Sum(x=>x.ServiceCharge)),
                TradeDate = Time_End,
                AccountNumber = Transaction_Id,
                TemplateId = financeConfig?.TempleteId ?? 0,
                OrderSource = 17,
                Remark = Remark + "下单，" + DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                detailList,
                OriginalFee = (orderGoodsList.Sum(x => x.ServiceCharge)),
                CreateBy = userInfo.Id,
                RemitterName = umodel.Name,
                RB_Branch_Id = userInfo.School_Id,
                RB_Group_Id = userInfo.Group_Id,
                RB_Depart_Id = financeConfig.UpdateBy,
                RB_CreateByName = userInfo.EmployeeName,
                RB_DepartName = DeptName,
                RB_BranchName = userInfo.SchoolName,
                RB_GroupName = userInfo.GroupName,
                FinanceType = 2,
                OtherType = 54,
                ReFinanceId = eduOrderId,
                ReFinanceId2 = oldOrder.OrderId,
                ECOrderList = ECList
            };
            #endregion

            string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
            var resultInfo = new
            {
                msg = sign,
            };
            string apiResult = Common.Plugin.HttpHelper.HttpPost(Config.ReadConfigKey("IncomeFinanceApi"), JsonHelper.Serialize(resultInfo), "");
            LogHelper.WriteInfo("咖啡劵/资产收入财务单据结果：" + apiResult);
            #endregion
        }

        /// <summary>
        /// 订单完成 返佣
        /// </summary>
        /// <returns></returns>
        public bool InsertOrderCommissionCompleted(RB_Goods_Order_Extend orderModel)
        {
            int mallBaseId = orderModel.MallBaseId;
            int tenantId = orderModel.TenantId;
            bool IsUpdateCommission = true;
            var mallModel = mallBaseRepository.GetEntity(mallBaseId);
            if (mallModel != null && mallModel.AfterTime > 0)
            {
                var OrderM = goods_OrderRepository.GetEntity(orderModel.OrderId);
                if (OrderM != null && OrderM.ReceivingTime.HasValue && OrderM.ReceivingTime.Value.AddDays(mallModel.AfterTime) > DateTime.Now)
                {
                    IsUpdateCommission = false;
                }
            }
            if (IsUpdateCommission)
            {
                //更新返佣为已返佣
                var ocList = goods_OrderCommissionRepository.GetList(new RB_Goods_OrderCommission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                if (ocList.Where(x => x.CommissionState == 1).Any())
                {
                    foreach (var item in ocList.Where(x => x.CommissionState == 1))
                    {
                        //查询是否有申请退款
                        var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                        if (!afterSaleList.Any())
                        {
                            //获取分销商信息
                            var disInfo = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = item.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                            if (disInfo != null && disInfo.AuditStatus == DistributorAuditStatusEnum.Audited)
                            {
                                //更新分销商佣金
                                Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_Distributor_Info_Extend.TotalCommission),(disInfo.TotalCommission??0)+(item.Commission??0)},
                                        { nameof(RB_Distributor_Info_Extend.CommissionWithdrawal),(disInfo.CommissionWithdrawal??0)+(item.Commission??0)},
                                    };
                                List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                              FiledValue=disInfo.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                bool flag1 = distributor_InfoRepository.Update(keyValues2, wheres2);
                                if (flag1)
                                {
                                    //更新返佣状态
                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_OrderCommission_Extend.CommissionState),2},
                                            { nameof(RB_Goods_OrderCommission_Extend.UpdateDate),DateTime.Now},
                                        };
                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_Goods_OrderCommission_Extend.Id),
                                                  FiledValue=item.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                    goods_OrderCommissionRepository.Update(keyValues1, wheres1);
                                }
                            }
                        }
                    }
                }
                //更新推荐供应商返佣
                var oiList = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                if (oiList.Any())
                {
                    foreach (var item in oiList)
                    {
                        //查询是否有申请退款
                        var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                        if (!afterSaleList.Any())
                        {
                            //更新返佣状态
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_OrderIntroduction_Extend.CommissionState),2},
                                        { nameof(RB_Goods_OrderIntroduction_Extend.UpdateDate),DateTime.Now},
                                    };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                                FiledName=nameof(RB_Goods_OrderIntroduction_Extend.Id),
                                                FiledValue=item.Id,
                                                OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                            goods_OrderIntroductionRepository.Update(keyValues1, wheres1);
                        }
                    }
                }

                //更新微店返佣
                var ssList = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                if (ssList.Where(x => x.CommissionState == 1).Any())
                {
                    var ssmodel = ssList.FirstOrDefault();
                    //获取微店信息
                    var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = ssmodel.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                    foreach (var item in ssList.Where(x => x.CommissionState == 1))
                    {
                        //查询是否有申请退款
                        var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                        if (!afterSaleList.Any())
                        {
                            if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                            {
                                //更新微店佣金
                                Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0)+(item.Commission??0)},
                                        { nameof(RB_SmallShops_Info_Extend.Commission),(smallModel.Commission??0)+(item.Commission??0)},
                                    };
                                List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                                FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                FiledValue=smallModel.Id,
                                                OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                if (flag1)
                                {
                                    //更新返佣状态
                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                            { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                        };
                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                    FiledValue=item.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                    smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                }
                            }
                        }
                    }
                }
            }
            //积分赠送
            var dlist = goodsOrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderModel.OrderId, TenantId = tenantId, MallBaseId = mallBaseId });
            if (dlist.Any())
            {
                int IntegralGoodsPresent = 0;
                foreach (var item in dlist)
                {
                    if (item.IntegralGoodsPresent > 0)
                    {
                        IntegralGoodsPresent += (item.IntegralGoodsPresent ?? 0);
                    }
                }
                if (IntegralGoodsPresent > 0)
                {
                    //保存积分赠送
                    var umodel = member_UserRepository.GetEntity(orderModel.UserId);
                    //用户订单数增加
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User_Extend.Integral), (umodel.Integral ?? 0)+IntegralGoodsPresent }
                            };
                    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);
                    member_IntegralRepository.Insert(new Model.Entity.User.RB_Member_Integral()
                    {
                        Id = 0,
                        CreateDate = DateTime.Now,
                        Description = "订单购买赠送积分，订单号：" + orderModel.OrderNo,
                        Image = 0,
                        Integral = IntegralGoodsPresent,
                        MallBaseId = orderModel.MallBaseId,
                        PlatformType = orderModel.OrderSource,
                        Remarks = "",
                        TenantId = orderModel.TenantId,
                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                        UserId = orderModel.UserId,
                        OrderId = orderModel.OrderId
                    });
                }
            }

            return true;
        }

        /// <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, 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, 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.Commit(); return false; }
                var PTModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
                if (PTModel == null) { vipBuyRepository.DBSession.Commit(); 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.Commit(); 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.Commit(); return false; }
                        if (pfxModel.Grade < VipModel.Grade)
                        {
                            if (pmodel.SuperiorId > 0)
                            {
                                while (pmodel.SuperiorId > 0)
                                {
                                    pmodel = member_UserRepository.GetEntity(pmodel.SuperiorId);
                                    if (pmodel == null || (pmodel.SuperiorId ?? 0) == 0) { vipBuyRepository.DBSession.Commit(); return false; }
                                    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) { vipBuyRepository.DBSession.Commit(); return false; }
                                    pfxModel = FXList.Where(x => x.Id == dispModel.FXGradeId).FirstOrDefault();
                                    if (pfxModel == null) { vipBuyRepository.DBSession.Commit(); return false; }
                                    if (pfxModel.Grade < VipModel.Grade)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                vipBuyRepository.DBSession.Commit(); return false;
                            }
                            //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)
                                {
                                    //后面的全部不返佣  2020-08-06  刘东  继续找下级
                                    UserId = numodel.SuperiorId ?? 0;
                                    continue;
                                }
                                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;
                                                numodel = n1umodel;//继续查找下一级  2020-08-06 刘东
                                            }
                                            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 BuyUserId, int OrderId, string Out_Trade_No, 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.Commit(); 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.Commit(); return false; }
                    var PTModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
                    if (PTModel == null) { vipBuyRepository.DBSession.Commit(); 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.Commit();
                            return false;
                        }
                        //求其上级
                        var pmodel = member_UserRepository.GetEntity(uModel.SuperiorId);
                        if (pmodel == null) { vipBuyRepository.DBSession.Commit(); 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.Commit(); return false; }
                            if (pfxModel.Grade < VipModel.Grade)
                            {
                                if (pmodel.SuperiorId > 0)
                                {
                                    while (pmodel.SuperiorId > 0)
                                    {
                                        pmodel = member_UserRepository.GetEntity(pmodel.SuperiorId);
                                        if (pmodel == null || (pmodel.SuperiorId ?? 0) == 0) { vipBuyRepository.DBSession.Commit(); return false; }
                                        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) { vipBuyRepository.DBSession.Commit(); return false; }
                                        pfxModel = FXList.Where(x => x.Id == dispModel.FXGradeId).FirstOrDefault();
                                        if (pfxModel == null) { vipBuyRepository.DBSession.Commit(); return false; }
                                        if (pfxModel.Grade < VipModel.Grade)
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    vipBuyRepository.DBSession.Commit(); return false;
                                }
                                //vipBuyRepository.DBSession.Commit();
                                //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)
                                    {
                                        //后面的全部不返佣  2020-08-06 刘东 后面的人继续找
                                        UserId = numodel.SuperiorId ?? 0;
                                        continue;
                                    }
                                    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;
                                                    numodel = n1umodel;//继续查找下一级  2020-08-06  刘东 
                                                }
                                                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


        #region 普通分销模式会员购买

        /// <summary>
        /// 修改会员购买
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateMemberBuy(int UserId, int OrderId, string Out_Trade_No, string Transaction_Id, Common.Enum.Goods.OrderPayTypeEnum PayWay, decimal Money, DateTime Time_End)
        {
            var umodel = member_UserRepository.GetEntity(UserId);
            if (umodel == null)
            {
                return false;
            }
            //判断订单状态是否是待支付  2020-06-16 Add By:W
            var model = memberBuyRepository.GetEntity(OrderId);
            if (model == null)
            {
                return false;
            }
            if (model.PayState != 0)
            {
                return false;
            }
            if (model.Money != Money)
            {
                return false;
            }

            var trans = memberBuyRepository.DbTransaction;
            bool flag;
            try
            {

                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Member_Buy.PayTime),Time_End},
                     { nameof(RB_Member_Buy.PayState),1},
                       { nameof(RB_Member_Buy.Out_Trade_No),Out_Trade_No},
                         { nameof(RB_Member_Buy.Transaction_Id),Transaction_Id}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper{
                         FiledName=nameof(RB_Member_Buy.Id),
                          FiledValue=OrderId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = memberBuyRepository.Update(keyValues, wheres, trans);//更新会员购买记录

                Dictionary<string, object> keyValuesMember = new Dictionary<string, object>() {
                    { nameof(RB_Member_User.MemberGrade),model.GradeId}
                };
                List<WhereHelper> wheresMember = new List<WhereHelper>() {
                    new WhereHelper{
                         FiledName=nameof(RB_Member_User.Id),
                          FiledValue=model.UserId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = member_UserRepository.Update(keyValuesMember, wheresMember, trans);//更新会员购买记录
                memberBuyRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "UpdateMemberBuy");
                memberBuyRepository.DBSession.Rollback("UpdateMemberBuy");
                return false;
            }
            return flag;
        }
        #endregion



        #region 同步甲鹤小程序订单到教育erp中去
        public void Synchro(List<RB_Goods_OrderDetail_Extend> orderDetailList, Model.Entity.Product.RB_Goods_Order model)
        {
            List<object> classList = new List<object>();
            foreach (var item in orderDetailList.Where(x => x.ClassId > 0))
            {
                classList.Add(new
                {
                    ClassId = item.ClassId,
                    GuestNum = item.Number,
                    Unit_Price = item.Unit_Price,
                    PreferPrice = item.Final_Price,
                    SaleRemark ="学生信息："+ model.Consignee + "," + model.Mobile+ (string.IsNullOrWhiteSpace(model.Remark)?"": "学生备注：" + model.Remark) ,
                    IsLessPrice = (item.CouponMoney ?? 0) > 0 ? 1 : 0,
                    LessPrice = (item.CouponMoney ?? 0),
                    Income = 0,//item.Final_Price - item.ServiceCharge,
                    DiscountMoney = 0,
                    PlatformTax = item.ServiceCharge,
                    EnterID = model.EduUserId > 0 ? model.EduUserId : 1,
                    GuestName = model.Consignee + "," + model.Mobile
                });
            }
            if (classList!=null&& classList.Any())
            {
                var resultInfo = new
                {
                    Msg = new { Order = classList, EnterID = model.EduUserId > 0 ? model.EduUserId : Convert.ToInt32(Config.EduXuZongId??"2602") },
                };
                string apiResult = Common.Plugin.HttpHelper.HttpPost(Config.ReadConfigKey("EduOrderApi"), JsonHelper.Serialize(resultInfo), "");
                Newtonsoft.Json.Linq.JObject parmsJob = Newtonsoft.Json.Linq.JObject.Parse(apiResult);
                string resultCode = parmsJob.GetStringValue("Code");
                if (resultCode == "1")//新增记录
                {

                }
            }
        }
        #endregion
    }
}
