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;

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

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


        private readonly MiniProgramMsgModule appletWeChatModule = new MiniProgramMsgModule();

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

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

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

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

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

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

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

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



                //发送订阅消息

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

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

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

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


                //判断返佣的过期时间
                if (distributorModel.VipExpiryDate.HasValue)
                {
                    if (distributorModel.VipExpiryDate.Value > System.DateTime.Now)
                    {
                        int year = model.ExpiryDate.Value.Year - model.CreateDate.Year;
                        distributorModel.VipExpiryDate = distributorModel.VipExpiryDate.Value.AddYears((year == 0 ? 1 : year));
                    }
                    else
                    {
                        distributorModel.VipExpiryDate = model.ExpiryDate;
                    }
                }
                else
                {
                    distributorModel.VipExpiryDate = model.ExpiryDate;
                }

                //2020-07-20 Add By:W 
                Dictionary<string, object> keyValuesDistributor = new Dictionary<string, object>() {
                                        { nameof(RB_Distributor_Info.VipExpiryDate),distributorModel.VipExpiryDate}
                                    };
                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) { 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) { return false; }
                    var PTModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
                    if (PTModel == null) { 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)
                        {
                            return false;
                        }
                        //求其上级
                        var pmodel = member_UserRepository.GetEntity(uModel.SuperiorId);
                        if (pmodel == null) { 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) { return false; }
                            if (pfxModel.Grade < VipModel.Grade)
                            {
                                return false;//其上级不是vip   直接后面的全部不提
                            }
                            //查询出当前用户的所有上级
                            string UserIds = member_UserRepository.GetMemberParentIdStr(pmodel.Id);
                            var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = UserIds, TenantId = TenantId, MallBaseId = MallBaseId });
                            //查询出用户的所有分销信息
                            var dlist = distributor_InfoRepository.GetListForSingle(new RB_Distributor_Info_Extend() { UserIds = UserIds, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited, TenantId = TenantId, MallBaseId = MallBaseId });
                            foreach (var item in dlist)
                            {
                                item.Grade = FXList.Where(x => x.Id == item.FXGradeId).FirstOrDefault()?.Grade ?? 0;
                            }

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

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

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

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

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

                                    }
                                }
                            }

                            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");
                return false;
            }
        }
    }
}
