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 Newtonsoft.Json;
using Mall.Repository.BaseSetUp;
using Mall.Common.Enum.User;
using Mall.Common.API;
using Newtonsoft.Json.Linq;
using System.Threading;
using Mall.Repository.Finance;
using NPOI.SS.Formula.Functions;
using VT.FW.DB;

namespace Mall.Module.User
{
    /// <summary>
    /// 商户用户处理层
    /// </summary>
    public class UserModule
    {
        /// <summary>
        /// 用户管理
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 会员等级
        /// </summary>
        private readonly RB_Member_GradeRepository member_GradeRepository = new RB_Member_GradeRepository();
        /// <summary>
        /// 会员权益
        /// </summary>
        private readonly RB_Member_EquityRepository member_EquityRepository = new RB_Member_EquityRepository();
        /// <summary>
        /// 用户积分
        /// </summary>
        private readonly RB_Member_IntegralRepository member_IntegralRepository = new RB_Member_IntegralRepository();
        /// <summary>
        /// 用户余额
        /// </summary>
        private readonly RB_Member_BalanceRepository member_BalanceRepository = new RB_Member_BalanceRepository();
        /// <summary>
        /// 素材
        /// </summary>
        private readonly RB_Material_InfoRepository material_InfoRepository = new RB_Material_InfoRepository();
        /// <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_Distributor_GradeRepository distributor_GradeRepository = new RB_Distributor_GradeRepository();
        /// <summary>
        /// 分销商
        /// </summary>
        private readonly RB_Distributor_InfoRepository distributor_InfoRepository = new RB_Distributor_InfoRepository();
        /// <summary>
        /// 分销提现
        /// </summary>
        private readonly RB_Distributor_RemitRepository distributor_RemitRepository = new RB_Distributor_RemitRepository();
        /// <summary>
        /// 收货地址
        /// </summary>
        private readonly RB_Member_ShippingAddressRepository member_ShippingAddressRepository = new RB_Member_ShippingAddressRepository();
        /// <summary>
        /// 区域
        /// </summary>
        private readonly Rb_destinationRepository destinationRepository = new Rb_destinationRepository();
        /// <summary>
        /// 商品
        /// </summary>
        private readonly RB_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 收藏表
        /// </summary>
        private readonly RB_Member_CollectionRepository member_CollectionRepository = new RB_Member_CollectionRepository();
        /// <summary>
        /// 订单返佣
        /// </summary>
        private readonly RB_Goods_OrderCommissionRepository goods_OrderCommissionRepository = new RB_Goods_OrderCommissionRepository();

        private readonly RB_SmallShops_RemitRepository smallShopsRemitRepository = new RB_SmallShops_RemitRepository();
        private readonly RB_SmallShops_CommissionRepository smallShopsCommissionRepository = new RB_SmallShops_CommissionRepository();
        /// <summary>
        /// 订单
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 订单明细
        /// </summary>
        private readonly RB_Goods_OrderDetailRepository goods_OrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 足迹
        /// </summary>
        private readonly RB_Member_FootmarkRepository member_FootmarkRepository = new RB_Member_FootmarkRepository();
        /// <summary>
        /// 小程序
        /// </summary>
        private readonly RB_MiniProgramRepository miniProgramRepository = new RB_MiniProgramRepository();
        /// <summary>
        /// 和平等级
        /// </summary>
        private readonly RB_Distributor_HPGradeInfoRepository distributor_HPGradeInfoRepository = new RB_Distributor_HPGradeInfoRepository();
        /// <summary>
        /// 和平返佣
        /// </summary>
        private readonly RB_Distributor_HPCommissionRepository distributor_HPCommissionRepository = new RB_Distributor_HPCommissionRepository();
        /// <summary>
        /// 和平返佣分类
        /// </summary>
        private readonly RB_Distributor_HPCategoryRepository distributor_HPCategoryRepository = new RB_Distributor_HPCategoryRepository();
        /// <summary>
        /// 和平返佣比例
        /// </summary>
        private readonly RB_Distributor_HPGradeRatioRepository distributor_HPGradeRatioRepository = new RB_Distributor_HPGradeRatioRepository();
        /// <summary>
        /// 财务单据规则
        /// </summary>
        private static readonly RB_Finance_ConfigurineRepository financeConfigurineRepository = new RB_Finance_ConfigurineRepository();
        /// <summary>
        /// 用户优惠券
        /// </summary>
        private readonly RB_Member_CouponRepository memberCouponRepository = new RB_Member_CouponRepository();
        /// <summary>
        /// 分销海报仓储层对象
        /// </summary>
        private readonly RB_MiniProgram_FenXiaoPosterRepository fenXiaoPosterRepository = new RB_MiniProgram_FenXiaoPosterRepository();
        /// <summary>
        /// 会员购买仓储层
        /// </summary>
        private readonly RB_Member_BuyRepository memberBuyRepository = new RB_Member_BuyRepository();
        /// <summary>
        /// 粉象返佣等级
        /// </summary>
        private readonly RB_Distributor_FXGradeRepository distributor_FXGradeRepository = new RB_Distributor_FXGradeRepository();
        /// <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>
        /// 粉象返佣金额
        /// </summary>
        private readonly RB_Distributor_FXCommissionRepository distributor_FXCommissionRepository = new RB_Distributor_FXCommissionRepository();
        /// <summary>
        /// 分销商日志
        /// </summary>
        private readonly RB_Distributor_LogRepository distributor_LogRepository = new RB_Distributor_LogRepository();
        /// <summary>
        /// 推荐供应商返佣账单
        /// </summary>
        private readonly RB_Distributor_BillRepository distributor_BillRepository = new RB_Distributor_BillRepository();
        /// <summary>
        /// 推荐供应商返佣账单明细
        /// </summary>
        private readonly RB_Distributor_BillDetailRepository distributor_BillDetailRepository = new RB_Distributor_BillDetailRepository();
        /// <summary>
        /// 推荐供应商返佣
        /// </summary>
        private readonly RB_Goods_OrderIntroductionRepository goods_OrderIntroductionRepository = new RB_Goods_OrderIntroductionRepository();
        /// <summary>
        /// 供应商
        /// </summary>
        private readonly RB_SupplierRepository supplierRepository = new RB_SupplierRepository();

        private readonly RB_SmallShops_InfoRepository smallShopsInfoRepository = new RB_SmallShops_InfoRepository();

        private readonly RB_SmallShops_CustomRepository smallShopsCustomRepository = new RB_SmallShops_CustomRepository();

        #region 基础配置

        /// <summary>
        /// 获取用户分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetMemberUserPageList(int pageIndex, int pageSize, out long count, RB_Member_User_Extend dmodel)
        {
            var list = member_UserRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                List<RB_Member_Grade_Extend> gradeList = new List<RB_Member_Grade_Extend>();
                if (list.Where(x => x.MemberGrade > 0).Any())
                {
                    var gradeIds = string.Join(",", list.Where(x => x.MemberGrade > 0).Select(x => x.MemberGrade ?? 0));
                    gradeList = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { GradeIds = gradeIds, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    if (item.MemberGrade > 0)
                    {
                        item.MemberGradeName = gradeList.Where(x => x.Id == item.MemberGrade).FirstOrDefault()?.Name ?? "";
                    }
                    else
                    {
                        item.MemberGradeName = "普通会员";
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取下拉列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetMemberUserDropDownList(int pageIndex, int pageSize, out long count, RB_Member_User_Extend demodel)
        {
            return member_UserRepository.GetMemberUserDropDownList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public RB_Member_User_Extend GetMemberUserInfo(int userId)
        {
            return member_UserRepository.GetEntity(userId).RefMapperTo<RB_Member_User_Extend>();
        }

        /// <summary>
        /// 根据条件获取用户实体
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RB_Member_User_Extend GetMemberUserEntityModule(RB_Member_User_Extend query)
        {
            return member_UserRepository.GetMemberUserEntityRepository(query);
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public int AddMemberUserInfo(RB_Member_User_Extend demodel)
        {
            int result = member_UserRepository.Insert(demodel);
            //result = member_UserRepository.SetMemberUserRepository(demodel);
            return result;
        }

        /// <summary>
        /// 验证用户是否存在
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="source"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool ValidateUserOpenId(string openId, Common.Enum.User.UserSourceEnum? source, int tenantId, int mallBaseId)
        {
            var flag = false;
            var model = member_UserRepository.GetMemberUserEntityRepository(new RB_Member_User_Extend()
            {
                OpenId = openId,
                TenantId = tenantId,
                MallBaseId = mallBaseId,
                Source = source
            });
            if (model != null && model.Id > 0)
            {
                flag = true;
            }
            return flag;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetMemberUserList(RB_Member_User_Extend dmodel)
        {
            var list = member_UserRepository.GetList(dmodel);
            if (list.Any())
            {
                List<RB_Member_Grade_Extend> gradeList = new List<RB_Member_Grade_Extend>();
                if (list.Where(x => x.MemberGrade > 0).Any())
                {
                    var gradeIds = string.Join(",", list.Where(x => x.MemberGrade > 0).Select(x => x.MemberGrade ?? 0));
                    gradeList = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { GradeIds = gradeIds, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    if (item.MemberGrade > 0)
                    {
                        item.MemberGradeName = gradeList.Where(x => x.Id == item.MemberGrade).FirstOrDefault()?.Name ?? "";
                    }
                    else
                    {
                        item.MemberGradeName = "普通会员";
                    }
                }
            }
            return list;
        }




        /// <summary>
        ///根据昵称ID手机号码 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetListByPhoneOrAliasName(RB_Member_User_Extend dmodel)
        {
            return member_UserRepository.GetListByPhoneOrAliasName(dmodel);
        }






        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetPageListByKey(int pageIndex, int pageSize, out long rowCount, RB_Member_User_Extend dmodel)
        {
            return member_UserRepository.GetPageListByKey(pageIndex, pageSize, out rowCount, dmodel);
        }

        /// <summary>
        /// 获取等级分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_Grade_Extend> GetMemberGradePageList(int pageIndex, int pageSize, out long count, RB_Member_Grade_Extend dmodel)
        {
            var list = member_GradeRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            if (list.Any())
            {
                string Ids = string.Join(",", list.Select(x => x.Id));
                var elist = member_EquityRepository.GetList(new RB_Member_Equity_Extend() { GradeIds = Ids, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });

                List<int> MaterialIds = new List<int>();
                MaterialIds.AddRange(list.Select(x => x.Icon ?? 0).Distinct().ToList());
                MaterialIds.AddRange(list.Select(x => x.BackgroundImage ?? 0).Distinct().ToList());
                List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
                if (MaterialIds.Any())
                {
                    mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = string.Join(",", MaterialIds), TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    item.EquityList = elist.Where(x => x.GradeId == item.Id).ToList();
                    item.IconPath = mlist.Where(x => x.Id == item.Icon).FirstOrDefault()?.Path ?? "";
                    item.BackgroundImagePath = mlist.Where(x => x.Id == item.BackgroundImage).FirstOrDefault()?.Path ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 后台修改用户信息
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMemberUserInfoForHT(RB_Member_User_Extend demodel)
        {
            Dictionary<string, object> files = new Dictionary<string, object>() {
                { nameof(RB_Member_User.MemberGrade),demodel.MemberGrade},
                { nameof(RB_Member_User.SuperiorId),demodel.SuperiorId},
                { nameof(RB_Member_User.ContactWay),demodel.ContactWay},
                { nameof(RB_Member_User.Remark),demodel.Remark},
                { nameof(RB_Member_User.AliasName),demodel.AliasName},
                { nameof(RB_Member_Grade.UpdateDate),demodel.UpdateDate},
                { nameof(RB_Member_User.PostId),demodel.PostId},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Member_User.Id),
                    FiledValue=demodel.Id,
                    OperatorEnum=OperatorEnum.Equal
                }
            };
            return member_UserRepository.Update(files, wheres);
        }

        /// <summary>
        /// 获取会员等级列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_Grade_Extend> GetMemberGradeList(RB_Member_Grade_Extend dmodel)
        {
            var list = member_GradeRepository.GetList(dmodel);
            if (list.Any())
            {
                string Ids = string.Join(",", list.Select(x => x.Id));
                var elist = member_EquityRepository.GetList(new RB_Member_Equity_Extend() { GradeIds = Ids, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });

                List<int> MaterialIds = new List<int>();
                MaterialIds.AddRange(list.Select(x => x.Icon ?? 0).Distinct().ToList());
                MaterialIds.AddRange(list.Select(x => x.BackgroundImage ?? 0).Distinct().ToList());
                List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
                if (MaterialIds.Any())
                {
                    mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = string.Join(",", MaterialIds), TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    item.EquityList = elist.Where(x => x.GradeId == item.Id).ToList();
                    item.IconPath = mlist.Where(x => x.Id == item.Icon).FirstOrDefault()?.Path ?? "";
                    item.BackgroundImagePath = mlist.Where(x => x.Id == item.BackgroundImage).FirstOrDefault()?.Path ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取会员等级列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_Grade_Extend> GetMemberGrade(RB_Member_Grade_Extend dmodel)
        {
            var list = member_GradeRepository.GetGrade(dmodel);
            return list;
        }

        /// <summary>
        /// 新增会员等级
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMemberGradeInfo(RB_Member_Grade_Extend demodel)
        {
            var trans = member_GradeRepository.DbTransaction;
            try
            {
                if (demodel.Id > 0)
                {
                    Dictionary<string, object> files = new Dictionary<string, object>() {
                        { nameof(RB_Member_Grade.BackgroundImage),demodel.BackgroundImage},
                        { nameof(RB_Member_Grade.Discount),demodel.Discount},
                        { nameof(RB_Member_Grade.Enabled),demodel.Enabled},
                        { nameof(RB_Member_Grade.Grade),demodel.Grade},
                        { nameof(RB_Member_Grade.Icon),demodel.Icon},
                        { nameof(RB_Member_Grade.IsAutoUpGrade),demodel.IsAutoUpGrade},
                        { nameof(RB_Member_Grade.IsMemberBuy),demodel.IsMemberBuy},
                        { nameof(RB_Member_Grade.MemberBuyMoney),demodel.MemberBuyMoney},
                        { nameof(RB_Member_Grade.MemberSpecification),demodel.MemberSpecification},
                        { nameof(RB_Member_Grade.Name),demodel.Name},
                        { nameof(RB_Member_Grade.UpGradeMoney),demodel.UpGradeMoney},
                        { nameof(RB_Member_Grade.UpdateDate),demodel.UpdateDate},
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                         FiledName=nameof(RB_Member_Grade.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    bool flag = member_GradeRepository.Update(files, wheres, trans);
                    if (flag)
                    {
                        var elist = member_EquityRepository.GetList(new RB_Member_Equity_Extend() { GradeId = demodel.Id });
                        List<RB_Member_Equity_Extend> InsertList = new List<RB_Member_Equity_Extend>();
                        List<RB_Member_Equity_Extend> UpdateList = new List<RB_Member_Equity_Extend>();
                        List<RB_Member_Equity_Extend> DeleteList = new List<RB_Member_Equity_Extend>();
                        if (demodel.EquityList != null && demodel.EquityList.Any())
                        {
                            InsertList = demodel.EquityList.Where(x => x.Id == 0).ToList();
                            UpdateList = demodel.EquityList.Where(x => elist.Select(y => y.Id).Contains(x.Id)).ToList();
                            DeleteList = elist.Where(x => !demodel.EquityList.Select(y => y.Id).Contains(x.Id)).ToList();
                        }
                        foreach (var item in InsertList)
                        {
                            member_EquityRepository.Insert(new RB_Member_Equity()
                            {
                                Content = item.Content,
                                CreateDate = demodel.CreateDate,
                                GradeId = demodel.Id,
                                Id = 0,
                                Image = item.Image,
                                MallBaseId = demodel.MallBaseId,
                                Status = 0,
                                TenantId = demodel.TenantId,
                                Title = item.Title,
                                UpdateDate = demodel.CreateDate
                            }, trans);
                        }
                        foreach (var item in UpdateList)
                        {
                            Dictionary<string, object> cols = new Dictionary<string, object>() {
                                { nameof(RB_Member_Equity.Content),item.Content},
                                { nameof(RB_Member_Equity.Image),item.Image},
                                { nameof(RB_Member_Equity.Title),item.Title},
                                { nameof(RB_Member_Equity.UpdateDate),demodel.UpdateDate},
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Member_Equity.Id),
                                      FiledValue=item.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            member_EquityRepository.Update(cols, wheres1, trans);
                        }
                        foreach (var item in DeleteList)
                        {
                            Dictionary<string, object> cols = new Dictionary<string, object>() {
                                { nameof(RB_Member_Equity.Status),1},
                                { nameof(RB_Member_Equity.UpdateDate),demodel.UpdateDate},
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Member_Equity.Id),
                                      FiledValue=item.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            member_EquityRepository.Update(cols, wheres1, trans);
                        }
                    }
                    member_GradeRepository.DBSession.Commit();
                    return flag;
                }
                else
                {
                    int Id = member_GradeRepository.Insert(demodel, trans);
                    bool flag = Id > 0;
                    if (flag)
                    {
                        //插入权益
                        if (demodel.EquityList != null && demodel.EquityList.Any())
                        {
                            foreach (var item in demodel.EquityList)
                            {
                                member_EquityRepository.Insert(new Model.Entity.User.RB_Member_Equity()
                                {
                                    Content = item.Content,
                                    CreateDate = demodel.CreateDate,
                                    GradeId = Id,
                                    Id = 0,
                                    Image = item.Image,
                                    MallBaseId = demodel.MallBaseId,
                                    Status = 0,
                                    TenantId = demodel.TenantId,
                                    Title = item.Title,
                                    UpdateDate = demodel.CreateDate
                                }, trans);
                            }
                        }
                    }
                    member_GradeRepository.DBSession.Commit();
                    return flag;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetMemberGradeInfo");
                member_GradeRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 升级会员
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string GetUserMemberCenterInfo(int gradeId, AppletUserInfo userInfo)
        {
            var umodel = member_UserRepository.GetEntity(userInfo.UserId);
            var gradeModel = member_GradeRepository.GetEntity(gradeId);
            if (gradeModel == null)
            {
                return "等级不存在";
            }
            if (gradeModel.IsAutoUpGrade != 1)
            {
                return "无法升级到该等级";
            }
            //获取用户订单金额
            var SaleModel = goods_OrderRepository.GetUserOrderNumAndMoney(userInfo.UserId.ToString(), userInfo.TenantId, userInfo.MallBaseId).FirstOrDefault();
            if (gradeModel.UpGradeMoney > (SaleModel?.Income ?? 0))
            {
                //升级条件不满足
                return "需累计完成订单金额：" + gradeModel.UpGradeMoney;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Member_User.MemberGrade),gradeId},
                { nameof(RB_Member_User.Remark),umodel.Remark +" 客人自行升级会员等级："+gradeModel.Name}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Member_User.Id),
                      FiledValue=umodel.Id,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = member_UserRepository.Update(keyValues, wheres);
            if (flag)
            {
                return "";
            }
            else
            {
                return "升级失败，请联系管理员";
            }
        }

        /// <summary>
        /// 获取小程序用户会员中心
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetUserMemberCenterInfo(AppletUserInfo userInfo)
        {
            var umodel = member_UserRepository.GetEntity(userInfo.UserId);
            string GradeName = "普通用户";
            string Icon = "";
            string BackgroundImage = "";
            decimal Discount = 0;
            int Grade = 0;
            var qlist = new List<RB_Member_Equity_Extend>();
            if (umodel.MemberGrade > 0)
            {
                var gradeModel = member_GradeRepository.GetEntity(umodel.MemberGrade);
                GradeName = gradeModel?.Name ?? "暂无等级";
                Icon = material_InfoRepository.GetEntity(gradeModel?.Icon ?? 0)?.Path ?? "";
                BackgroundImage = material_InfoRepository.GetEntity(gradeModel?.BackgroundImage ?? 0)?.Path ?? "";
                Discount = gradeModel?.Discount ?? 0;
                Grade = gradeModel.Grade ?? 0;
                //获取权益列表
                qlist = member_EquityRepository.GetList(new RB_Member_Equity_Extend() { GradeId = umodel.MemberGrade, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            }

            //获取可升级的会员信息
            var UpGradeModel = member_GradeRepository.GetMemberUpgrade(Grade, userInfo.TenantId, userInfo.MallBaseId);
            var UpGradeInfo = new object();
            if (UpGradeModel != null && UpGradeModel.IsAutoUpGrade == 1)
            {
                //获取权益列表
                var qlist1 = member_EquityRepository.GetList(new RB_Member_Equity_Extend() { GradeId = UpGradeModel.Id, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                UpGradeInfo = new
                {
                    Status = 1,
                    Info = new
                    {
                        UpGradeModel.Id,
                        UpGradeModel.Grade,
                        UpGradeModel.Name,
                        UpGradeModel.Discount,
                        UpGradeModel.UpGradeMoney,
                        UpGradeModel.IsMemberBuy,
                        UpGradeModel.MemberBuyMoney,
                        UpGradeModel.MemberSpecification,
                        QList = qlist1.Select(x => new
                        {
                            x.Id,
                            x.Title,
                            x.ImagePath,
                            x.Content
                        }),
                    }
                };
            }
            else
            {
                UpGradeInfo = new
                {
                    Status = 2,
                    Msg = "暂无可升级会员等级"
                };
            }

            return new
            {
                UserId = umodel.Id,
                umodel.Name,
                umodel.Photo,
                GradeName,
                umodel.MemberGrade,
                umodel.Balance,
                Icon,
                BackgroundImage,
                Discount,
                QList = qlist.Select(x => new
                {
                    x.Id,
                    x.Title,
                    x.ImagePath,
                    x.Content
                }),
                UpGradeInfo
            };
        }

        /// <summary>
        /// 验证会员等级是否存在
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool ValidateMemberGrade(RB_Member_Grade_Extend demodel)
        {
            List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Member_Grade.Grade),
                        FiledValue=demodel.Grade,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Member_Grade.TenantId),
                        FiledValue=demodel.TenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Member_Grade.MallBaseId),
                        FiledValue=demodel.MallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            if (demodel.Id > 0)
            {
                whereHelpers.Add(new WhereHelper()
                {
                    FiledName = nameof(RB_Member_Grade.Id),
                    FiledValue = demodel.Id,
                    OperatorEnum = OperatorEnum.NotEqual
                });
            }
            return member_GradeRepository.Exists(whereHelpers);
        }

        /// <summary>
        /// 获取会员等级
        /// </summary>
        /// <param name="gradeId"></param>
        /// <returns></returns>
        public RB_Member_Grade_Extend GetMemberGradeInfo(int gradeId)
        {
            var model = member_GradeRepository.GetEntity(gradeId).RefMapperTo<RB_Member_Grade_Extend>();
            if (model == null)
            {
                return new RB_Member_Grade_Extend();
            }
            model.EquityList = member_EquityRepository.GetList(new RB_Member_Equity_Extend() { GradeId = model.Id });
            model.IconPath = material_InfoRepository.GetEntity(model.Icon)?.Path ?? "";
            model.BackgroundImagePath = material_InfoRepository.GetEntity(model.BackgroundImage)?.Path ?? "";
            return model;
        }

        /// <summary>
        /// 删除会员等级
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelMemberGradeInfo(int gradeId, string uid)
        {
            Dictionary<string, object> cols = new Dictionary<string, object>() {
                { nameof(RB_Member_Grade.Status),1},
                { nameof(RB_Member_Grade.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Member_Grade.Id),
                        FiledValue=gradeId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Member_Grade.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return member_GradeRepository.Update(cols, wheres1);
        }

        /// <summary>
        /// 获取积分分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Member_Integral_Extend> GetMemberIntegralPageList(int pageIndex, int pageSize, out long count, RB_Member_Integral_Extend demodel)
        {
            return member_IntegralRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 保存积分
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMemberIntegralInfo(RB_Member_Integral_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            int Integral;
            if ((int)demodel.Type == 1)
            {
                Integral = (umodel.Integral ?? 0) + (demodel.Integral ?? 0);
            }
            else
            {
                Integral = (umodel.Integral ?? 0) - (demodel.Integral ?? 0);
            }
            if (Integral < 0)
            {
                Integral = 0;
            }
            Dictionary<string, object> keys = new Dictionary<string, object>() {
                { nameof(RB_Member_User.Integral),Integral}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Member_User.Id),
                    FiledValue=demodel.UserId,
                    OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = member_UserRepository.Update(keys, wheres);
            if (flag)
            {
                return member_IntegralRepository.Insert(demodel) > 0;
            }
            return false;
        }

        /// <summary>
        /// 获取余额分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Member_Balance_Extend> GetMemberBalancePageList(int pageIndex, int pageSize, out long count, RB_Member_Balance_Extend demodel)
        {
            return member_BalanceRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 保存余额充值
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMemberBalanceInfo(RB_Member_Balance_Extend demodel)
        {
            var umodel = member_UserRepository.GetEntity(demodel.UserId);
            decimal Balance;
            if ((int)demodel.Type == 1)
            {
                Balance = (umodel.Balance ?? 0) + (demodel.Balance ?? 0);
            }
            else
            {
                Balance = (umodel.Balance ?? 0) - (demodel.Balance ?? 0);
            }
            if (Balance < 0)
            {
                Balance = 0;
            }
            Dictionary<string, object> keys = new Dictionary<string, object>() {
                { nameof(RB_Member_User.Balance),Balance}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Member_User.Id),
                    FiledValue=demodel.UserId,
                    OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = member_UserRepository.Update(keys, wheres);
            if (flag)
            {
                return member_BalanceRepository.Insert(demodel) > 0;
            }
            return false;
        }

        /// <summary>
        /// 设置分销基础配置
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetDistributorBasicsInfo(RB_Distributor_Basics_Extend demodel)
        {
            demodel.GradeEntranceImage = new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("InitializeImages")["GradeEntranceImage"];
            var OModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if (OModel != null)
            {
                demodel.Id = OModel.Id;
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_Basics.DistributorTier),demodel.DistributorTier},
                    { nameof(RB_Distributor_Basics.InPurchasing),demodel.InPurchasing},
                    { nameof(RB_Distributor_Basics.ReferralsCondition),demodel.ReferralsCondition},
                    { nameof(RB_Distributor_Basics.ApplyFor),demodel.ApplyFor},
                    { nameof(RB_Distributor_Basics.DistributorCondition),demodel.DistributorCondition},
                    { nameof(RB_Distributor_Basics.DistributorCommissionType),demodel.DistributorCommissionType},
                    { nameof(RB_Distributor_Basics.OneCommission),demodel.OneCommission},
                    { nameof(RB_Distributor_Basics.TwoCommission),demodel.TwoCommission},
                    { nameof(RB_Distributor_Basics.ThreeCommission),demodel.ThreeCommission},
                    { nameof(RB_Distributor_Basics.GradeEntrance),demodel.GradeEntrance},
                    { nameof(RB_Distributor_Basics.GradeEntranceImage),demodel.GradeEntranceImage},
                    { nameof(RB_Distributor_Basics.WithdrawWay),demodel.WithdrawWay},
                    { nameof(RB_Distributor_Basics.MinimumWithdrawalLimit),demodel.MinimumWithdrawalLimit},
                    { nameof(RB_Distributor_Basics.DailyWithdrawalLimit),demodel.DailyWithdrawalLimit},
                    { nameof(RB_Distributor_Basics.WithdrawFee),demodel.WithdrawFee},
                    { nameof(RB_Distributor_Basics.ApplicationProtocol),demodel.ApplicationProtocol},
                    { nameof(RB_Distributor_Basics.UserNotes),demodel.UserNotes},
                    { nameof(RB_Distributor_Basics.BackgroundImage),demodel.BackgroundImage},
                    { nameof(RB_Distributor_Basics.IndexImage),demodel.IndexImage},
                    { nameof(RB_Distributor_Basics.UpdateDate),demodel.UpdateDate},
                    { nameof(RB_Distributor_Basics.HpReferralsGradeAudit),demodel.HpReferralsGradeAudit},
                    { nameof(RB_Distributor_Basics.IsCommissionResidue),demodel.IsCommissionResidue},
                    { nameof(RB_Distributor_Basics.IsWithdrawAll),demodel.IsWithdrawAll},
                    { nameof(RB_Distributor_Basics.IsEnableFXGrade),demodel.IsEnableFXGrade},
                    { nameof(RB_Distributor_Basics.IsEnableNoSuperiorFY),demodel.IsEnableNoSuperiorFY},
                };
                List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Basics.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Basics.TenantId),
                          FiledValue=demodel.TenantId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Basics.MallBaseId),
                          FiledValue=demodel.MallBaseId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return distributor_BasicsRepository.Update(keyValuePairs, whereHelpers);
            }
            else
            {
                return distributor_BasicsRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 获取分销基础信息
        /// </summary>
        /// <param name="basicsId"></param>
        /// <returns></returns>
        public RB_Distributor_Basics_Extend GetDistributorBasicsInfo(int basicsId)
        {
            var model = distributor_BasicsRepository.GetEntity(basicsId).RefMapperTo<RB_Distributor_Basics_Extend>();
            if (model == null)
            {
                return new RB_Distributor_Basics_Extend();
            }
            model.IndexImagePath = material_InfoRepository.GetEntity(model.IndexImage)?.Path ?? "";
            model.BackgroundImagePath = material_InfoRepository.GetEntity(model.BackgroundImage)?.Path ?? "";
            return model;
        }

        /// <summary>
        /// 获取分销基础信息
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_Distributor_Basics_Extend GetDistributorBasicsInfo(string uid, int mallBaseId)
        {
            var model = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return new RB_Distributor_Basics_Extend();
            }
            model.IndexImagePath = material_InfoRepository.GetEntity(model.IndexImage)?.Path ?? "";
            model.BackgroundImagePath = material_InfoRepository.GetEntity(model.BackgroundImage)?.Path ?? "";
            if (!string.IsNullOrEmpty(model.WithdrawWay))
            {
                model.WithdrawWayList = JsonConvert.DeserializeObject<List<int>>(model.WithdrawWay);
            }
            return model;
        }

        /// <summary>
        /// 设置分销自定义
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetDistributorCustomInfo(RB_Distributor_Custom_Extend demodel)
        {
            var OModel = distributor_CustomRepository.GetList(new RB_Distributor_Custom_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if (OModel != null)
            {
                demodel.Id = OModel.Id;
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_Custom.HeadImage),demodel.HeadImage},
                    { nameof(RB_Distributor_Custom.BottomImage),demodel.BottomImage},
                    { nameof(RB_Distributor_Custom.DistributionApplication),demodel.DistributionApplication},
                    { nameof(RB_Distributor_Custom.ApplicationAgreement),demodel.ApplicationAgreement},
                    { nameof(RB_Distributor_Custom.ButtonFilletPX),demodel.ButtonFilletPX},
                    { nameof(RB_Distributor_Custom.ButtonText),demodel.ButtonText},
                    { nameof(RB_Distributor_Custom.ButtonColor),demodel.ButtonColor},
                    { nameof(RB_Distributor_Custom.ButtonTextColor),demodel.ButtonTextColor},
                    { nameof(RB_Distributor_Custom.DistributionCommissionName),demodel.DistributionCommissionName},
                    { nameof(RB_Distributor_Custom.DistributionCommissionImage),demodel.DistributionCommissionImage},
                    { nameof(RB_Distributor_Custom.DistributionOrderName),demodel.DistributionOrderName},
                    { nameof(RB_Distributor_Custom.DistributionOrderImage),demodel.DistributionOrderImage},
                    { nameof(RB_Distributor_Custom.WithdrawDetialsName),demodel.WithdrawDetialsName},
                    { nameof(RB_Distributor_Custom.WithdrawDetialsImage),demodel.WithdrawDetialsImage},
                    { nameof(RB_Distributor_Custom.MyTeamName),demodel.MyTeamName},
                    { nameof(RB_Distributor_Custom.MyTeamImage),demodel.MyTeamImage},
                    { nameof(RB_Distributor_Custom.PromoteQRCodeName),demodel.PromoteQRCodeName},
                    { nameof(RB_Distributor_Custom.PromoteQRCodeImage),demodel.PromoteQRCodeImage},
                    { nameof(RB_Distributor_Custom.ReferrerName),demodel.ReferrerName},
                    { nameof(RB_Distributor_Custom.CommissionForWithdrawalName),demodel.CommissionForWithdrawalName},
                    { nameof(RB_Distributor_Custom.WithdrawDepositName),demodel.WithdrawDepositName},
                    { nameof(RB_Distributor_Custom.CommissionWithdrawnName),demodel.CommissionWithdrawnName},
                    { nameof(RB_Distributor_Custom.OutstandingCommissionName),demodel.OutstandingCommissionName},
                    { nameof(RB_Distributor_Custom.DistributorName),demodel.DistributorName},
                    { nameof(RB_Distributor_Custom.CommissionTobePaidName),demodel.CommissionTobePaidName},
                    { nameof(RB_Distributor_Custom.UserNotesName),demodel.UserNotesName},
                    { nameof(RB_Distributor_Custom.IWantToWithdrawName),demodel.IWantToWithdrawName},
                    { nameof(RB_Distributor_Custom.WithdrawalAmountName),demodel.WithdrawalAmountName},
                    { nameof(RB_Distributor_Custom.WithdrawalWayName),demodel.WithdrawalWayName},
                    { nameof(RB_Distributor_Custom.OneDistributionName),demodel.OneDistributionName},
                    { nameof(RB_Distributor_Custom.TwoDistributionName),demodel.TwoDistributionName},
                    { nameof(RB_Distributor_Custom.ThreeDistributionName),demodel.ThreeDistributionName},
                    { nameof(RB_Distributor_Custom.UpdateDate),demodel.UpdateDate},
                    { nameof(RB_Distributor_Custom.IsShowVIPBuyPic),demodel.IsShowVIPBuyPic},
                      { nameof(RB_Distributor_Custom.VipBuyICO),demodel.VipBuyICO},
                        { nameof(RB_Distributor_Custom.VipBuyUrl),demodel.VipBuyUrl}
            };
                List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Custom.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Custom.TenantId),
                          FiledValue=demodel.TenantId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Custom.MallBaseId),
                          FiledValue=demodel.MallBaseId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return distributor_CustomRepository.Update(keyValuePairs, whereHelpers);
            }
            else
            {
                return distributor_CustomRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 获取分销自定义信息
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_Distributor_Custom_Extend GetDistributorCustomInfo(string uid, int mallBaseId)
        {
            var model = distributor_CustomRepository.GetList(new RB_Distributor_Custom_Extend() { TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return new RB_Distributor_Custom_Extend();
            }
            model.BottomImagePath = material_InfoRepository.GetEntity(model.BottomImage)?.Path ?? "";
            model.DistributionCommissionImagePath = material_InfoRepository.GetEntity(model.DistributionCommissionImage)?.Path ?? "";
            model.DistributionOrderImagePath = material_InfoRepository.GetEntity(model.DistributionOrderImage)?.Path ?? "";
            model.HeadImagePath = material_InfoRepository.GetEntity(model.HeadImage)?.Path ?? "";
            model.MyTeamImagePath = material_InfoRepository.GetEntity(model.MyTeamImage)?.Path ?? "";
            model.PromoteQRCodeImagePath = material_InfoRepository.GetEntity(model.PromoteQRCodeImage)?.Path ?? "";
            model.WithdrawDetialsImagePath = material_InfoRepository.GetEntity(model.WithdrawDetialsImage)?.Path ?? "";
            return model;
        }

        /// <summary>
        /// 获取等级分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Grade_Extend> GetDistributorGradePageList(int pageIndex, int pageSize, out long count, RB_Distributor_Grade_Extend demodel)
        {
            var list = distributor_GradeRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            //获取分销商基础
            var bmodel = GetDistributorBasicsInfo(demodel.TenantId.ToString(), demodel.MallBaseId);
            if (bmodel != null)
            {
                switch (bmodel.DistributorTier)
                {
                    case 0:
                        foreach (var item in list)
                        {
                            item.OneCommission = -1;
                            item.TwoCommission = -1;
                            item.ThreeCommission = -1;
                        }
                        break;
                    case 1:
                        foreach (var item in list)
                        {
                            item.TwoCommission = -1;
                            item.ThreeCommission = -1;
                        }
                        break;
                    case 2:
                        foreach (var item in list)
                        {
                            item.ThreeCommission = -1;
                        }
                        break;
                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改分销商等级
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetDistributorGradeInfo(RB_Distributor_Grade_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                var model = distributor_GradeRepository.GetEntity(demodel.Id);
                if (model == null)
                {
                    return false;
                }
                if (model.TenantId != demodel.TenantId)
                {
                    return false;
                }
                if (model.MallBaseId != demodel.MallBaseId)
                {
                    return false;
                }
                if (model.Enabled == 1 && demodel.Enabled == 2)
                {
                    //验证是否有分销商在使用该等级
                    if (ValidateDistributorGradeEnabled(model.Id))
                    {
                        return false;
                    }
                }

                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_Grade.CommissionWithdrawn),demodel.CommissionWithdrawn},
                    { nameof(RB_Distributor_Grade.DistributionCommissionType),demodel.DistributionCommissionType},
                    { nameof(RB_Distributor_Grade.Enabled),demodel.Enabled},
                    { nameof(RB_Distributor_Grade.Grade),demodel.Grade},
                    { nameof(RB_Distributor_Grade.GradeExplain),demodel.GradeExplain},
                    { nameof(RB_Distributor_Grade.IsAutoUpGrade),demodel.IsAutoUpGrade},
                    { nameof(RB_Distributor_Grade.Name),demodel.Name},
                    { nameof(RB_Distributor_Grade.OneCommission),demodel.OneCommission},
                    { nameof(RB_Distributor_Grade.ReferralsNumber),demodel.ReferralsNumber},
                    { nameof(RB_Distributor_Grade.ThreeCommission),demodel.ThreeCommission},
                    { nameof(RB_Distributor_Grade.TotalCommission),demodel.TotalCommission},
                    { nameof(RB_Distributor_Grade.TwoCommission),demodel.TwoCommission},
                    { nameof(RB_Distributor_Grade.UpGradeCondition),demodel.UpGradeCondition},
                    { nameof(RB_Distributor_Grade.UpdateDate),demodel.UpdateDate}
                };
                List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Grade.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = distributor_GradeRepository.Update(keyValues, whereHelpers);
                if (flag)
                {
                    if (model.Enabled == 1 && demodel.Enabled == 2)
                    {
                        //由启用设置为停用  需更新该等级下的用户为默认等级
                        member_UserRepository.UpdateMemberGrade(GradeId: demodel.Id, DefaultGId: 0, demodel.TenantId, demodel.MallBaseId);
                    }
                }
                return flag;
            }
            else
            {
                return distributor_GradeRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 获取分销等级下拉列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Grade_Extend> GetDistributorGradeDropdownList(RB_Distributor_Grade_Extend demodel)
        {
            var list = distributor_GradeRepository.GetList(demodel);
            return list;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelDistributorGradeInfo(int gradeId, string uid, int mallBaseId)
        {
            var gmodel = distributor_GradeRepository.GetEntity(gradeId);
            if (gmodel == null)
            {
                return false;
            }
            if (gmodel.TenantId != Convert.ToInt32(uid))
            {
                return false;
            }
            if (gmodel.MallBaseId != mallBaseId)
            {
                return false;
            }
            if (gmodel.Enabled == 1)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_Grade.Status),1},
                { nameof(RB_Distributor_Grade.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_Grade.Id),
                        FiledValue=gradeId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return distributor_GradeRepository.Update(keyValues, whereHelpers);
        }

        /// <summary>
        /// 验证分销商等级使用
        /// </summary>
        /// <param name="gradeId"></param>
        /// <returns></returns>
        public bool ValidateDistributorGradeEnabled(int gradeId)
        {
            List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_Info.GradeId),
                        FiledValue=gradeId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_Info.Status),
                        FiledValue=0,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_Info.AuditStatus),
                        FiledValue=2,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return distributor_InfoRepository.Exists(whereHelpers);
        }

        /// <summary>
        /// 修改分销商等级启用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetDistributorGradeEnabledStatus(RB_Distributor_Grade model)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_Grade.Enabled),model.Enabled==1?2:1},
                { nameof(RB_Distributor_Grade.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_Grade.Id),
                        FiledValue=model.Id,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return distributor_GradeRepository.Update(keyValues, whereHelpers);
        }

        /// <summary>
        /// 获取分销商等级信息
        /// </summary>
        /// <param name="gradeId"></param>
        /// <returns></returns>
        public RB_Distributor_Grade GetDistributorGradeInfo(int gradeId)
        {
            return distributor_GradeRepository.GetEntity(gradeId);
        }

        /// <summary>
        /// 获取分销商分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Info_Extend> GetDistributorInfoPageList(int pageIndex, int pageSize, out long count, RB_Distributor_Info_Extend demodel)
        {
            var list = distributor_InfoRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询分销商等级
                string gradeIds = string.Join(",", list.Where(x => x.GradeId > 0).Select(x => x.GradeId ?? 0).Distinct());
                List<RB_Distributor_Grade_Extend> GradeList = new List<RB_Distributor_Grade_Extend>();
                if (!string.IsNullOrEmpty(gradeIds))
                {
                    GradeList = distributor_GradeRepository.GetList(new RB_Distributor_Grade_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                //查询和平分销等级
                string hpgradeIds = string.Join(",", list.Where(x => x.HPGradeId > 0).Select(x => x.HPGradeId ?? 0).Distinct());
                List<RB_Distributor_HPGradeInfo_Extend> HPGradeList = new List<RB_Distributor_HPGradeInfo_Extend>();
                if (!string.IsNullOrEmpty(hpgradeIds))
                {
                    HPGradeList = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { GradeIds = hpgradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                //查询粉象分销等级
                string fxgradeIds = string.Join(",", list.Where(x => x.FXGradeId > 0).Select(x => x.FXGradeId ?? 0).Distinct());
                List<RB_Distributor_FXGrade_Extend> FXGradeList = new List<RB_Distributor_FXGrade_Extend>();
                if (!string.IsNullOrEmpty(fxgradeIds))
                {
                    FXGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = fxgradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                //查询推荐人列表
                string tjrIds = string.Join(",", list.Where(x => x.SuperiorId > 0).Select(x => x.SuperiorId ?? 0).Distinct());
                List<RB_Member_User_Extend> UserList = new List<RB_Member_User_Extend>();
                if (!string.IsNullOrEmpty(tjrIds))
                {
                    UserList = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = tjrIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                //根据基础配置层级查询下级数量  暂放弃
                //var basmdoel = GetDistributorBasicsInfo(demodel.TenantId.ToString(), demodel.MallBaseId);
                //if (basmdoel != null && basmdoel.DistributorTier > 0) {
                string uids = string.Join(",", list.Select(x => x.UserId ?? 0));
                List<RB_Member_User_Extend> UserNum1List = member_UserRepository.GetDistributorReferralsNum(uids, tier: 1, tenantId: demodel.TenantId, mallBaseId: demodel.MallBaseId);//直接查询三级
                List<RB_Member_User_Extend> UserNum2List = member_UserRepository.GetDistributorReferralsNum(uids, tier: 2, tenantId: demodel.TenantId, mallBaseId: demodel.MallBaseId);//直接查询三级
                List<RB_Member_User_Extend> UserNum3List = member_UserRepository.GetDistributorReferralsNum(uids, tier: 3, tenantId: demodel.TenantId, mallBaseId: demodel.MallBaseId);//直接查询三级

                foreach (var item in list)
                {
                    if (item.GradeId == 0)
                    {
                        item.GradeName = "默认等级";
                    }
                    else if (item.GradeId > 0)
                    {
                        item.GradeName = GradeList.Where(x => x.Id == item.GradeId).FirstOrDefault()?.Name ?? "";
                    }
                    if ((item.HPGradeId ?? 0) == 0)
                    {
                        item.HPGradeName = "默认等级";
                    }
                    else if (item.HPGradeId > 0)
                    {
                        item.HPGradeName = HPGradeList.Where(x => x.Id == item.HPGradeId).FirstOrDefault()?.GradeName ?? "";
                    }
                    if ((item.FXGradeId ?? 0) == 0)
                    {
                        item.FXGradeName = "默认等级";
                    }
                    else if (item.FXGradeId > 0)
                    {
                        item.FXGradeName = FXGradeList.Where(x => x.Id == item.FXGradeId).FirstOrDefault()?.GradeName ?? "";
                    }



                    if (item.SuperiorId == 0)
                    {
                        item.SuperiorName = "总店";
                    }
                    else if (item.SuperiorId > 0)
                    {
                        item.SuperiorName = UserList.Where(x => x.Id == item.SuperiorId).FirstOrDefault()?.Name ?? "";
                    }
                    item.OneNum = 0;
                    if (UserNum1List.Any())
                    {
                        item.OneNum = UserNum1List.Where(x => x.SuperiorId == item.UserId).FirstOrDefault()?.ReferralsNum ?? 0;
                    }
                    item.TwoNum = 0;
                    if (UserNum1List.Any())
                    {
                        item.TwoNum = UserNum2List.Where(x => x.SuperiorId == item.UserId).FirstOrDefault()?.ReferralsNum ?? 0;
                    }
                    item.ThreeNum = 0;
                    if (UserNum1List.Any())
                    {
                        item.ThreeNum = UserNum3List.Where(x => x.SuperiorId == item.UserId).FirstOrDefault()?.ReferralsNum ?? 0;
                    }
                }

            }
            return list;
        }

        /// <summary>
        /// 获取待审核的所有下线列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Info_Extend> GetHpUserReferralsAuditList(int pageIndex, int pageSize, out long count, RB_Distributor_Info_Extend demodel)
        {
            var list = distributor_InfoRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            return list;
        }

        /// <summary>
        /// 设置和平下线自行审核
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetHpUserReferralsAudit(int userId, int type, AppletUserInfo userInfo)
        {
            if (GetHpDistributorIsEnabled(userInfo.TenantId, userInfo.MallBaseId) == 2 && userInfo.TenantId != 1)
            {
                return false;
            }
            var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (disModel == null || disModel.AuditStatus == DistributorAuditStatusEnum.Reject)
            {
                return false;
            }
            if (type == 1)
            {
                //查询最小的代理等级
                var glist = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                int MinId = glist.Where(x => (x.IsGuest ?? 0) != 1).Max(x => x.Grade ?? 0);
                int MinGradeId = glist.Where(x => x.Grade == MinId).FirstOrDefault()?.Id ?? 0;
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_Info.AuditStatus),DistributorAuditStatusEnum.Audited},
                    {nameof(RB_Distributor_Info.HPGradeId),MinGradeId },
                    {nameof(RB_Distributor_Info.GradeId),userInfo.TenantId==1? 74:disModel.GradeId },
                    {nameof(RB_Distributor_Info.Remark),"上线自行审核通过"},
                    {nameof(RB_Distributor_Info.AuditDate),DateTime.Now }
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Info.Id),
                          FiledValue=disModel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = distributor_InfoRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //修改用户表状态
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                        { nameof(RB_Member_User.IsDistributor),1}
                    };
                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Member_User.Id),
                                FiledValue=disModel.UserId,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    member_UserRepository.Update(keyValues1, wheres1);

                    var umodel = GetMemberUserInfo(disModel.UserId ?? 0);
                    if (umodel != null)
                    {
                        new MiniProgramMsgModule().SendAuditResultMsg(disModel.TenantId, disModel.MallBaseId, umodel.OpenId, "分销商审核已通过", "通过", umodel.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                }
                return flag;
            }
            else
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_Info.AuditStatus),DistributorAuditStatusEnum.Reject},
                    {nameof(RB_Distributor_Info.Remark),"上线自行审核拒绝"},
                    {nameof(RB_Distributor_Info.AuditDate),DateTime.Now }
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Info.Id),
                          FiledValue=disModel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = distributor_InfoRepository.Update(keyValues, wheres);
                if (flag)
                {
                    var umodel = GetMemberUserInfo(disModel.UserId ?? 0);
                    if (umodel != null)
                    {
                        new MiniProgramMsgModule().SendAuditResultMsg(disModel.TenantId, disModel.MallBaseId, umodel.OpenId, "分销商审核被拒绝", "拒绝", umodel.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                }
                return flag;
            }

        }

        /// <summary>
        /// 新增分销商
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetDistributorInfo(RB_Distributor_Info_Extend demodel)
        {
            demodel.TotalCommission ??= 0;
            demodel.CommissionWithdrawal ??= 0;
            demodel.Name ??= "";
            demodel.GradeId ??= 0;
            demodel.AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Auditing;
            bool flag = distributor_InfoRepository.Insert(demodel) > 0;
            if (flag)
            {
                //更新手机号码
                //Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                //    { nameof(RB_Member_User.Moblie),demodel.Mobile}
                //};
                //List<WhereHelper> wheres = new List<WhereHelper>() {
                //    new WhereHelper(){
                //            FiledName=nameof(RB_Member_User.Id),
                //            FiledValue=demodel.UserId,
                //            OperatorEnum=OperatorEnum.Equal
                //    }
                //};
                //member_UserRepository.Update(keyValues, wheres);
            }
            return flag;
        }

        /// <summary>
        /// 新增分销商
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetDistributorInfoForFX(int FXGradeId, int UserId, int TenantId, int MallBaseId)
        {
            var demodel = new RB_Distributor_Info_Extend
            {
                UserId = UserId
            };
            demodel.TotalCommission ??= 0;
            demodel.CommissionWithdrawal ??= 0;
            demodel.Name ??= "";
            demodel.Mobile ??= "";
            demodel.GradeId ??= 0;
            demodel.HPGradeId ??= 0;
            demodel.FXGradeId = FXGradeId;
            demodel.AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited;
            demodel.AuditDate = DateTime.Now;
            demodel.Remark = "粉象模式 自动生成普通会员分销商信息";
            demodel.Status = 0;
            demodel.TenantId = TenantId;
            demodel.MallBaseId = MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = distributor_InfoRepository.Insert(demodel) > 0;
            return flag;
        }

        /// <summary>
        /// 验证分销商
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string ValidateDistributorInfo(int? userId, int tenantId, int mallBaseId)
        {
            var model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return "";
            }
            if (model.AuditStatus == Common.Enum.User.DistributorAuditStatusEnum.Reject)
            {
                return "已被拒绝，无法再次申请";
            }
            else if (model.AuditStatus == Common.Enum.User.DistributorAuditStatusEnum.Auditing)
            {
                return "申请正在审核中，无法再次申请";
            }
            else if (model.AuditStatus == Common.Enum.User.DistributorAuditStatusEnum.Audited)
            {
                return "已经成为分销商，无法再次申请";
            }
            return "";
        }

        /// <summary>
        /// 获取下级用户列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetDistributorInfoReferralsPageList(RB_Distributor_Info_Extend demodel)
        {
            var list = member_UserRepository.GetDistributorReferralsPageList(demodel.UserId, demodel.ReferralsType, demodel.TenantId, demodel.MallBaseId);
            return list;
        }

        /// <summary>
        /// 分销商审核+修改等级
        /// </summary>
        /// <param name="userIds"></param>
        /// <param name="type"></param>
        /// <param name="newGradeId"></param>
        /// <param name="remark"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string SetDistributorAudit(string userIds, int type, int newGradeId, string remark, string uid, int mallBaseId, int empId)
        {
            var trans = distributor_InfoRepository.DbTransaction;
            try
            {
                if (type == 1)
                {
                    var list = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserIds = userIds, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                    foreach (var item in list)
                    {
                        if (item.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Auditing)
                        {
                            return "用户ID:" + item.UserId + " 不是未审核状态，无法通过";
                        }
                    }
                    //批量修改状态
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Info.AuditStatus),2},
                            { nameof(RB_Distributor_Info.Remark),remark},
                            { nameof(RB_Distributor_Info.AuditDate),DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Distributor_Info.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag = distributor_InfoRepository.Update(keyValues, wheres, trans);
                        if (flag)
                        {
                            //修改用户表状态
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User.IsDistributor),1}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Member_User.Id),
                                      FiledValue=item.UserId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            member_UserRepository.Update(keyValues1, wheres1, trans);

                            var umodel = GetMemberUserInfo(item.UserId ?? 0);
                            if (umodel != null)
                            {
                                new MiniProgramMsgModule().SendAuditResultMsg(item.TenantId, item.MallBaseId, umodel.OpenId, "分销商审核已通过", "通过", umodel.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            }
                        }
                    }
                }
                else if (type == 2)
                {
                    var list = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserIds = userIds, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                    foreach (var item in list)
                    {
                        if (item.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Auditing)
                        {
                            return "用户ID:" + item.UserId + " 不是未审核状态，无法拒绝";
                        }
                    }
                    //批量修改状态
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Info.AuditStatus),3},
                            { nameof(RB_Distributor_Info.Remark),remark},
                            { nameof(RB_Distributor_Info.AuditDate),DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Distributor_Info.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag = distributor_InfoRepository.Update(keyValues, wheres, trans);
                        if (flag)
                        {
                            var umodel = GetMemberUserInfo(item.UserId ?? 0);
                            if (umodel != null)
                            {
                                new MiniProgramMsgModule().SendAuditResultMsg(item.TenantId, item.MallBaseId, umodel.OpenId, "分销商审核被拒绝", "拒绝", umodel.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            }
                        }
                    }
                }
                else if (type == 3)
                {
                    var list = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserIds = userIds, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                    foreach (var item in list)
                    {
                        if (item.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Audited)
                        {
                            return "用户ID:" + item.UserId + " 不是审核通过状态，无法删除";
                        }
                    }
                    //批量修改状态
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Info.Status),1},
                            { nameof(RB_Distributor_Info.UpdateDate),DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Distributor_Info.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag = distributor_InfoRepository.Update(keyValues, wheres, trans);
                        if (flag)
                        {
                            //修改用户表状态
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User.IsDistributor),2}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Member_User.Id),
                                      FiledValue=item.UserId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            member_UserRepository.Update(keyValues1, wheres1, trans);

                        }
                    }
                }
                else if (type == 4)
                {
                    var list = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserIds = userIds, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                    foreach (var item in list)
                    {
                        if (item.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Audited)
                        {
                            return "用户ID:" + item.UserId + " 不是审核通过状态，无法修改等级";
                        }
                    }
                    //批量修改状态
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Info.GradeId),newGradeId},
                            { nameof(RB_Distributor_Info.UpdateDate),DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Distributor_Info.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag = distributor_InfoRepository.Update(keyValues, wheres, trans);
                        if (flag)
                        {
                            //记录日志
                            distributor_LogRepository.Insert(new RB_Distributor_Log()
                            {
                                Content = "修改分销商等级为：newGradeId",
                                CreateDate = DateTime.Now,
                                EmpId = empId,
                                Id = 0,
                                MallBaseId = mallBaseId,
                                TenantId = Convert.ToInt32(uid),
                                Type = 1,
                                UserId = item.Id
                            });
                        }
                    }
                }
                else if (type == 5)
                {
                    var list = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserIds = userIds, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                    foreach (var item in list)
                    {
                        if (item.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Audited)
                        {
                            return "用户ID:" + item.UserId + " 不是审核通过状态，无法修改备注";
                        }
                    }
                    //批量修改状态
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Info.Remark),remark},
                            { nameof(RB_Distributor_Info.UpdateDate),DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Distributor_Info.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag = distributor_InfoRepository.Update(keyValues, wheres, trans);
                    }
                }
                else if (type == 6)
                {
                    var list = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserIds = userIds, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                    var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = userIds, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                    var gmodel = distributor_HPGradeInfoRepository.GetEntity(newGradeId);
                    foreach (var item in list)
                    {
                        if (item.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Audited)
                        {
                            return "用户ID:" + item.UserId + " 不是审核通过状态，无法修改等级";
                        }
                        //验证其上级用户 
                        var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                        if (umodel == null)
                        {
                            return "用户不存在ID:" + item.UserId;
                        }
                        if (umodel.SuperiorId == 0)
                        {
                            //上级为0  
                            if ((gmodel?.Grade ?? 0) != 1)
                            {
                                return "用户上级不存在，只能修改为1级和平分销 ID:" + item.UserId;
                            }
                        }
                        else
                        {
                            if ((gmodel?.Grade ?? 0) == 1)
                            {
                                return "用户上级存在，无法改为1级和平分销 ID:" + item.UserId;
                            }
                        }
                        if ((gmodel?.Grade ?? 0) > 1)
                        {
                            var pModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = umodel.SuperiorId, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId }).FirstOrDefault();
                            if (pModel == null)
                            {
                                return "用户上级不是分销商 ID:" + item.UserId;
                            }
                            if (pModel.AuditStatus != DistributorAuditStatusEnum.Audited)
                            {
                                return "用户上级分销商不是通过状态 ID:" + item.UserId;
                            }
                            if ((pModel.HPGradeId ?? 0) <= 0)
                            {
                                return "用户上级分销商未绑定和平分销等级 ID:" + item.UserId;
                            }
                            var hpgmodel = distributor_HPGradeInfoRepository.GetEntity(pModel.HPGradeId);
                            if ((hpgmodel.Grade ?? 0) == 2 && (gmodel?.Grade ?? 0) > 2)
                            {
                                //成立  特一级比较特殊
                            }
                            else
                            {
                                if ((gmodel?.Grade ?? 0) == 3)
                                {
                                    if (hpgmodel.Grade != 1 && hpgmodel.Grade != 2)
                                    {
                                        return "用户分销等级与上级用户分销等级不是关联关系 ID:" + item.UserId;
                                    }
                                }
                                else if ((gmodel?.Grade ?? 0) == 2 && hpgmodel.Grade != 1)
                                {
                                    return "用户分销等级与上级用户分销等级不是上下级关系 ID:" + item.UserId;
                                }
                                else if ((gmodel?.Grade ?? 0) - (hpgmodel.Grade ?? 0) != 1)
                                {
                                    return "用户分销等级与上级用户分销等级不是上下级关系 ID:" + item.UserId;
                                }
                            }
                        }
                    }
                    //批量修改状态
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Info.HPGradeId),newGradeId},
                            { nameof(RB_Distributor_Info.UpdateDate),DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Distributor_Info.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag = distributor_InfoRepository.Update(keyValues, wheres, trans);
                    }
                }
                else if (type == 7)
                {
                    var list = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserIds = userIds, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                    foreach (var item in list)
                    {
                        if (item.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Audited)
                        {
                            return "用户ID:" + item.UserId + " 不是审核通过状态，无法修改等级";
                        }
                    }
                    //批量修改状态
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Info.FXGradeId),newGradeId},
                            { nameof(RB_Distributor_Info.UpdateDate),DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Distributor_Info.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag = distributor_InfoRepository.Update(keyValues, wheres, trans);
                        if (flag)
                        {
                            //记录日志
                            distributor_LogRepository.Insert(new RB_Distributor_Log()
                            {
                                Content = "修改分销商等级为：newGradeId",
                                CreateDate = DateTime.Now,
                                EmpId = empId,
                                Id = 0,
                                MallBaseId = mallBaseId,
                                TenantId = Convert.ToInt32(uid),
                                Type = 1,
                                UserId = item.Id
                            });
                        }
                    }
                }
                else
                {
                    return "Type传递有误";
                }
                distributor_InfoRepository.DBSession.Commit();
                return "";
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetDistributorAudit");
                distributor_InfoRepository.DBSession.Rollback();
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 获取分销提现分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Remit_Extend> GetDistributorRemitPageList(int pageIndex, int pageSize, out long count, RB_Distributor_Remit_Extend demodel)
        {
            return distributor_RemitRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取下载列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Info_Extend> GetDistributorInfoList(RB_Distributor_Info_Extend demodel)
        {
            var list = distributor_InfoRepository.GetToExcelList(demodel);
            if (list.Any())
            {
                //查询分销商等级
                string gradeIds = string.Join(",", list.Where(x => x.GradeId > 0).Select(x => x.GradeId ?? 0).Distinct());
                List<RB_Distributor_Grade_Extend> GradeList = new List<RB_Distributor_Grade_Extend>();
                if (!string.IsNullOrEmpty(gradeIds))
                {
                    GradeList = distributor_GradeRepository.GetList(new RB_Distributor_Grade_Extend() { GradeIds = gradeIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                //查询推荐人列表
                string tjrIds = string.Join(",", list.Where(x => x.SuperiorId > 0).Select(x => x.SuperiorId ?? 0).Distinct());
                List<RB_Member_User_Extend> UserList = new List<RB_Member_User_Extend>();
                if (!string.IsNullOrEmpty(tjrIds))
                {
                    UserList = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = tjrIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                //根据基础配置层级查询下级数量  暂放弃
                //var basmdoel = GetDistributorBasicsInfo(demodel.TenantId.ToString(), demodel.MallBaseId);
                //if (basmdoel != null && basmdoel.DistributorTier > 0) {
                string uids = string.Join(",", list.Select(x => x.UserId ?? 0));
                List<RB_Member_User_Extend> UserNum1List = member_UserRepository.GetDistributorReferralsNum(uids, tier: 1, tenantId: demodel.TenantId, mallBaseId: demodel.MallBaseId);//直接查询三级
                List<RB_Member_User_Extend> UserNum2List = member_UserRepository.GetDistributorReferralsNum(uids, tier: 2, tenantId: demodel.TenantId, mallBaseId: demodel.MallBaseId);//直接查询三级
                List<RB_Member_User_Extend> UserNum3List = member_UserRepository.GetDistributorReferralsNum(uids, tier: 3, tenantId: demodel.TenantId, mallBaseId: demodel.MallBaseId);//直接查询三级

                foreach (var item in list)
                {
                    if (item.GradeId == 0)
                    {
                        item.GradeName = "默认等级";
                    }
                    else if (item.GradeId > 0)
                    {
                        item.GradeName = GradeList.Where(x => x.Id == item.GradeId).FirstOrDefault()?.Name ?? "";
                    }
                    if (item.SuperiorId == 0)
                    {
                        item.SuperiorName = "总店";
                    }
                    else if (item.SuperiorId > 0)
                    {
                        item.SuperiorName = UserList.Where(x => x.Id == item.SuperiorId).FirstOrDefault()?.Name ?? "";
                    }
                    item.OneNum = 0;
                    if (UserNum1List.Any())
                    {
                        item.OneNum = UserNum1List.Where(x => x.SuperiorId == item.UserId).FirstOrDefault()?.ReferralsNum ?? 0;
                    }
                    item.TwoNum = 0;
                    if (UserNum1List.Any())
                    {
                        item.TwoNum = UserNum2List.Where(x => x.SuperiorId == item.UserId).FirstOrDefault()?.ReferralsNum ?? 0;
                    }
                    item.ThreeNum = 0;
                    if (UserNum1List.Any())
                    {
                        item.ThreeNum = UserNum3List.Where(x => x.SuperiorId == item.UserId).FirstOrDefault()?.ReferralsNum ?? 0;
                    }
                }

            }
            return list;
        }

        /// <summary>
        /// 获取分销提现实体
        /// </summary>
        /// <param name="remitId"></param>
        /// <returns></returns>
        public RB_Distributor_Remit_Extend GetDistributorEntity(int remitId)
        {
            return distributor_RemitRepository.GetEntity<RB_Distributor_Remit_Extend>(remitId);
        }

        /// <summary>
        /// 获取小程序信息
        /// </summary>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_MiniProgram_Extend GetMiniProgramExtend(int mallBaseId)
        {
            return miniProgramRepository.GetEntity<RB_MiniProgram_Extend>(mallBaseId);
        }

        /// <summary>
        /// 分销提现审核
        /// </summary>
        /// <param name="remitId"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="erpEmpId"></param>
        /// <returns></returns>
        public string SetDistributorRemitAudit(int remitId, int type, string remark, string uid, int mallBaseId, int erpEmpId)
        {
            if (type == 1)
            {

                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_Remit.AuditStatus), (int)Common.Enum.User.DistributorRemitAuditStatusEnum.ToPlayWith},
                    { nameof(RB_Distributor_Remit.AuditDate), DateTime.Now},
                    { nameof(RB_Distributor_Remit.AuditRemark), remark},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_Distributor_Remit.Id),
                            FiledValue=remitId,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = distributor_RemitRepository.Update(keyValues, wheres);
                if (flag && uid == "1")
                {
                    #region 写入提现订单
                    var remitModel = distributor_RemitRepository.GetEntity(remitId);
                    if (remitModel.TenantId == 1 && string.IsNullOrEmpty(remitModel.ReOrderIds))
                    {
                        //所有未提现的 返佣
                        var clist = goods_OrderCommissionRepository.GetUserCommissionRemit(remitModel.UserId ?? 0);
                        if (clist.Any())
                        {
                            //获取订单列表
                            string OrderIds = string.Join(",", clist.Select(x => x.OrderId).Distinct());
                            var olist = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { OrderIds = OrderIds });
                            olist = olist.OrderByDescending(x => x.CreateDate).ToList();
                            List<int> OrderIdList = new List<int>();
                            string OrderNos = "";
                            decimal TMoney = (remitModel.AppliedMoney ?? 0);
                            //开始递减金额   订单不足的  给与提示
                            foreach (var item in olist)
                            {
                                if (TMoney > 0)
                                {
                                    decimal CommMoney = 0;
                                    var chlist = clist.Where(x => x.OrderId == item.OrderId).ToList();
                                    foreach (var qitem in chlist)
                                    {
                                        TMoney -= (qitem.Commission ?? 0);
                                        CommMoney += (qitem.Commission ?? 0);
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_OrderCommission_Extend.IsRemit),1}
                                    };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Goods_OrderCommission_Extend.Id),
                                              FiledValue=qitem.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                        goods_OrderCommissionRepository.Update(keyValues2, wheres2);
                                    }
                                    OrderNos += "\"" + item.OrderNo + "\"：" + CommMoney + "元，";
                                    OrderIdList.Add(item.OrderId);
                                }
                            }
                            if (!string.IsNullOrEmpty(OrderNos))
                            {
                                OrderNos = OrderNos[0..^1];
                            }
                            if (TMoney > 0)
                            {
                                OrderNos += "  余额" + TMoney + "尚未找到相关订单";
                            }

                            if (!string.IsNullOrEmpty(OrderNos))
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Distributor_Remit_Extend.ReOrderNos),OrderNos},
                                { nameof(RB_Distributor_Remit_Extend.ReOrderIds),JsonConvert.SerializeObject(OrderIdList)},
                            };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Distributor_Remit_Extend.Id),
                                      FiledValue=remitId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                                distributor_RemitRepository.Update(keyValues1, wheres1);
                            }
                        }
                    }
                    #endregion

                    //提现审核通过  自动生成财务单据
                    OrderIncomeFinanceModule(remitId, Convert.ToInt32(uid), mallBaseId, remark, erpEmpId);
                }
            }
            else if (type == 2)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_Remit.AuditStatus), (int)Common.Enum.User.DistributorRemitAuditStatusEnum.HaveMoney},
                    { nameof(RB_Distributor_Remit.RemitDate), DateTime.Now},
                    { nameof(RB_Distributor_Remit.RemitRemark), remark},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_Distributor_Remit.Id),
                            FiledValue=remitId,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = distributor_RemitRepository.Update(keyValues, wheres);
                if (flag)
                {
                    var remodel = distributor_RemitRepository.GetEntity<RB_Distributor_Remit_Extend>(remitId);
                    if (remodel.WithdrawalWay == DistrbutorWithdrawWayEnum.YETX)
                    {
                        var umodel = member_UserRepository.GetEntity(remodel.UserId);
                        if (umodel != null)
                        {
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User.Balance),(umodel.Balance??0)+(remodel.RemitMoney??0)}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Member_User.Id),
                                      FiledValue=umodel.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            bool flag1 = member_UserRepository.Update(keyValues1, wheres1);
                            if (flag1)
                            {
                                //插入余额明细
                                member_BalanceRepository.Insert(new RB_Member_Balance()
                                {
                                    Id = 0,
                                    Balance = (remodel.RemitMoney ?? 0),
                                    CreateDate = DateTime.Now,
                                    Description = "",
                                    Image = 0,
                                    MallBaseId = umodel.MallBaseId,
                                    PlatformType = umodel.Source,
                                    Remarks = "分销佣金提现转入余额,RemitId:" + remodel.Id,
                                    TenantId = umodel.TenantId,
                                    Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                                    UserId = umodel.Id
                                });
                            }
                        }
                    }
                }
            }
            else if (type == 3)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_Remit.AuditStatus), (int)Common.Enum.User.DistributorRemitAuditStatusEnum.Reject},
                    { nameof(RB_Distributor_Remit.RejectDate), DateTime.Now},
                    { nameof(RB_Distributor_Remit.RejectRemark), remark},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_Distributor_Remit.Id),
                            FiledValue=remitId,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = distributor_RemitRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //拒绝之后  需回滚提现佣金
                    var remodel = distributor_RemitRepository.GetEntity(remitId);
                    var dmodel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = remodel.UserId, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId }).FirstOrDefault();
                    if (dmodel != null)
                    {
                        #region 回滚提现金额
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Info.CommissionWithdrawal), (dmodel.CommissionWithdrawal ?? 0) + (remodel.AppliedMoney??0)}
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Distributor_Info.Id),
                                  FiledValue=dmodel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        distributor_InfoRepository.Update(keyValues1, wheres1);
                        #endregion

                        #region 回滚佣金已提现字段
                        try
                        {
                            if (!string.IsNullOrEmpty(remodel.ReOrderNos) && !string.IsNullOrEmpty(remodel.ReOrderIds))
                            {
                                List<int> OrderIdList = JsonConvert.DeserializeObject<List<int>>(remodel.ReOrderIds);
                                if (OrderIdList.Any())
                                {
                                    var oclist = goods_OrderCommissionRepository.GetUserCommissionRemitedList(remodel.UserId ?? 0, string.Join(",", OrderIdList));
                                    foreach (var qitem in oclist)
                                    {
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_OrderCommission_Extend.IsRemit),0}
                                        };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_Goods_OrderCommission_Extend.Id),
                                                  FiledValue=qitem.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        goods_OrderCommissionRepository.Update(keyValues2, wheres2);
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(remodel.ReOrderNos) && !string.IsNullOrEmpty(remodel.ReVipIds))
                            {
                                List<int> VipIdList = JsonConvert.DeserializeObject<List<int>>(remodel.ReVipIds);
                                if (VipIdList.Any())
                                {
                                    var oclist = vipBuy_CommissionRepository.GetList(new RB_VipBuy_Commission_Extend() { UserId = remodel.UserId, VipIds = string.Join(",", VipIdList) });
                                    foreach (var qitem in oclist)
                                    {
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_VipBuy_Commission_Extend.IsRemit),0}
                                        };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_VipBuy_Commission_Extend.Id),
                                                  FiledValue=qitem.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        vipBuy_CommissionRepository.Update(keyValues2, wheres2);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "SetDistributorRemitAudit回滚返佣字段失败");
                        }
                        #endregion
                    }

                }
            }
            else
            {
                return "type有误，请核实后再试";
            }
            return "";
        }

        /// <summary>
        /// 生成提现单据
        /// </summary>
        /// <returns></returns>
        public bool OrderIncomeFinanceModule(int remitId, int TenantId, int MallBaseId, string remark, int erpEmpId)
        {
            var flag = false;
            try
            {
                var remitModel = distributor_RemitRepository.GetEntity(remitId);
                if (remitModel == null)
                {
                    return false;
                }
                decimal Money = (remitModel.AppliedMoney ?? 0) - (remitModel.Fee ?? 0);
                //查询用户
                var umodel = member_UserRepository.GetEntity(remitModel.UserId);
                if (umodel == null) { return false; }
                //查询分销商
                var DisModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = remitModel.UserId, TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
                if (DisModel == null) { return false; }
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new Model.Extend.Finance.RB_Finance_Configurine_Extend { Type = 4 });

                //根据规则中的小程序，查询订单详情信息
                string dstr = "";
                if (remitModel.Fee > 0)
                {
                    dstr = "申请:" + (remitModel.AppliedMoney ?? 0) + "金额，手续费:" + (remitModel.Fee ?? 0) + "，实际打款:" + Money;
                }
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    var item = financeConfigurineList.FirstOrDefault();
                    var detailList = new List<object>() {
                        new
                        {
                            CostTypeId = item.RemitCostTypeId,
                            Number = 1,
                            OriginalMoney = Money,
                            UnitPrice = Money,
                            Remark = "订单号："+(remitModel?.ReOrderNos ?? "暂无")+"  " + dstr
                        }
                    };
                    item.IsPublic = 5;//默认平台虚拟账户
                    #region 查询所有的订单
                    List<Model.Entity.Finance.RB_ECFinanceId_Relation> ECList = new List<Model.Entity.Finance.RB_ECFinanceId_Relation>();
                    if (!string.IsNullOrEmpty(remitModel.ReOrderIds) || !string.IsNullOrEmpty(remitModel.ReVipIds))
                    {
                        if (string.IsNullOrEmpty(remitModel.ReOrderIds)) { remitModel.ReOrderIds = "[]"; }
                        if (string.IsNullOrEmpty(remitModel.ReVipIds)) { remitModel.ReVipIds = "[]"; }
                        List<int> reorderIdList = JsonConvert.DeserializeObject<List<int>>(remitModel.ReOrderIds);
                        List<int> revipIdList = JsonConvert.DeserializeObject<List<int>>(remitModel.ReVipIds);
                        if (revipIdList.Any())
                        {
                            var vipbuycList = vipBuy_CommissionRepository.GetList(new RB_VipBuy_Commission_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, VipIds = string.Join(",", revipIdList) });
                            //获取订单列表
                            if (vipbuycList.Where(x => x.ReOrderId > 0).Any())
                            {
                                reorderIdList.AddRange(vipbuycList.Where(x => x.ReOrderId > 0).Select(x => x.ReOrderId ?? 0).ToList());
                            }
                        }
                        if (reorderIdList.Any())
                        {
                            reorderIdList = reorderIdList.Distinct().ToList();
                            var orderDetailList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, OrderIds = string.Join(",", reorderIdList) });
                            foreach (var qitem in orderDetailList)
                            {
                                ECList.Add(new Model.Entity.Finance.RB_ECFinanceId_Relation()
                                {
                                    ECOrderId = qitem.OrderId,
                                    ECOrderDetailId = qitem.Id
                                });
                            }
                        }
                    }
                    #endregion
                    var financeObj = new
                    {
                        CreateBy = erpEmpId > 0 ? erpEmpId.ToString() : Config.ExpendDirector,
                        item.IsPublic,
                        ClientType = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["RemitTypeId"]),
                        ClientID = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["RemitAccountId"]),
                        item.CurrencyId,
                        WBMoney = Money,
                        PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                        RB_Branch_Id = Config.ExpendBranchId,
                        TemplateId = item.WorkFlowId,
                        OrderSource = 16,
                        OtherType = 11,
                        ReFinanceId = remitId,
                        Remark = "名称:" + umodel.Name + "（" + umodel.Id + "）" + "  姓名:" + DisModel.Name + "  手机:" + DisModel.Mobile + "   " + System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                        detailList,
                        RB_Depart_Id = Config.ExpendDepartment,
                        ECOrderList = ECList
                    };
                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                    var resultInfo = new
                    {
                        msg = sign
                    };

                    string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.PaymentFinanceApi, JsonHelper.Serialize(resultInfo), "");
                    var apir = JsonConvert.DeserializeObject<ApiResult>(apiResult);
                    LogHelper.WriteInfo("打款：" + apiResult);
                    if (apir.resultCode == 1)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Remit.FinanceId), Convert.ToInt32(apir.data.ToString())},
                            { nameof(RB_Distributor_Remit.AuditRemark), remark+"  自动生成财务单据:"+apir.data.ToString()},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_Distributor_Remit.Id),
                                    FiledValue=remitId,
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        distributor_RemitRepository.Update(keyValues, wheres);
                    }
                    else
                    {
                        //记录自动生成失败，需手动新增财务单据
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Remit.AuditRemark), remark+"  自动生成财务单据失败，请手动添加财务单据！"},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_Distributor_Remit.Id),
                                    FiledValue=remitId,
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        distributor_RemitRepository.Update(keyValues, wheres);
                    }
                }
            }
            catch (Exception ex)
            {

                LogHelper.Write(ex);
            }

            return flag;
        }

        /// <summary>
        /// 推荐生成提现单据
        /// </summary>
        /// <returns></returns>
        public bool OrderIncomeFinanceModuleForRecommend(int UserId, int BillId, List<RB_Goods_OrderIntroduction_Extend> list, int TenantId, int MallBaseId)
        {
            var flag = false;
            try
            {
                decimal Money = list.Sum(x => x.Commission ?? 0);
                //查询用户
                var umodel = member_UserRepository.GetEntity(UserId);
                if (umodel == null) { return false; }
                //查询分销商
                var DisModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = UserId, TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
                if (DisModel == null) { return false; }
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new Model.Extend.Finance.RB_Finance_Configurine_Extend { Type = 4 });

                //根据规则中的小程序，查询订单详情信息
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    var item = financeConfigurineList.FirstOrDefault();
                    var detailList = new List<object>();
                    var OrderNoList = list.Select(x => x.OrderNo).Distinct().ToList();
                    foreach (var qitem in OrderNoList)
                    {
                        var NoList = list.Where(x => x.OrderNo == qitem).ToList();
                        decimal unitmoney = NoList.Sum(x => x.Commission ?? 0);
                        detailList.Add(new
                        {
                            CostTypeId = item.RemitCostTypeId,
                            Number = 1,
                            OriginalMoney = unitmoney,
                            UnitPrice = unitmoney,
                            Remark = "推荐返佣：" + (qitem == "" ? "暂无" : qitem)
                        });
                    }
                    item.IsPublic = 5;//默认平台虚拟账户
                    #region 查询所有的订单
                    List<Model.Entity.Finance.RB_ECFinanceId_Relation> ECList = new List<Model.Entity.Finance.RB_ECFinanceId_Relation>();
                    foreach (var qitem in list)
                    {
                        ECList.Add(new Model.Entity.Finance.RB_ECFinanceId_Relation()
                        {
                            ECOrderId = qitem.OrderId,
                            ECOrderDetailId = qitem.OrderDetailId
                        });
                    }
                    #endregion
                    var financeObj = new
                    {
                        CreateBy = Config.ExpendDirector,
                        item.IsPublic,
                        ClientType = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["RemitTypeId"]),
                        ClientID = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["RemitAccountId"]),
                        item.CurrencyId,
                        WBMoney = Money,
                        PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                        RB_Branch_Id = Config.ExpendBranchId,
                        TemplateId = item.WorkFlowId,
                        OrderSource = 16,
                        OtherType = 18,
                        ReFinanceId = BillId,
                        Remark = "名称:" + umodel.Name + "（" + umodel.Id + "）" + "  姓名:" + DisModel.Name + "  手机:" + DisModel.Mobile + "   " + System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据(推荐供应商返佣)",
                        detailList,
                        RB_Depart_Id = Config.ExpendDepartment,
                        ECOrderList = ECList
                    };
                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                    var resultInfo = new
                    {
                        msg = sign
                    };

                    string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.PaymentFinanceApi, JsonHelper.Serialize(resultInfo), "");
                    var apir = JsonConvert.DeserializeObject<ApiResult>(apiResult);
                    if (apir.resultCode == 1)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Bill.FinanceId), Convert.ToInt32(apir.data.ToString())},
                            { nameof(RB_Distributor_Bill.Remark), "自动生成财务单据:"+apir.data.ToString()},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_Distributor_Remit.Id),
                                    FiledValue=BillId,
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        distributor_BillRepository.Update(keyValues, wheres);
                    }
                    else
                    {
                        //记录自动生成失败，需手动新增财务单据
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Distributor_Bill.Remark), "自动生成财务单据失败，请手动添加财务单据！"},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_Distributor_Remit.Id),
                                    FiledValue=BillId,
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        distributor_BillRepository.Update(keyValues, wheres);
                    }
                }
            }
            catch (Exception ex)
            {

                LogHelper.Write(ex);
            }

            return flag;
        }

        /// <summary>
        /// 设置打款备注
        /// </summary>
        /// <param name="remitId"></param>
        /// <param name="remark"></param>        
        /// <returns></returns>
        public bool SetDistributorRemitRemark(int remitId, string remark)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_Remit.RemitRemark),remark},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_Remit.Id),
                        FiledValue=remitId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return distributor_RemitRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 分销提现列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Remit_Extend> GetDistributorRemitList(RB_Distributor_Remit_Extend demodel)
        {
            return distributor_RemitRepository.GetDistributorRemitList(demodel);
        }

        /// <summary>
        /// 分销提现申请
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetDistributorRemitInfo(RB_Distributor_Remit_Extend demodel)
        {
            var dmodel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = demodel.UserId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if (dmodel == null || dmodel.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Audited && dmodel.Status == 1)
            {
                return "分销商不存在或者分销商未审核通过";
            }
            if ((dmodel.CommissionWithdrawal ?? 0) < demodel.AppliedMoney)
            {
                return "分销商剩余可提现佣金金额不足";
            }
            bool flag = distributor_RemitRepository.Insert(demodel) > 0;
            if (flag)
            {
                //扣除分销可提现佣金
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_Info.CommissionWithdrawal), (dmodel.CommissionWithdrawal ?? 0) - (demodel.AppliedMoney??0)}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Distributor_Info.Id),
                          FiledValue=dmodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                distributor_InfoRepository.Update(keyValues, wheres);
            }
            return flag ? "" : "操作失败";
        }

        /// <summary>
        /// 后台修改分销商可提现佣金
        /// </summary>
        /// <param name="distributorId"></param>
        /// <param name="money"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public bool SetDistributorCommission(int distributorId, decimal money, string uid, int mallBaseId, int empId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_Info.CommissionWithdrawal),money}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Distributor_Info.Id),
                      FiledValue=distributorId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = distributor_InfoRepository.Update(keyValues, wheres);
            if (flag)
            {
                //记录日志
                distributor_LogRepository.Insert(new RB_Distributor_Log()
                {
                    Content = "修改分销商佣金为：" + money,
                    CreateDate = DateTime.Now,
                    EmpId = empId,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    TenantId = Convert.ToInt32(uid),
                    Type = 1,
                    UserId = distributorId
                });
            }
            return flag;
        }

        #endregion

        #region 收货地址

        /// <summary>
        /// 收货地址分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Member_ShippingAddress_Extend> GetUserShippingAddressPageList(int pageIndex, int pageSize, out long count, RB_Member_ShippingAddress_Extend demodel)
        {
            var list = member_ShippingAddressRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string areaIds1 = string.Join(",", list.Select(x => x.Province ?? 0).Distinct());
                string areaIds2 = string.Join(",", list.Select(x => x.City ?? 0).Distinct());
                string areaIds3 = string.Join(",", list.Select(x => x.District ?? 0).Distinct());
                string areaIds = "0";
                if (!string.IsNullOrEmpty(areaIds1))
                {
                    areaIds += "," + areaIds1;
                }
                if (!string.IsNullOrEmpty(areaIds2))
                {
                    areaIds += "," + areaIds2;
                }
                if (!string.IsNullOrEmpty(areaIds3))
                {
                    areaIds += "," + areaIds3;
                }
                var arealist = destinationRepository.GetDictvalueListForIds(areaIds);
                foreach (var item in list)
                {
                    item.DistrictAddress = (arealist.Where(x => x.ID == item.Province).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == item.City).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == item.District).FirstOrDefault()?.Name ?? "");
                }
            }
            return list;
        }

        /// <summary>
        /// 收货地址列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Member_ShippingAddress_Extend> GetUserShippingAddressList(RB_Member_ShippingAddress_Extend demodel)
        {
            var list = member_ShippingAddressRepository.GetList(demodel);
            if (list.Any())
            {
                string areaIds1 = string.Join(",", list.Select(x => x.Province ?? 0).Distinct());
                string areaIds2 = string.Join(",", list.Select(x => x.City ?? 0).Distinct());
                string areaIds3 = string.Join(",", list.Select(x => x.District ?? 0).Distinct());
                string areaIds = "0";
                if (!string.IsNullOrEmpty(areaIds1))
                {
                    areaIds += "," + areaIds1;
                }
                if (!string.IsNullOrEmpty(areaIds2))
                {
                    areaIds += "," + areaIds2;
                }
                if (!string.IsNullOrEmpty(areaIds3))
                {
                    areaIds += "," + areaIds3;
                }
                var arealist = destinationRepository.GetDictvalueListForIds(areaIds);
                foreach (var item in list)
                {
                    item.DistrictAddress = (arealist.Where(x => x.ID == item.Province).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == item.City).FirstOrDefault()?.Name ?? "") + " " + (arealist.Where(x => x.ID == item.District).FirstOrDefault()?.Name ?? "");
                }
            }
            return list;
        }

        /// <summary>
        /// 获取收货地址详情
        /// </summary>
        /// <param name="addressId"></param>
        /// <returns></returns>
        public RB_Member_ShippingAddress_Extend GetUserShippingAddressInfo(int addressId)
        {
            var model = member_ShippingAddressRepository.GetEntity<RB_Member_ShippingAddress_Extend>(addressId);
            model.DistrictAddress = (destinationRepository.GetEntity(model.Province)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.City)?.Name ?? "") + " " + (destinationRepository.GetEntity(model.District)?.Name ?? "");
            return model;
        }

        /// <summary>
        /// 新增修改
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetUserShippingAddress(RB_Member_ShippingAddress_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Member_ShippingAddress.Name),demodel.Name},
                    { nameof(RB_Member_ShippingAddress.Mobile),demodel.Mobile},
                    { nameof(RB_Member_ShippingAddress.Country),demodel.Country},
                    { nameof(RB_Member_ShippingAddress.Province),demodel.Province},
                    { nameof(RB_Member_ShippingAddress.City),demodel.City},
                    { nameof(RB_Member_ShippingAddress.District),demodel.District},
                    { nameof(RB_Member_ShippingAddress.Address),demodel.Address},
                    { nameof(RB_Member_ShippingAddress.UpdateDate),demodel.UpdateDate}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper{
                         FiledName=nameof(RB_Member_ShippingAddress.TenantId),
                          FiledValue=demodel.TenantId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper{
                         FiledName=nameof(RB_Member_ShippingAddress.MallBaseId),
                          FiledValue=demodel.MallBaseId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper{
                         FiledName=nameof(RB_Member_ShippingAddress.UserId),
                          FiledValue=demodel.UserId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper{
                         FiledName=nameof(RB_Member_ShippingAddress.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return member_ShippingAddressRepository.Update(keyValues, wheres);
            }
            else
            {
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper{
                         FiledName=nameof(RB_Member_ShippingAddress.TenantId),
                          FiledValue=demodel.TenantId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper{
                         FiledName=nameof(RB_Member_ShippingAddress.MallBaseId),
                          FiledValue=demodel.MallBaseId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper{
                         FiledName=nameof(RB_Member_ShippingAddress.UserId),
                          FiledValue=demodel.UserId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                };
                if (!member_ShippingAddressRepository.Exists(wheres))
                {
                    demodel.IsDefault = 1;
                }
                return member_ShippingAddressRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 设置默认
        /// </summary>
        /// <param name="addressId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool SetUserShippingAddressDefault(int addressId, int userId)
        {
            var addmodel = member_ShippingAddressRepository.GetEntity(addressId);
            int oldId = 0;
            if (addmodel.IsDefault != 1)
            {
                var defmodel = member_ShippingAddressRepository.GetList(new RB_Member_ShippingAddress_Extend() { UserId = userId, IsDefault = 1 }).FirstOrDefault();
                oldId = defmodel?.Id ?? 0;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Member_ShippingAddress.IsDefault),addmodel.IsDefault==1?2:1},
                { nameof(RB_Member_ShippingAddress.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper{
                        FiledName=nameof(RB_Member_ShippingAddress.UserId),
                        FiledValue=userId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper{
                        FiledName=nameof(RB_Member_ShippingAddress.Id),
                        FiledValue=addressId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = member_ShippingAddressRepository.Update(keyValues, wheres);
            if (flag)
            {
                //获取当前默认
                if (addmodel.IsDefault != 1 && oldId > 0)
                {
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                        { nameof(RB_Member_ShippingAddress.IsDefault),2},
                        { nameof(RB_Member_ShippingAddress.UpdateDate),DateTime.Now}
                    };
                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                        new WhereHelper{
                                FiledName=nameof(RB_Member_ShippingAddress.UserId),
                                FiledValue=userId,
                                OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper{
                                FiledName=nameof(RB_Member_ShippingAddress.Id),
                                FiledValue=oldId,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    member_ShippingAddressRepository.Update(keyValues1, wheres1);
                }
            }
            return flag;
        }

        /// <summary>
        /// 删除地址
        /// </summary>
        /// <param name="addressId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool DelUserShippingAddressDefault(int addressId, int userId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Member_ShippingAddress.Status),1},
                { nameof(RB_Member_ShippingAddress.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper{
                        FiledName=nameof(RB_Member_ShippingAddress.UserId),
                        FiledValue=userId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper{
                        FiledName=nameof(RB_Member_ShippingAddress.Id),
                        FiledValue=addressId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return member_ShippingAddressRepository.Update(keyValues, wheres);
        }


        #region 地址

        /// <summary>
        /// 根据地区名称获取地区列表
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<Model.Extend.BaseSetUp.RB_Destination_Extend> GetDestinationListByNames(string[] where)
        {
            return destinationRepository.GetListByNames(where);
        }
        #endregion

        #endregion

        #region 收藏商品

        /// <summary>
        /// 获取用户收藏商品分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetUserCollectionPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetMemberCollectGoodsPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                foreach (var item in list)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 设置用户收藏商品
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetUserCollectionInfo(int goodsId, int userId, int tenantId, int mallBaseId)
        {
            bool flag = true;
            var list = member_CollectionRepository.GetList(new RB_Member_Collection_Extend() { UserId = userId, GoodsId = goodsId, TenantId = tenantId, MallBaseId = mallBaseId });
            if (list.Any())
            {
                //取消收藏
                foreach (var item in list)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Member_Collection.Status),1},
                        { nameof(RB_Member_Collection.UpdateDate),DateTime.Now}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Member_Collection.Id),
                              FiledValue=item.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    flag = member_CollectionRepository.Update(keyValues, wheres);
                }
            }
            else
            {
                //新增收藏
                flag = member_CollectionRepository.Insert(new RB_Member_Collection()
                {
                    CreateDate = DateTime.Now,
                    GoodsId = goodsId,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    Status = 0,
                    TenantId = tenantId,
                    Type = 1,
                    UpdateDate = DateTime.Now,
                    UserId = userId
                }) > 0;
            }
            return flag;
        }

        #endregion

        #region 分销中心


        /// <summary>
        /// 验证分销商
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetUserDistrbutorStatus(int userId, int tenantId, int mallBaseId)
        {
            var model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (model == null)
            {
                var basicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                bool flag = true;
                if (basicsModel.DistributorCondition == DistributorConditionEnum.GMSP)
                {
                    //验证购买商品
                    List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.UserId),
                              FiledValue=userId,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.TenantId),
                              FiledValue=tenantId,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.MallBaseId),
                              FiledValue=mallBaseId,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.Recycled),
                              FiledValue=2,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.Status),
                              FiledValue=0,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods_Order_Extend.OrderStatus),
                              FiledValue="2,3,4,5,6",
                               OperatorEnum=OperatorEnum.IN
                        },
                    };
                    flag = goods_OrderRepository.Exists(whereHelpers);
                }
                else if (basicsModel.DistributorCondition == DistributorConditionEnum.DCXF)
                {
                    //单次消费   充值也算  (货到付款这种怎么处理)

                }
                if (flag)
                {
                    return new
                    {
                        Status = 1,
                        Msg = "未申请成为分销商",
                        basicsModel.ApplyFor,
                        ApplyForName = basicsModel.ApplyFor.GetEnumName()
                    };
                }
                else
                {
                    return new
                    {
                        Status = 0,
                        Msg = "未满足申请成为分销商条件：" + basicsModel.DistributorCondition.GetEnumName()
                    };
                }
            }
            if (model.AuditStatus == Common.Enum.User.DistributorAuditStatusEnum.Reject)
            {
                return new
                {
                    Status = 4,
                    Msg = "申请已被拒绝"
                };
            }
            else if (model.AuditStatus == Common.Enum.User.DistributorAuditStatusEnum.Auditing)
            {
                return new
                {
                    Status = 2,
                    Msg = "正在审核中"
                };
            }
            else if (model.AuditStatus == Common.Enum.User.DistributorAuditStatusEnum.Audited)
            {
                return new
                {
                    Status = 3,
                    Msg = "已是分销商"
                };
            }
            return new
            {
                Status = 0,
                Msg = ""
            };
        }

        /// <summary>
        /// 获取用户申请分销商页面信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetUserApplyForDistrbutorInfo(int userId, int tenantId, int mallBaseId)
        {
            int SuperiorId = 0;
            string SuperiorName = "总店";
            var umodel = member_UserRepository.GetEntity(userId);
            if (umodel.SuperiorId > 0)
            {
                SuperiorId = umodel.SuperiorId ?? 0;
                var upmodel = member_UserRepository.GetEntity(umodel.SuperiorId ?? 0);
                SuperiorName = upmodel?.Name ?? "";
            }
            else if (umodel.SuperiorId == 0 && umodel.IsBeDownline == 2 && umodel.WaitSuperiorId > 0)
            {
                SuperiorId = umodel.WaitSuperiorId ?? 0;
                var upmodel = member_UserRepository.GetEntity(umodel.WaitSuperiorId ?? 0);
                SuperiorName = upmodel?.Name ?? "";
            }
            var CustomModel = distributor_CustomRepository.GetList(new RB_Distributor_Custom_Extend() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (CustomModel == null)
            {
                return "";
            }

            var basicModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (basicModel == null)
            {
                return "";
            }
            List<string> template_message_list = new List<string>();
            var minModel = miniProgramRepository.GetEntity(mallBaseId);
            if (minModel != null)
            {

                if (!string.IsNullOrWhiteSpace(minModel.AuditResultTpl))
                {
                    template_message_list.Add(minModel.AuditResultTpl);
                }
            }

            return new
            {
                template_message_list,
                CustomModel = new
                {
                    CustomModel.HeadImage,
                    CustomModel.BottomImage,
                    CustomModel.DistributionApplication,
                    CustomModel.ApplicationAgreement,
                    CustomModel.ButtonFilletPX,
                    CustomModel.ButtonText,
                    CustomModel.ButtonColor,
                    CustomModel.ButtonTextColor,
                    basicModel.ApplicationProtocol
                },
                ApplyForInfo = new
                {
                    SuperiorId,
                    SuperiorName
                }
            };
        }

        /// <summary>
        /// 申请成为分销商
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetUserApplyForBeDistrbutor(RB_Distributor_Info_Extend demodel)
        {
            var model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = demodel.UserId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if (model != null)
            {
                return false;
            }
            return distributor_InfoRepository.Insert(demodel) > 0;
        }

        /// <summary>
        /// 获取用户分销中心
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetDistrbutorCenter(AppletUserInfo userInfo)
        {
            var basicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            var model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return "分销商不存在";
            }
            if (model.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Audited)
            {
                return "分销商不存在";
            }

            //分销商等级
            string GradeName = "默认等级";
            int HpEnabled = 2;
            int IsVip = 2;
            string Icon = "";
            if ((basicsModel?.IsEnableFXGrade ?? 0) == 1)
            {
                var gmodel = distributor_FXGradeRepository.GetEntity((model.FXGradeId ?? 0));
                Icon = gmodel.Icon ?? "";
                GradeName = gmodel?.GradeName ?? "默认等级";
                if ((gmodel?.IsGuest ?? 0) == 3)
                {
                    IsVip = 1;
                }
            }
            else
            {
                HpEnabled = GetHpDistributorIsEnabled(userInfo.TenantId, userInfo.MallBaseId);
                if (HpEnabled == 1)
                {
                    if (model.HPGradeId > 0)
                    {
                        var gmodel = distributor_HPGradeInfoRepository.GetEntity((model.HPGradeId ?? 0));
                        GradeName = gmodel?.GradeName ?? "";
                    }
                }
                else
                {
                    if (model.GradeId > 0)
                    {
                        var gmodel = distributor_GradeRepository.GetEntity((model.GradeId ?? 0));
                        GradeName = gmodel?.Name ?? "默认等级";
                    }
                }
            }

            //已提现佣金 //未结算佣金
            var commModel = distributor_RemitRepository.GetDistributorCommissionStatiscs(userInfo.UserId);
            //提现总额
            var remitMoney = distributor_RemitRepository.GetDistributorRemitCommission(userInfo.UserId);

            //分销订单
            decimal OrderCommission = goods_OrderCommissionRepository.GetUserOrderCommissionStatistics(userInfo.UserId);
            //未结算返佣
            decimal WJSCommission = goods_OrderCommissionRepository.GetUserOrderCommissionNoSettlement(userInfo.UserId);

            int SuperiorId = 0;
            string SuperiorName = "";
            var umodel = member_UserRepository.GetEntity(userInfo.UserId);
            if (umodel.SuperiorId > 0)
            {
                SuperiorId = umodel.SuperiorId ?? 0;
                var upmodel = member_UserRepository.GetEntity(umodel.SuperiorId ?? 0);
                SuperiorName = upmodel?.Name ?? "";
            }
            //下线数量
            int oneNum = 0, twoNum = 0, threeNum = 0, fxNum = 0;
            if ((basicsModel?.IsEnableFXGrade ?? 0) == 1)
            {
                //求其所有下线的数量
                var UserIds = member_UserRepository.GetMemberChildIdStr(umodel.Id);
                if (!string.IsNullOrEmpty(UserIds))
                {
                    string[] arr = UserIds.Split(',');
                    fxNum = arr.Length - 1;
                }
            }
            else
            {
                oneNum = member_UserRepository.GetDistributorReferralsNumTwo(umodel.Id, 1, userInfo.TenantId, userInfo.MallBaseId);
                twoNum = member_UserRepository.GetDistributorReferralsNumTwo(umodel.Id, 2, userInfo.TenantId, userInfo.MallBaseId);
                threeNum = member_UserRepository.GetDistributorReferralsNumTwo(umodel.Id, 3, userInfo.TenantId, userInfo.MallBaseId);
            }

            //Vip购买返佣金额
            decimal VipBuyCommission = vipBuy_CommissionRepository.getVipBuyCommissionMoney(userInfo.UserId);

            var CustomModel = distributor_CustomRepository.GetList(new RB_Distributor_Custom_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (CustomModel == null)
            {
                return "";
            }
            return new
            {
                CustomModel = new
                {
                    CustomModel.DistributionCommissionName,
                    CustomModel.DistributionCommissionImage,
                    CustomModel.DistributionOrderName,
                    CustomModel.DistributionOrderImage,
                    CustomModel.WithdrawDetialsName,
                    CustomModel.WithdrawDetialsImage,
                    CustomModel.MyTeamName,
                    CustomModel.MyTeamImage,
                    CustomModel.PromoteQRCodeName,
                    CustomModel.PromoteQRCodeImage,
                    CustomModel.ReferrerName,
                    CustomModel.CommissionForWithdrawalName,
                    CustomModel.WithdrawDepositName,
                    CustomModel.CommissionWithdrawnName,
                    CustomModel.OutstandingCommissionName,
                    CustomModel.DistributorName,
                },
                UserInfo = new
                {
                    UserId = umodel.Id,
                    UserName = umodel.Name,
                    umodel.Photo,
                    GradeName,
                    GradeIcon = Icon,
                    SuperiorId,
                    SuperiorName,
                    DistributorGradeEntrance = HpEnabled == 1 ? 2 : (basicsModel?.GradeEntrance ?? 2),
                    HpReferralsGradeAudit = userInfo.TenantId == 1 ? 1 : HpEnabled == 1 ? (basicsModel?.HpReferralsGradeAudit ?? 2) : 2,
                    CommissionWithdrawal = model.CommissionWithdrawal ?? 0,
                    TXCommission = commModel?.TXCommission ?? 0,
                    WJSCommission,
                    model.TotalCommission,
                    OrderCommission,
                    RemitMoney = remitMoney,
                    ReferralsNum = (basicsModel?.IsEnableFXGrade ?? 0) == 1 ? fxNum : (oneNum + twoNum + threeNum),
                    IsEnableFXGrade = (basicsModel?.IsEnableFXGrade ?? 0),
                    IsVip,
                    VipExpiryDate = model.VipExpiryDate.HasValue ? model.VipExpiryDate.Value.ToString("yyyy-MM-dd") : "",
                    VipBuyCommission,

                }
            };
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetUserListExtModule(RB_Member_User_Extend dmodel)
        {
            return member_UserRepository.GetListExtRepository(dmodel);
        }

        /// <summary>
        /// 获取团队成员详情
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public object GetTeamUserInfoModule(int UserId)
        {
            var extModel = GetUserListExtModule(new RB_Member_User_Extend() { UserIds = UserId.ToString() })?.FirstOrDefault();
            List<RB_Member_User_Extend> totalList = new List<RB_Member_User_Extend>();
            //本月佣金
            List<RB_Member_User_Extend> currentMonthList = new List<RB_Member_User_Extend>();

            decimal totalCommission = 0;
            totalList = member_UserRepository.GetUserCommissionRepository(new RB_Member_User_Extend() { UserIds = UserId.ToString() });
            if (totalList != null && totalList.Count > 0)
            {
                totalCommission = totalList.Sum(qitem => qitem.Commission);
            }
            decimal currentCommission = 0;
            currentMonthList = member_UserRepository.GetUserCommissionRepository(new RB_Member_User_Extend() { UserIds = UserId.ToString() }, IsGetCurrentMonth: true);
            if (currentMonthList != null && currentMonthList.Count > 0)
            {
                currentCommission = currentMonthList.Sum(qitem => qitem.Commission);
            }
            string createDateStr = "";
            if (extModel != null && extModel.CreateDate != null)
            {
                createDateStr = Convert.ToDateTime(extModel.CreateDate).ToString("yyyy年MM月dd月");
            }
            var obj = new
            {
                extModel?.Name,
                extModel?.Photo,
                extModel?.Icon,
                createDateStr,
                totalCommission,
                currentCommission
            };
            return obj;
        }

        /// <summary>
        /// 获取分销商升级条件
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetDistrbutorUpgradeConditions(AppletUserInfo userInfo)
        {
            var model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (model == null || model.AuditStatus != DistributorAuditStatusEnum.Audited)
            {
                return new
                {
                    Status = 2,
                    GradeInfo = new { }
                };
            }
            var gmodel = distributor_GradeRepository.GetEntity(model.GradeId);
            var upgmodel = distributor_GradeRepository.GetDistrbutorUpgrade(gmodel?.Grade ?? 0, userInfo.TenantId, userInfo.MallBaseId);
            if (upgmodel == null || upgmodel.IsAutoUpGrade != 1)
            {
                return new
                {
                    Status = 2,
                    GradeInfo = new { }
                };
            }
            else
            {
                return new
                {
                    Status = 1,
                    GradeInfo = new
                    {
                        upgmodel.Id,
                        upgmodel.Grade,
                        upgmodel.Name,
                        upgmodel.UpGradeCondition,
                        UpGradeConditionName = upgmodel.UpGradeCondition.GetEnumName(),
                        upgmodel.ReferralsNumber,
                        upgmodel.TotalCommission,
                        upgmodel.CommissionWithdrawn,
                        upgmodel.DistributionCommissionType,
                        upgmodel.OneCommission,
                        upgmodel.TwoCommission,
                        upgmodel.ThreeCommission,
                        upgmodel.GradeExplain
                    }
                };
            }
        }

        /// <summary>
        /// 用户自行升级分销商等级
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetUserDistrbutorUpgrade(int gradeId, AppletUserInfo userInfo)
        {
            if (GetHpDistributorIsEnabled(userInfo.TenantId, userInfo.MallBaseId) == 2)
            {
                return "和平分销无法自动升级";
            }
            var model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (model == null || model.AuditStatus != DistributorAuditStatusEnum.Audited)
            {
                return "您不是分销商，无法操作";
            }
            var gmodel = distributor_GradeRepository.GetEntity(gradeId);
            if (gmodel == null)
            {
                return "该等级不存在，无法升级";
            }
            if (gmodel.IsAutoUpGrade != 1)
            {
                return "该等级不能自动升级";
            }

            if (gmodel.UpGradeCondition == DistrbutorGradeUpdateEnum.XXYHS)
            {
                //验证下线数量
                var xxModel = member_UserRepository.GetDistributorReferralsNum(userInfo.UserId.ToString(), 1, userInfo.TenantId, userInfo.MallBaseId).FirstOrDefault();
                if (xxModel == null)
                {
                    return "您当前下线数量为0，无法升级";
                }
                if ((xxModel.ReferralsNum ?? 0) < (gmodel.ReferralsNumber ?? 0))
                {
                    return "您当前下线数量为" + (xxModel.ReferralsNum ?? 0) + "，无法升级";
                }
            }
            else if (gmodel.UpGradeCondition == DistrbutorGradeUpdateEnum.LJYJ)
            {
                //验证累计佣金
                if ((model.TotalCommission ?? 0) < (gmodel.TotalCommission ?? 0))
                {
                    return "您当前累计佣金为" + (model.TotalCommission ?? 0) + ",无法升级";
                }
            }
            else if (gmodel.UpGradeCondition == DistrbutorGradeUpdateEnum.YTXYJ)
            {
                //验证已提现佣金
                //已提现佣金 //未结算佣金
                var commModel = distributor_RemitRepository.GetDistributorCommissionStatiscs(userInfo.UserId);
                if ((commModel?.TXCommission ?? 0) < (gmodel.CommissionWithdrawn ?? 0))
                {
                    return "您当前已提现佣金为" + (commModel?.TXCommission ?? 0) + "，无法升级";
                }
            }

            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_Info.GradeId),gradeId},
                { nameof(RB_Distributor_Info.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Distributor_Info.Id),
                      FiledValue=gradeId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = distributor_InfoRepository.Update(keyValues, wheres);
            if (flag)
            {
                return "";
            }
            return "升级失败，请联系管理员";
        }

        /// <summary>
        /// 获取提现余额
        /// </summary>
        /// <returns></returns>
        public object GetDistrbutorWithdrawDepositBalance(AppletUserInfo userInfo)
        {
            var basicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();

            decimal CanRemitMoney = -1;
            if (basicsModel.DailyWithdrawalLimit != -1)
            {
                //获取当日所有用户提现金额
                decimal RemitMoney = distributor_RemitRepository.GetAllUserToDayRemitMoney(userInfo.TenantId, userInfo.MallBaseId);
                CanRemitMoney = (basicsModel.DailyWithdrawalLimit ?? 0) - RemitMoney;
                CanRemitMoney = CanRemitMoney < 0 ? 0 : CanRemitMoney;
            }
            //提现方式
            List<int> WithdrawWayids = JsonConvert.DeserializeObject<List<int>>(basicsModel.WithdrawWay);
            var list = EnumHelper.GetEnumList(typeof(DistrbutorWithdrawWayEnum));
            var WayList = list.Where(x => WithdrawWayids.Contains(Convert.ToInt32(x.Value)));

            //获取订阅消息
            var miniModel = miniProgramRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();

            List<string> template_message_list = new List<string>();

            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.ReflectSuccessTpl))
                {
                    template_message_list.Add(miniModel.ReflectSuccessTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.ReflectFailTpl))
                {
                    template_message_list.Add(miniModel.ReflectFailTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.AuditResultTpl))
                {
                    template_message_list.Add(miniModel.AuditResultTpl);
                }
            }


            return new
            {
                template_message_list,
                disModel.CommissionWithdrawal,
                CanRemitMoney,
                basicsModel.MinimumWithdrawalLimit,
                basicsModel.WithdrawFee,
                basicsModel.IsWithdrawAll,
                WithdrawWayList = WayList.Select(x => new
                {
                    Id = Convert.ToInt32(x.Value),
                    Name = x.Key
                })
            };
        }

        /// <summary>
        /// 提现
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetDistrbutorWithdrawDeposit(RB_Distributor_Remit_Extend demodel)
        {
            //验证金额
            var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = demodel.UserId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if ((disModel.CommissionWithdrawal ?? 0) < (demodel.AppliedMoney ?? 0))
            {
                return "账户余额不足，请刷新后再试";
            }
            var basicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            //提现方式
            List<int> WithdrawWayids = JsonConvert.DeserializeObject<List<int>>(basicsModel.WithdrawWay);
            if (!WithdrawWayids.Contains((int)(demodel.WithdrawalWay ?? DistrbutorWithdrawWayEnum.ZDDK)))
            {
                return "提现方式不正确";
            }

            if (basicsModel.IsWithdrawAll == 1)
            {
                if ((disModel.CommissionWithdrawal ?? 0) != (demodel.AppliedMoney ?? 0))
                {
                    return "提现必须全额提现";
                }
            }
            if (basicsModel.DailyWithdrawalLimit != -1)
            {
                //获取当日所有用户提现金额
                decimal RemitMoney = distributor_RemitRepository.GetAllUserToDayRemitMoney(demodel.TenantId, demodel.MallBaseId);
                //今日可提
                decimal CanRemitMoney = (basicsModel.DailyWithdrawalLimit ?? 0) - RemitMoney;
                CanRemitMoney = CanRemitMoney < 0 ? 0 : CanRemitMoney;

                if (CanRemitMoney < (demodel.AppliedMoney ?? 0))
                {
                    return "今日可提现余额不足";
                }
            }
            //验证手续费
            if (basicsModel.WithdrawFee > 0)
            {
                decimal fee = Math.Round((demodel.AppliedMoney ?? 0) * (basicsModel.WithdrawFee ?? 0) / 100, 2, MidpointRounding.AwayFromZero);
                if (demodel.Fee != fee)
                {
                    return "手续费计算不准确";
                }
                if (demodel.RemitMoney != (demodel.AppliedMoney ?? 0) - fee)
                {
                    return "最终金额不正确";
                }
            }
            else
            {
                demodel.Fee = 0;
                demodel.RemitMoney = demodel.AppliedMoney;
            }
            var trans = distributor_RemitRepository.DbTransaction;
            try
            {
                int RemitId = distributor_RemitRepository.Insert(demodel, trans);
                bool flag = RemitId > 0;
                if (flag)
                {
                    //扣除账户可提佣金
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Distributor_Info.CommissionWithdrawal),(disModel.CommissionWithdrawal ?? 0) - (demodel.AppliedMoney ?? 0)}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Distributor_Info.Id),
                              FiledValue=disModel.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    distributor_InfoRepository.Update(keyValues, wheres, trans);

                    #region 写入提现订单

                    if (demodel.TenantId == 1)
                    {
                        //所有未提现的 返佣
                        var clist = goods_OrderCommissionRepository.GetUserCommissionRemit(demodel.UserId ?? 0);
                        var viplist = vipBuy_CommissionRepository.GetList(new RB_VipBuy_Commission_Extend() { UserId = demodel.UserId, Type = 1, IsRemit = 2 });
                        if (clist.Any() || viplist.Any())
                        {
                            //获取订单列表
                            List<RB_Goods_Order_Extend> olist = new List<RB_Goods_Order_Extend>();
                            if (clist.Any())
                            {
                                string OrderIds = string.Join(",", clist.Select(x => x.OrderId).Distinct());
                                olist = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { OrderIds = OrderIds });
                                olist = olist.OrderByDescending(x => x.CreateDate).ToList();
                            }
                            List<int> OrderIdList = new List<int>();
                            List<int> VipIdList = new List<int>();
                            string OrderNos = "";
                            decimal TMoney = (demodel.AppliedMoney ?? 0);
                            //首先查询 vip购买返佣，有的话  优先提vip返佣的
                            if (viplist.Any())
                            {
                                //获取订单列表
                                string vipoIds = string.Join(",", viplist.Where(x => x.ReOrderId > 0).Select(x => x.ReOrderId));
                                List<RB_Goods_Order_Extend> vipolist = new List<RB_Goods_Order_Extend>();
                                if (!string.IsNullOrEmpty(vipoIds))
                                {
                                    vipolist = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { OrderIds = vipoIds });
                                }
                                foreach (var item in viplist)
                                {
                                    if (TMoney > 0)
                                    {
                                        TMoney -= (item.Commission ?? 0);
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_VipBuy_Commission_Extend.IsRemit),1}
                                        };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_VipBuy_Commission_Extend.Id),
                                                    FiledValue=item.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        vipBuy_CommissionRepository.Update(keyValues2, wheres2, trans);
                                        string OrderNo = item.OrderNo;
                                        var vipoModel = vipolist.Where(x => x.OrderId == item.ReOrderId).FirstOrDefault();
                                        if (vipoModel != null)
                                        {
                                            OrderNo = vipoModel.OrderNo ?? "";
                                        }
                                        OrderNos += "\"VIP " + OrderNo + "\"：" + (item.Commission ?? 0) + "元，";
                                        VipIdList.Add(item.Id);
                                    }
                                }
                            }

                            //开始递减金额   订单不足的  给与提示
                            foreach (var item in olist)
                            {
                                if (TMoney > 0)
                                {
                                    decimal CommMoney = 0;
                                    var chlist = clist.Where(x => x.OrderId == item.OrderId).ToList();
                                    foreach (var qitem in chlist)
                                    {
                                        TMoney -= (qitem.Commission ?? 0);
                                        CommMoney += (qitem.Commission ?? 0);
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_OrderCommission_Extend.IsRemit),1}
                                    };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Goods_OrderCommission_Extend.Id),
                                              FiledValue=qitem.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                        goods_OrderCommissionRepository.Update(keyValues2, wheres2, trans);
                                    }
                                    OrderNos += "\"" + item.OrderNo + "\"：" + CommMoney + "元，";
                                    OrderIdList.Add(item.OrderId);
                                }
                            }
                            if (!string.IsNullOrEmpty(OrderNos))
                            {
                                OrderNos = OrderNos[0..^1];
                            }
                            if (TMoney > 0)
                            {
                                OrderNos += "  余额" + TMoney + "尚未找到相关订单";
                            }
                            else if (TMoney < 0)
                            {
                                OrderNos += "  多出" + (0 - TMoney) + "存在未匹配到正确的订单";
                            }

                            if (!string.IsNullOrEmpty(OrderNos))
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Distributor_Remit_Extend.ReOrderNos),OrderNos},
                                    { nameof(RB_Distributor_Remit_Extend.ReOrderIds),JsonConvert.SerializeObject(OrderIdList)},
                                    { nameof(RB_Distributor_Remit_Extend.ReVipIds),JsonConvert.SerializeObject(VipIdList)},
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Distributor_Remit_Extend.Id),
                                          FiledValue=RemitId,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                distributor_RemitRepository.Update(keyValues1, wheres1, trans);
                            }
                        }
                    }
                    #endregion
                }
                distributor_RemitRepository.DBSession.Commit();
                return "";
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetDistrbutorWithdrawDeposit");
                distributor_RemitRepository.DBSession.Rollback();
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 获取分销佣金页面详情
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetDistrbutorCommissionInfo(AppletUserInfo userInfo)
        {
            var model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return "分销商不存在";
            }
            if (model.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Audited)
            {
                return "分销商不存在";
            }
            //已提现佣金 //未结算佣金
            var commModel = distributor_RemitRepository.GetDistributorCommissionStatiscs(userInfo.UserId);

            var CustomModel = distributor_CustomRepository.GetList(new RB_Distributor_Custom_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (CustomModel == null)
            {
                return "";
            }
            var baseModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();

            return new
            {
                CustomModel = new
                {
                    CustomModel.CommissionTobePaidName,
                    CustomModel.UserNotesName,
                    CustomModel.IWantToWithdrawName,
                    baseModel.UserNotes
                },
                CommissionInfo = new
                {
                    model.TotalCommission,
                    CommissionWithdrawal = model.CommissionWithdrawal ?? 0,
                    TXCommission = commModel?.TXCommission ?? 0,
                    WJSCommission = commModel?.WJSCommission ?? 0
                }
            };
        }

        /// <summary>
        /// 获取我的团队
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public object GetUserMyTeamPageList(int pageIndex, int pageSize, out long count, RB_Distributor_Info_Extend demodel)
        {
            var list = member_UserRepository.GetDistributorReferralsPageList(pageIndex, pageSize, out count, demodel);
            List<object> RList = new List<object>();
            if (list.Any())
            {
                string userIds = string.Join(",", list.Select(x => x.Id));
                //获取推广人数
                var tList = member_UserRepository.GetDistributorReferralsNum(userIds, 1, demodel.TenantId, demodel.MallBaseId);
                //获取消费金额 + 订单数量
                var oList = goods_OrderRepository.GetUserOrderNumAndMoney(userIds, demodel.TenantId, demodel.MallBaseId);

                foreach (var item in list)
                {
                    int tgNum = tList.Where(x => x.SuperiorId == item.Id).FirstOrDefault()?.ReferralsNum ?? 0;
                    var orderModel = oList.Where(x => x.UserId == item.Id).FirstOrDefault();
                    RList.Add(new
                    {
                        UserId = item.Id,
                        UserName = item.Name,
                        item.Photo,
                        CreateDate = item.CreateDate.HasValue ? item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        GeneralizeNum = tgNum,
                        OrderNum = orderModel?.OrderNum ?? 0,
                        Income = orderModel?.Income ?? 0
                    });
                }
            }
            return RList;
        }

        /// <summary>
        /// 获取我的团队自定义信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetUserMyTeamCustomInfo(AppletUserInfo userInfo)
        {
            var CustomModel = distributor_CustomRepository.GetList(new RB_Distributor_Custom_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            return new
            {
                CustomModel.OneDistributionName,
                CustomModel.TwoDistributionName,
                CustomModel.ThreeDistributionName
            };
        }

        /// <summary>
        /// 获取粉象我的团队标题列表
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GerUserMyTeamTitelListForFX(AppletUserInfo userInfo)
        {
            string UserIds = member_UserRepository.GetMemberChildIdStr(userInfo.UserId);
            //获取下级所有等级
            var disList = distributor_InfoRepository.GetFXGreadeListForMyTeam(new RB_Distributor_Info_Extend() { UserIds = UserIds, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            var fxList = new List<RB_Distributor_FXGrade_Extend>();
            if (disList.Where(x => x.FXGradeId > 0).Any())
            {
                string fxgradeIds = string.Join(",", disList.Select(x => x.FXGradeId));
                fxList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = fxgradeIds, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                fxList = fxList.OrderByDescending(x => x.Grade).ToList();//倒序  最大的拍前面
                foreach (var item in fxList)
                {
                    var dismodel = disList.Where(x => x.FXGradeId == item.Id).FirstOrDefault();
                    item.GradeName += " (" + (dismodel?.OneNum ?? 0) + ")";
                }
            }
            else
            {
                //增加一个 普通会员等级
                fxList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { IsGuest = 1, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                foreach (var item in fxList)
                {
                    item.GradeName += " (0)";
                }
            }
            return fxList.Select(x => new
            {
                x.Id,
                x.GradeName
            });
        }

        /// <summary>
        /// 获取我的团队 (粉象)
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <param name="NewUserId"></param>
        /// <returns></returns>
        public object GetUserMyTeamPageListForFX(int pageIndex, int pageSize, out long count, RB_Distributor_Info_Extend demodel,int NewUserId=0)
        {
            string UserIds = member_UserRepository.GetMemberChildIdStr(demodel.UserId ?? 0);
         
            var list = member_UserRepository.GetPageListForFX(pageIndex, pageSize, out count,
                new RB_Member_User_Extend()
                {
                    UserIds = UserIds,
                    FXGradeId = demodel.FXGradeId,
                    Name = demodel.Name,
                    TenantId = demodel.TenantId,
                    MallBaseId = demodel.MallBaseId,
                    SortNum = demodel.SortNum
                });
            List<object> RList = new List<object>();
            if (list.Any())
            {
                string userIds = string.Join(",", list.Select(x => x.Id));
                //获取推广人数
                var tList = member_UserRepository.GetDistributorReferralsNum(userIds, 1, demodel.TenantId, demodel.MallBaseId);
                //获取消费金额 + 订单数量
                var oList = goods_OrderRepository.GetUserOrderNumAndMoney(userIds, demodel.TenantId, demodel.MallBaseId);

                foreach (var item in list.Where(qitem => qitem.Id != NewUserId))
                {
                    int tgNum = tList.Where(x => x.SuperiorId == item.Id).FirstOrDefault()?.ReferralsNum ?? 0;
                    var orderModel = oList.Where(x => x.UserId == item.Id).FirstOrDefault();
                    RList.Add(new
                    {
                        UserId = item.Id,
                        UserName = item.Name,
                        item.Photo,
                        CreateDate = item.CreateDate.HasValue ? item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        GeneralizeNum = tgNum,
                        OrderNum = orderModel?.OrderNum ?? 0,
                        Income = orderModel?.Income ?? 0,
                    });
                }
            }
            return RList;
        }

        /// <summary>
        /// 粉象升级条件
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetUserDistrbutorUpgradeConditionsForFX(AppletUserInfo userInfo)
        {
            var model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (model == null || model.AuditStatus != DistributorAuditStatusEnum.Audited)
            {
                return new
                {
                    Status = 2,
                    GradeInfo = new { }
                };
            }
            var gmodel = distributor_FXGradeRepository.GetEntity(model.FXGradeId);
            var upgmodel = distributor_FXGradeRepository.GetDistrbutorUpgrade(gmodel?.Grade ?? 0, userInfo.TenantId, userInfo.MallBaseId);
            if (upgmodel == null || (upgmodel.IsUpgrade ?? 2) != 1)
            {
                return new
                {
                    Status = 2,
                    GradeInfo = new { }
                };
            }
            else
            {
                var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                var upfxmodel = FXList.Where(x => x.Id == upgmodel.UpgradeId).FirstOrDefault();
                int MeetNum = 0;
                if (upfxmodel != null)
                {
                    FXList = FXList.Where(x => x.Grade >= upfxmodel.Grade).ToList();
                    //已发展等级
                    if (FXList.Any())
                    {
                        string FXGradeIds = string.Join(",", FXList.Select(x => x.Id));
                        MeetNum = member_UserRepository.GetUserReferralsForFX(new RB_Member_User_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, SuperiorId = userInfo.UserId, FXGradeIds = FXGradeIds });
                    }
                }
                return new
                {
                    Status = 1,
                    GradeInfo = new
                    {
                        upgmodel.Id,
                        upgmodel.Grade,
                        upgmodel.GradeName,
                        upgmodel.CommissionRatio,
                        upgmodel.UpgradeNum,
                        MeetNum,
                        upgmodel.UpgradeId,
                        UpgradeIdName = distributor_FXGradeRepository.GetEntity(upgmodel.UpgradeId)?.GradeName ?? "其他等级"
                    }
                };
            }
        }

        /// <summary>
        /// 用户自动升级粉象等级
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetUserDistrbutorUpgradeForFX(int gradeId, AppletUserInfo userInfo)
        {
            var disModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if ((disModel?.IsEnableFXGrade ?? 2) != 1)
            {
                return "未启用自动升级";
            }
            var model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (model == null || model.AuditStatus != DistributorAuditStatusEnum.Audited)
            {
                return "您不是分销商，无法操作";
            }
            var gmodel = distributor_FXGradeRepository.GetEntity(gradeId);
            if (gmodel == null)
            {
                return "该等级不存在，无法升级";
            }
            if (gmodel.IsUpgrade != 1)
            {
                return "该等级未启用自动升级";
            }

            var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            var upfxmodel = FXList.Where(x => x.Id == gmodel.UpgradeId).FirstOrDefault();
            if (upfxmodel == null)
            {
                return "未满足升级条件";
            }
            FXList = FXList.Where(x => x.Grade >= upfxmodel.Grade).ToList();
            int MeetNum = 0;
            //已发展等级
            if (FXList.Any())
            {
                string FXGradeIds = string.Join(",", FXList.Select(x => x.Id));
                MeetNum = member_UserRepository.GetUserReferralsForFX(new RB_Member_User_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, SuperiorId = userInfo.UserId, FXGradeIds = FXGradeIds });
            }
            if ((gmodel.UpgradeNum ?? 0) > MeetNum)
            {
                return "未满足升级条件";
            }

            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_Info.FXGradeId),gradeId},
                { nameof(RB_Distributor_Info.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Distributor_Info.Id),
                      FiledValue=gradeId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = distributor_InfoRepository.Update(keyValues, wheres);
            if (flag)
            {
                return "";
            }
            return "升级失败，请联系管理员";
        }

        /// <summary>
        /// 获取分销中心  vip购买返佣列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_VipBuy_Commission_Extend> GetUserVipCommissionOrdersPageList(int pageIndex, int pageSize, out long count, RB_VipBuy_Commission_Extend demodel)
        {
            var List = vipBuy_CommissionRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (List.Any())
            {
                string fxgradeids = string.Join(",", List.Select(x => x.Grade ?? 0).Distinct());
                var fxlist = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = fxgradeids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in List)
                {
                    var fxmodel = fxlist.Where(x => x.Id == item.Grade).FirstOrDefault();
                    item.GradeDescription = fxmodel.GradeName + "佣金";
                }
            }
            return List;
        }

        #endregion

        #region 我的足迹


        /// <summary>
        /// 获取用户足迹分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Member_Footmark_Extend> GetUserFootMarkPageList(int pageIndex, int pageSize, out long count, RB_Member_Footmark_Extend demodel)
        {
            var list = member_FootmarkRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询商品信息
                string goodsIds = string.Join(",", list.Select(x => x.GoodsId).Distinct());
                var goodsList = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                foreach (var item in list)
                {
                    var goodsModel = goodsList.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    item.GoodsName = goodsModel?.Name ?? "";
                    item.Price = goodsModel?.SellingPrice ?? 0;
                    item.GoodsImgPath = "";
                    if (goodsModel != null)
                    {
                        if (!string.IsNullOrEmpty(goodsModel.CarouselImage) && goodsModel.CarouselImage != "[]")
                        {
                            List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(goodsModel.CarouselImage);
                            //封面图
                            item.GoodsImgPath = CarouselIdList[0];
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 新增足迹
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetUserFootMarkInfo(int goodsId, AppletUserInfo userInfo)
        {
            var model = member_FootmarkRepository.GetList(new RB_Member_Footmark_Extend() { GoodsId = goodsId, UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();

            if (model == null)
            {
                return member_FootmarkRepository.Insert(new RB_Member_Footmark()
                {
                    Id = 0,
                    GoodsId = goodsId,
                    Status = 0,
                    UserId = userInfo.UserId,
                    CreateDate = DateTime.Now,
                    TenantId = userInfo.TenantId,
                    MallBaseId = userInfo.MallBaseId
                }) > 0;
            }
            else
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Member_Footmark.CreateDate),DateTime.Now}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper{
                         FiledName=nameof(RB_Member_Footmark.Id),
                          FiledValue=model.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return member_FootmarkRepository.Update(keyValues, wheres);
            }
        }

        /// <summary>
        /// 删除足迹
        /// </summary>
        /// <param name="footMarkId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool DelUserFootMarkInfo(int footMarkId, AppletUserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Member_Footmark.Status),1},
                { nameof(RB_Member_Footmark.CreateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper{
                        FiledName=nameof(RB_Member_Footmark.Id),
                        FiledValue=footMarkId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper{
                        FiledName=nameof(RB_Member_Footmark.UserId),
                        FiledValue=userInfo.UserId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper{
                        FiledName=nameof(RB_Member_Footmark.TenantId),
                        FiledValue=userInfo.TenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper{
                        FiledName=nameof(RB_Member_Footmark.MallBaseId),
                        FiledValue=userInfo.MallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return member_FootmarkRepository.Update(keyValues, wheres);
        }

        #endregion

        #region 个人中心



        /// <summary>
        /// 获取个人中心统计
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetAppletUserCenterStatistics(string openId)
        {
            var objData = new object();
            var umodel = member_UserRepository.GetMemberUserEntityRepository(new RB_Member_User_Extend() { OpenId = openId });
            if (umodel != null && umodel.Id > 0)
            {
                //获取我的收藏
                int CollectionNum = member_CollectionRepository.GetMyCollectionNum(new RB_Member_Collection_Extend() { UserId = umodel.Id, TenantId = umodel.TenantId, MallBaseId = umodel.MallBaseId });
                //获取我的足迹
                int FootmarkNum = member_FootmarkRepository.GetMyFootmarkNum(umodel.Id, umodel.TenantId, umodel.MallBaseId);
                //订单状态
                List<RB_Goods_Order_Extend> olist = goods_OrderRepository.GetAppletGoodsOrderNumStatistics(umodel.Id, umodel.TenantId, umodel.MallBaseId);
                //待评价
                int WaitCommentNum = goods_OrderRepository.GetAppletGoodsOrderWaitCommentNum(umodel.Id, umodel.TenantId, umodel.MallBaseId);
                //售后处理中
                int AfterSaleNum = goods_OrderRepository.GetAppletGoodsOrderAfterSaleNum(umodel.Id, umodel.TenantId, umodel.MallBaseId);
                string parent_name = "";
                if (umodel.SuperiorId != null)
                {
                    if (umodel.SuperiorId == 0)
                    {
                        parent_name = "总店";
                    }
                    else if (umodel.SuperiorId > 0)
                    {
                        parent_name = member_UserRepository.GetEntity<RB_Member_User_Extend>(umodel.SuperiorId)?.Name ?? "";
                    }
                }

                #region 和平分销 - 是否显示分销中心

                //获取是否开启和平分销
                int IsShowDistributionCenter = 1;//默认显示
                var IsHpFX = GetHpDistributorIsEnabled(umodel?.TenantId ?? 0, umodel?.MallBaseId ?? 0);
                if (IsHpFX == 1)
                {
                    //验证如果其上级为二级分销商  则无法看到分销中心
                    if (umodel.IsDistributor != 1 && umodel.SuperiorId > 0)
                    {
                        var SdisModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = umodel.SuperiorId, TenantId = umodel.TenantId, MallBaseId = umodel.MallBaseId }).FirstOrDefault();
                        if (SdisModel != null)
                        {
                            var glist = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { TenantId = umodel.TenantId, MallBaseId = umodel.MallBaseId });
                            int MinId = glist.Where(x => (x.IsGuest ?? 0) != 1).Max(x => x.Grade ?? 0);
                            var sdisgM = glist.Where(x => x.Id == SdisModel.HPGradeId).FirstOrDefault();
                            if (MinId == (sdisgM?.Grade ?? 0))
                            {
                                IsShowDistributionCenter = 2;//其上级为最后一级  和平下不能显示分销中心
                            }
                        }
                    }
                    else if (umodel.IsDistributor != 1 && umodel.SuperiorId == 0)
                    {
                        IsShowDistributionCenter = 2;//没有上级  和平下不能显示分销中心
                    }
                }

                #endregion

                //获取会员优惠券信息  2020-06-15  add by :W 
                var couponList = memberCouponRepository.GetAllMemberCouponPageList(new RB_Member_DiscountCoupon_Extend { TenantId = umodel.TenantId, MallBaseId = umodel.MallBaseId, UseState = 0, UserId = umodel.Id });

                var MemberGrade = "普通用户";
                string MemberGradeIcon = "";
                if (umodel.MemberGrade > 0)
                {
                    var mgModel = member_GradeRepository.GetEntity(umodel.MemberGrade);
                    if (mgModel != null)
                    {
                        MemberGrade = mgModel.Name;
                        if (mgModel.Icon > 0)
                        {
                            MemberGradeIcon = material_InfoRepository.GetEntity(mgModel.Icon)?.Path ?? "";
                        }
                    }
                }
                objData = new
                {
                    //昵称
                    nickname = umodel?.Name ?? "",
                    //电话
                    mobile = umodel?.Moblie ?? "",
                    //头像
                    avatar = umodel?.Photo ?? "",
                    //积分
                    integral = umodel?.Integral ?? 0,
                    //余额
                    balance = umodel?.Balance ?? 0,
                    //选项todo
                    options = new { },
                    //收藏 todo
                    favorite = CollectionNum,
                    //足迹
                    footprint = FootmarkNum,
                    //优惠券
                    coupon = (couponList != null && couponList.Any()) ? couponList.Count() : 0,//2020-06-15  update by :W   // umodel.CouponsNum,
                    //卡券
                    card = umodel.CardVolumeNum,
                    //标识
                    identity = new
                    {
                        parent_name,
                        member_level = umodel.MemberGrade,
                        level_name = MemberGrade,
                        level_icon = MemberGradeIcon,
                        is_admin = 0,
                    },
                    MyOrder = new
                    {
                        NonPayment = olist.Where(x => x.OrderStatus == Common.Enum.Goods.OrderStatusEnum.NonPayment).FirstOrDefault()?.OrderNum ?? 0,
                        WaitSendGoods = olist.Where(x => x.OrderStatus == Common.Enum.Goods.OrderStatusEnum.WaitSendGoods).FirstOrDefault()?.OrderNum ?? 0,
                        WaitReceiving = olist.Where(x => x.OrderStatus == Common.Enum.Goods.OrderStatusEnum.WaitReceiving).FirstOrDefault()?.OrderNum ?? 0,
                        WaitCommentNum,
                        AfterSaleNum
                    },
                    isShowDistributionCenter = IsShowDistributionCenter
                };
            }
            return objData;
        }

        #endregion

        #region 用户转移

        /// <summary>
        /// 更新用户微信头像
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="count"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool UpdateUserPhotoForWeiXin(int userId, int count, int tenantId, int mallBaseId)
        {
            var list = member_UserRepository.GetPageList(1, count, out long rcount, new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, Id = userId, Source = UserSourceEnum.WeiXin, IsEmptyUserPhoto = 1 });

            var appletWeChatModel = miniProgramRepository.GetEntity(mallBaseId);
            string token = CacheManager.AppletWeChat.WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => CacheManager.AppletWeChat.WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            foreach (var item in list)
            {
                string photo = Mall.Common.Pay.WeChatPat.TokenHelper.GetWeiXinUserPhoto(token, item.OpenId);
                if (!string.IsNullOrEmpty(photo))
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Member_User.Photo),photo}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Member_User.Id),
                              FiledValue=item.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    member_UserRepository.Update(keyValues, wheres);
                }
            }
            return true;
        }

        /// <summary>
        /// 更新用户上下级关系
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="count"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public int UpdateUserSuperiorForWeiXin(int userId, int count, int tenantId, int mallBaseId)
        {
            string cookie = "__login_route=%2Fadmin%2Fpassport%2Flogin; __login_role=admin; HJ_SESSION_ID=lgfv5vck57rj84nh4npn59b4pj; _csrf=1febe37678187521a164220da9a9293f67d6d638a1cc01acebf0d3123757216ea%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22e5vd7mYVeGAfqcBMV_m0lkeiJLXFghtc%22%3B%7D";
            var list = member_UserRepository.GetPageList(1, count, out long rcount, new RB_Member_User_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, MinUserId = userId, Source = UserSourceEnum.WeiXin });
            foreach (var item in list)
            {
                string data = Mall.Common.Pay.WeChatPat.TokenHelper.GetZYUserInfo(item.Id, cookie);
                if (!string.IsNullOrEmpty(data))
                {
                    var data1 = Encoding.GetEncoding("GBK").GetBytes(data);
                    data = Encoding.GetEncoding("GBK").GetString(data1);
                    var jdata = (JObject)JsonConvert.DeserializeObject(data);
                    var List = jdata["list"].ToString();
                    if (List != "" && List != "[]")
                    {
                        //根据用户名  查询一次用户列表
                        List<Model.Query.UserSuperiorImport> UserList = JsonConvert.DeserializeObject<List<Model.Query.UserSuperiorImport>>(List);
                        foreach (var uitem in UserList)
                        {
                            uitem.nickname = uitem.nickname.Replace("'", "\"");
                            uitem.nickname = uitem.nickname.Replace("??", "?");
                            uitem.nickname = "'" + uitem.nickname + "'";
                        }
                        string UserNameStr = string.Join(",", UserList.Select(x => x.nickname));
                        var uList = member_UserRepository.GetList(new RB_Member_User_Extend() { UserNameStr = UserNameStr, TenantId = tenantId, MallBaseId = mallBaseId });

                        foreach (var qitem in uList)
                        {
                            if (qitem.SuperiorId == 0)
                            {
                                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                    { nameof(RB_Member_User.SuperiorId),item.Id}
                                };
                                List<WhereHelper> wheres = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Member_User.Id),
                                          FiledValue=qitem.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                member_UserRepository.Update(keyValues, wheres);
                            }
                        }
                    }
                }
            }
            return list.Max(x => x.Id);
        }

        #endregion

        #region 数据统计-分销排行
        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetRankingListPage(int pageIndex, int pageSize, out long rowCount, RB_Member_User_Extend dmodel)
        {
            return member_UserRepository.GetRankingListPage(pageIndex, pageSize, out rowCount, dmodel);
        }

        /// <summary>
        /// 获取全部分销商信息
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetRankingList(RB_Member_User_Extend dmodel)
        {
            return member_UserRepository.GetRankingList(dmodel);
        }
        #endregion

        #region 和平分销

        /// <summary>
        /// 获取和平分销等级分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_HPGradeInfo_Extend> GetHpDistributorGradePageList(int pageIndex, int pageSize, out long count, RB_Distributor_HPGradeInfo_Extend demodel)
        {
            return distributor_HPGradeInfoRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取等级列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_HPGradeInfo_Extend> GetHpDistributorGradeList(RB_Distributor_HPGradeInfo_Extend demodel)
        {
            return distributor_HPGradeInfoRepository.GetList(demodel);
        }

        /// <summary>
        /// 新增修改和平等级
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetHpDistributorGradeInfo(RB_Distributor_HPGradeInfo_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_HPGradeInfo.Grade),demodel.Grade},
                    { nameof(RB_Distributor_HPGradeInfo.GradeName),demodel.GradeName},
                    { nameof(RB_Distributor_HPGradeInfo.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPGradeInfo.Id),
                         FiledValue=demodel.Id,
                          OperatorEnum=OperatorEnum.Equal
                    }
                };
                return distributor_HPGradeInfoRepository.Update(keyValues, wheres);
            }
            else
            {
                return distributor_HPGradeInfoRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 删除和平等级
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelHpDistributorGradeInfo(int gradeId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_HPGradeInfo.Status),1},
                { nameof(RB_Distributor_HPGradeInfo.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Distributor_HPGradeInfo.Id),
                        FiledValue=gradeId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Distributor_HPGradeInfo.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Distributor_HPGradeInfo.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return distributor_HPGradeInfoRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 获取分销返佣分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_HPCommission_Extend> GetHpDistributorPageList(int pageIndex, int pageSize, out long count, RB_Distributor_HPCommission_Extend demodel)
        {
            var list = distributor_HPCommissionRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string cids = string.Join(",", list.Select(x => x.Id));
                //查询所有分类
                var clist = distributor_HPCategoryRepository.GetList(new RB_Distributor_HPCategory_Extend() { CommissionIds = cids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                //查询所有比例
                var rlist = distributor_HPGradeRatioRepository.GetList(new RB_Distributor_HPGradeRatio_Extend() { CommissionIds = cids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.CommissionId == item.Id).ToList();
                    item.RatioList = rlist.Where(x => x.CommissionId == item.Id).OrderBy(x => x.Grade).ToList();
                }
            }
            return list;
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="commissionId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_Distributor_HPCommission_Extend GetHpdistributorInfo(int commissionId, int tenantId, int mallBaseId)
        {
            var model = distributor_HPCommissionRepository.GetEntity<RB_Distributor_HPCommission_Extend>(commissionId);
            model.CategoryList = distributor_HPCategoryRepository.GetList(new RB_Distributor_HPCategory_Extend() { CommissionId = commissionId, TenantId = tenantId, MallBaseId = mallBaseId });
            //查询所有比例
            model.RatioList = distributor_HPGradeRatioRepository.GetList(new RB_Distributor_HPGradeRatio_Extend() { CommissionId = commissionId, TenantId = tenantId, MallBaseId = mallBaseId });
            return model;
        }

        /// <summary>
        /// 新增修改和平分销
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetHpDistributorInfo(RB_Distributor_HPCommission_Extend demodel)
        {
            var trans = distributor_HPCommissionRepository.DbTransaction;
            try
            {
                if (demodel.Id > 0)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Distributor_HPCommission.Enabled),demodel.Enabled},
                        { nameof(RB_Distributor_HPCommission.Name),demodel.Name},
                        { nameof(RB_Distributor_HPCommission.DecimalType),demodel.DecimalType},
                        { nameof(RB_Distributor_HPCommission.IsCommon),demodel.IsCommon},
                        { nameof(RB_Distributor_HPCommission.UpdateDate),demodel.UpdateDate}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Distributor_HPCommission.Id),
                              FiledValue=demodel.Id,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Distributor_HPCommission.TenantId),
                              FiledValue=demodel.TenantId,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Distributor_HPCommission.MallBaseId),
                              FiledValue=demodel.MallBaseId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    bool flag = distributor_HPCommissionRepository.Update(keyValues, wheres, trans);
                    if (flag)
                    {
                        #region 验证比例是否修改
                        var rlist = distributor_HPGradeRatioRepository.GetList(new RB_Distributor_HPGradeRatio_Extend() { CommissionId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        var rUpdateList = rlist.Where(x => demodel.RatioList.Select(z => z.GradeId).Contains(x.GradeId)).ToList();
                        var rDelList = rlist.Where(x => !demodel.RatioList.Select(z => z.GradeId).Contains(x.GradeId)).ToList();
                        var rInsertList = demodel.RatioList.Where(x => !rlist.Select(z => z.GradeId).Contains(x.GradeId)).ToList();

                        foreach (var item in rUpdateList)
                        {
                            var rmodel = demodel.RatioList.Where(x => x.GradeId == item.GradeId).FirstOrDefault();
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Distributor_HPGradeRatio.CommissionRatio),rmodel?.CommissionRatio??0}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Distributor_HPGradeRatio.Id),
                                      FiledValue=item.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            distributor_HPGradeRatioRepository.Update(keyValues1, wheres1, trans);
                        }
                        foreach (var item in rDelList)
                        {
                            distributor_HPGradeRatioRepository.Delete(item, trans);
                        }
                        foreach (var item in rInsertList)
                        {
                            distributor_HPGradeRatioRepository.Insert(new RB_Distributor_HPGradeRatio()
                            {
                                CommissionId = demodel.Id,
                                Id = 0,
                                CommissionRatio = item.CommissionRatio,
                                CreateDate = demodel.CreateDate,
                                GradeId = item.GradeId,
                                MallBaseId = demodel.MallBaseId,
                                TenantId = demodel.TenantId
                            }, trans);
                        }
                        #endregion

                        #region 验证分类是否修改

                        var clist = distributor_HPCategoryRepository.GetList(new RB_Distributor_HPCategory_Extend() { CommissionId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        var cDelList = clist.Where(x => !demodel.CategoryList.Select(z => z.CategoryId).Contains(x.CategoryId)).ToList();
                        var cInsertList = demodel.CategoryList.Where(x => !clist.Select(z => z.CategoryId).Contains(x.CategoryId)).ToList();

                        foreach (var item in cDelList)
                        {
                            distributor_HPCategoryRepository.Delete(item);
                        }
                        foreach (var item in cInsertList)
                        {
                            distributor_HPCategoryRepository.Insert(new RB_Distributor_HPCategory()
                            {
                                CategoryId = item.CategoryId,
                                CommissionId = demodel.Id,
                                Id = 0,
                                CreateDate = demodel.CreateDate,
                                MallBaseId = demodel.MallBaseId,
                                TenantId = demodel.TenantId
                            }, trans);
                        }
                        #endregion

                    }
                    distributor_HPCommissionRepository.DBSession.Commit();
                    return flag;
                }
                else
                {
                    int Id = distributor_HPCommissionRepository.Insert(demodel, trans);
                    if (Id > 0)
                    {
                        //插入比例
                        foreach (var item in demodel.RatioList)
                        {
                            distributor_HPGradeRatioRepository.Insert(new RB_Distributor_HPGradeRatio()
                            {
                                CommissionId = Id,
                                Id = 0,
                                CommissionRatio = item.CommissionRatio,
                                CreateDate = demodel.CreateDate,
                                GradeId = item.GradeId,
                                MallBaseId = demodel.MallBaseId,
                                TenantId = demodel.TenantId
                            }, trans);
                        }
                        //插入分类
                        foreach (var item in demodel.CategoryList)
                        {
                            distributor_HPCategoryRepository.Insert(new RB_Distributor_HPCategory()
                            {
                                CategoryId = item.CategoryId,
                                CommissionId = Id,
                                Id = 0,
                                CreateDate = demodel.CreateDate,
                                MallBaseId = demodel.MallBaseId,
                                TenantId = demodel.TenantId
                            }, trans);
                        }
                    }
                    distributor_HPCommissionRepository.DBSession.Commit();
                    return Id > 0;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetHpDistributorInfo");
                distributor_HPCommissionRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 启用和平分销
        /// </summary>
        /// <param name="commissionId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetGetHpDistrIbutorEnabled(int commissionId, int tenantId, int mallBaseId)
        {
            var model = distributor_HPCommissionRepository.GetEntity(commissionId);
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_HPCommission.Enabled),model.Enabled==1?2:1},
                { nameof(RB_Distributor_HPCommission.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission.Id),
                        FiledValue=commissionId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return distributor_HPCommissionRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 获取和平分销是否启用
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public int GetHpDistributorIsEnabled(int tenantId, int mallBaseId)
        {
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission.Status),
                        FiledValue=0,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission.Enabled),
                        FiledValue=1,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return distributor_HPCommissionRepository.Exists(wheres) ? 1 : 2;
        }

        /// <summary>
        /// 删除分销
        /// </summary>
        /// <param name="commissionId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelHpDistributorInfo(int commissionId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_HPCommission.Status),1},
                { nameof(RB_Distributor_HPCommission.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission.Id),
                        FiledValue=commissionId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return distributor_HPCommissionRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 获取用户和平分销信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetHpUserDistributorInfo(int userId, int tenantId, int mallBaseId)
        {
            var umodel = member_UserRepository.GetEntity(userId);
            var model = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = userId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return new
                {
                    Status = 3,
                    Msg = "该用户不是分销商"
                };
            }
            if (model.AuditStatus != DistributorAuditStatusEnum.Audited)
            {
                return new
                {
                    Status = 3,
                    Msg = "该用户不是分销商"
                };
            }

            var gmodel = distributor_HPGradeInfoRepository.GetEntity((model.HPGradeId ?? 0));
            var fxmodel = distributor_FXGradeRepository.GetEntity((model.FXGradeId ?? 0));
            return new
            {
                Status = 1,
                UserName = umodel?.Name ?? "",
                HPGrade = gmodel?.Grade ?? 0,
                HPGradeName = gmodel?.GradeName ?? "默认等级",
                FXGrade = fxmodel?.Grade ?? 0,
                FXGradeName = fxmodel?.GradeName ?? "默认等级"
            };
        }

        /// <summary>
        /// 获取商品建议价格
        /// </summary>
        /// <param name="categoryIds"></param>
        /// <param name="costPrice"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetHpGoodsSuggestPrice(string categoryIds, decimal costPrice, int tenantId, int mallBaseId)
        {
            //判断是否开启和平返佣
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission_Extend.Status),
                        FiledValue=0,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission_Extend.Enabled),
                        FiledValue=1,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission_Extend.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission_Extend.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            if (!distributor_HPCommissionRepository.Exists(wheres))
            {
                return new
                {
                    Status = 2,
                    MPrice = 0,
                    Msg = "未配置和平返佣"
                };
            }
            List<RB_Distributor_HPCommission_Extend> hpcList = new List<RB_Distributor_HPCommission_Extend>();
            if (string.IsNullOrEmpty(categoryIds))
            {
                hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, IsCommon = 1, TenantId = tenantId, MallBaseId = mallBaseId });
            }
            else
            {
                hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, CategoryIds = categoryIds, TenantId = tenantId, MallBaseId = mallBaseId });
                if (!hpcList.Any())
                {
                    hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, IsCommon = 1, TenantId = tenantId, MallBaseId = mallBaseId });
                }
            }
            if (hpcList.Any())
            {
                var hpcModel = hpcList.FirstOrDefault();
                //查询直客毛利率
                var gList = distributor_HPGradeRatioRepository.GetList(new RB_Distributor_HPGradeRatio_Extend() { CommissionId = hpcModel.Id, IsGuest = 1, TenantId = tenantId, MallBaseId = mallBaseId });

                var ratioModel = gList.FirstOrDefault();
                if (ratioModel != null)
                {
                    decimal MPrice = costPrice / (1 - ((ratioModel.CommissionRatio ?? 0) / 100));
                    MPrice = Math.Ceiling(MPrice);
                    return new
                    {
                        Status = 1,
                        MPrice,
                        Msg = ""
                    };
                }
            }
            return new
            {
                Status = 3,
                MPrice = 0,
                Msg = "未匹配到适用的返佣"
            };
        }

        /// <summary>
        /// 获取和平分销在商品中使用
        /// </summary>
        /// <param name="categoryIds"></param>
        /// <param name="costPrice"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetHpDistributorGoodsInfo(string categoryIds, decimal costPrice, int tenantId, int mallBaseId)
        {
            //判断是否开启和平返佣
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission_Extend.Status),
                        FiledValue=0,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission_Extend.Enabled),
                        FiledValue=1,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission_Extend.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPCommission_Extend.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            if (!distributor_HPCommissionRepository.Exists(wheres))
            {
                return new
                {
                    Status = 2,
                    RatioList = new { },
                    Msg = "未配置和平返佣"
                };
            }
            List<RB_Distributor_HPCommission_Extend> hpcList = new List<RB_Distributor_HPCommission_Extend>();
            if (string.IsNullOrEmpty(categoryIds))
            {
                hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, IsCommon = 1, TenantId = tenantId, MallBaseId = mallBaseId });
            }
            else
            {
                hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, CategoryIds = categoryIds, TenantId = tenantId, MallBaseId = mallBaseId });
                if (!hpcList.Any())
                {
                    hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, IsCommon = 1, TenantId = tenantId, MallBaseId = mallBaseId });
                }
            }
            if (hpcList.Any())
            {
                var hpcModel = hpcList.FirstOrDefault();
                //查询直客毛利率
                var gList = distributor_HPGradeRatioRepository.GetList(new RB_Distributor_HPGradeRatio_Extend() { CommissionId = hpcModel.Id, TenantId = tenantId, MallBaseId = mallBaseId });
                return new
                {
                    Status = 1,
                    RatioList = gList.OrderBy(x => x.Grade).Select(x => new
                    {
                        x.Id,
                        x.Grade,
                        x.GradeName,
                        x.CommissionRatio
                    }),
                    Msg = ""
                };

            }
            return new
            {
                Status = 3,
                RatioList = new { },
                Msg = "未匹配到适用的返佣"
            };
        }

        #endregion

        #region 粉象返佣

        /// <summary>
        /// 获取粉象分销等级分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_FXGrade_Extend> GetFXDistributorGradePageList(int pageIndex, int pageSize, out long count, RB_Distributor_FXGrade_Extend demodel)
        {
            return distributor_FXGradeRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取等级列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_FXGrade_Extend> GetFXDistributorGradeList(RB_Distributor_FXGrade_Extend demodel)
        {
            return distributor_FXGradeRepository.GetList(demodel);
        }

        /// <summary>
        /// 新增修改粉象等级
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetFXDistributorGradeInfo(RB_Distributor_FXGrade_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Distributor_FXGrade.Grade),demodel.Grade},
                    { nameof(RB_Distributor_FXGrade.GradeName),demodel.GradeName},
                    { nameof(RB_Distributor_FXGrade.IsGuest),demodel.IsGuest},
                    { nameof(RB_Distributor_FXGrade.CommissionRatio),demodel.CommissionRatio},
                    { nameof(RB_Distributor_FXGrade.SiblingRatio),demodel.SiblingRatio},
                    { nameof(RB_Distributor_FXGrade.SiblingRebatesNum),demodel.SiblingRebatesNum},
                    { nameof(RB_Distributor_FXGrade.IsCanBuy),demodel.IsCanBuy},
                    { nameof(RB_Distributor_FXGrade.BuyMoney),demodel.BuyMoney},
                    { nameof(RB_Distributor_FXGrade.Year),demodel.Year},
                    { nameof(RB_Distributor_FXGrade.IsUpgrade),demodel.IsUpgrade},
                    { nameof(RB_Distributor_FXGrade.UpgradeNum),demodel.UpgradeNum},
                    { nameof(RB_Distributor_FXGrade.UpgradeId),demodel.UpgradeId},
                    { nameof(RB_Distributor_FXGrade.UpdateDate),demodel.UpdateDate},
                    { nameof(RB_Distributor_FXGrade.DecimalType),demodel.DecimalType},
                    { nameof(RB_Distributor_FXGrade.Description),demodel.Description},
                    { nameof(RB_Distributor_FXGrade.Icon),demodel.Icon},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                        FiledName=nameof(RB_Distributor_HPGradeInfo.Id),
                         FiledValue=demodel.Id,
                          OperatorEnum=OperatorEnum.Equal
                    }
                };
                return distributor_FXGradeRepository.Update(keyValues, wheres);
            }
            else
            {
                return distributor_FXGradeRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 验证等级是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <param name="grade"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool ValidateFXGrade(int id, int? grade, int tenantId, int mallBaseId)
        {
            List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_FXGrade_Extend.Grade),
                        FiledValue=grade,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_FXGrade_Extend.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Distributor_FXGrade_Extend.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            if (id > 0)
            {
                whereHelpers.Add(new WhereHelper()
                {
                    FiledName = nameof(RB_Distributor_FXGrade_Extend.Id),
                    FiledValue = id,
                    OperatorEnum = OperatorEnum.NotEqual
                });
            }
            return distributor_FXGradeRepository.Exists(whereHelpers);
        }

        /// <summary>
        /// 删除粉象等级
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelFXDistributorGradeInfo(int gradeId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_FXGrade.Status),1},
                { nameof(RB_Distributor_FXGrade.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Distributor_HPGradeInfo.Id),
                        FiledValue=gradeId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Distributor_HPGradeInfo.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Distributor_HPGradeInfo.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return distributor_FXGradeRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 获取视图查询
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult GetFXDistributorGradeView(int tenantId, int mallBaseId)
        {
            var list = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = tenantId, MallBaseId = mallBaseId });
            if (list.Any())
            {
                var pModel = list.Where(x => x.IsGuest == 1).FirstOrDefault();
                if (pModel == null)
                {
                    return ApiResult.Failed("未查询到普通会员等级");
                }
                List<string> TitleList = new List<string>
                {
                    "等级名称",
                    "级别标准",
                    pModel.GradeName,
                    "间接普会"
                };
                foreach (var item in list)
                {
                    if (item.Id != pModel.Id)
                    {
                        TitleList.Add(item.GradeName);
                    }
                }
                List<object> ContenList = new List<object>();
                foreach (var item in list)
                {
                    List<string> itemList = new List<string>
                    {
                        item.GradeName,
                        (item.CommissionRatio ?? 0).ToString() + "%"
                    };
                    foreach (var qitem in list)
                    {
                        if (qitem.Id == pModel.Id)
                        {
                            itemList.Add(GetFXGradeRatioCommon(list, item.Id, qitem.Id, 1).ToString() + "%");
                            itemList.Add(GetFXGradeRatioCommon(list, item.Id, qitem.Id, 2).ToString() + "%");
                        }
                        else
                        {
                            itemList.Add(GetFXGradeRatioCommon(list, item.Id, qitem.Id).ToString() + "%");
                        }
                    }
                    ContenList.Add(itemList);
                }

                return ApiResult.Success("", new
                {
                    TitleList,
                    ContenList
                });
            }
            else
            {
                return ApiResult.Failed("没有数据");
            }
        }

        /// <summary>
        /// 获取比例
        /// </summary>
        /// <param name="list"></param>
        /// <param name="id1"></param>
        /// <param name="id2"></param>
        /// <returns></returns>
        private decimal GetFXGradeRatioCommon(List<RB_Distributor_FXGrade_Extend> list, int id1, int id2, int Type = 1)
        {
            var model1 = list.Where(x => x.Id == id1).FirstOrDefault();
            var model2 = list.Where(x => x.Id == id2).FirstOrDefault();
            var pModel = list.Where(x => x.IsGuest == 1).FirstOrDefault();
            if (id1 == id2 && Type == 1)
            {
                return model1.SiblingRatio ?? 0;
            }
            if (model2.Grade > model1.Grade)
            {
                return 0;
            }
            if (model1.Grade > model2.Grade && Type == 1)
            {
                return (model1.CommissionRatio ?? 0) - (model2.CommissionRatio ?? 0);
            }
            if (id2 == pModel.Id && Type == 2)
            {
                if (id1 == id2) { return 0; }
                return (model1.CommissionRatio ?? 0) - ((pModel.CommissionRatio ?? 0) + (pModel.SiblingRatio ?? 0));
            }
            return 0;
        }

        /// <summary>
        /// 获取粉象等级权益
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetUserVipBuyRecommend(int gradeId, AppletUserInfo userInfo)
        {
            var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            var fxgradeModel = FXList.Where(x => x.Id == gradeId).FirstOrDefault();
            if (fxgradeModel == null || fxgradeModel.IsGuest == 1)
            {
                return new { Status = 2, Msg = "等级不存在" };
            }
            var pModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
            if (pModel == null)
            {
                return new { Status = 2, Msg = "普通会员不存在" };
            }
            var vipModel = FXList.Where(x => x.IsGuest == 3).FirstOrDefault();
            if (vipModel == null)
            {
                return new { Status = 2, Msg = "Vip会员不存在" };
            }
            decimal fxP = GetFXGradeRatioCommon(FXList, fxgradeModel.Id, pModel.Id, 1);
            decimal fxJP = GetFXGradeRatioCommon(FXList, fxgradeModel.Id, pModel.Id, 2);
            var mingradeModel = FXList.Where(x => x.Grade < fxgradeModel.Grade).OrderBy(x => x.Grade).FirstOrDefault();


            var FXCList = distributor_FXCommissionRepository.GetFXCommissionList(new RB_Distributor_FXCommission_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            decimal fxVip = FXCList.Where(x => x.FXGradeId == fxgradeModel.Id && x.CommissionGradeId == vipModel.Id && x.GradeType == 1).FirstOrDefault()?.CommissionPrice ?? 0;
            decimal fxJVip = FXCList.Where(x => x.FXGradeId == fxgradeModel.Id && x.CommissionGradeId == vipModel.Id && x.GradeType == 2).FirstOrDefault()?.CommissionPrice ?? 0;

            return new
            {
                Status = 1,
                Model = new
                {
                    EarningsAdd = (fxgradeModel?.CommissionRatio ?? 0) - (mingradeModel?.CommissionRatio ?? 0),
                    FXPRate = fxP,
                    FXJPRate = fxJP,
                    FXVIP = fxVip,
                    FXJVIP = fxJVip,
                    fxgradeModel.Description
                }
            };
        }

        #endregion

        #region ERP查询用户返佣

        /// <summary>
        /// 获取用户返佣列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public object GetDistributionCommissionPageList(int pageIndex, int pageSize, out long count, RB_Member_User_Extend dmodel)
        {
            var list = member_UserRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            List<object> RList = new List<object>();
            if (list.Any())
            {
                int HpEnabled = GetHpDistributorIsEnabled(dmodel.TenantId, dmodel.MallBaseId);
                //获取分销商信息
                var userIds = string.Join(",", list.Select(x => x.Id));
                var DisList = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserIds = userIds, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                List<RB_Distributor_Grade_Extend> GradeList = new List<RB_Distributor_Grade_Extend>();
                List<RB_Distributor_HPGradeInfo_Extend> HpGradeList = new List<RB_Distributor_HPGradeInfo_Extend>();
                if (DisList.Any())
                {
                    //获取分销商等级
                    if (HpEnabled == 1)
                    {
                        if (DisList.Where(x => x.HPGradeId > 0).Any())
                        {
                            string gradeIds = string.Join(",", DisList.Where(x => x.HPGradeId > 0).Select(x => x.HPGradeId));
                            HpGradeList = distributor_HPGradeInfoRepository.GetList(new RB_Distributor_HPGradeInfo_Extend() { GradeIds = gradeIds, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                        }
                    }
                    else
                    {
                        if (DisList.Where(x => x.GradeId > 0).Any())
                        {
                            string gradeIds = string.Join(",", DisList.Where(x => x.GradeId > 0).Select(x => x.GradeId));
                            GradeList = distributor_GradeRepository.GetList(new RB_Distributor_Grade_Extend() { GradeIds = gradeIds, TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId });
                        }
                    }
                }
                //获取用户返佣统计
                var commList = goods_OrderCommissionRepository.GetUserCommissionStatistics(userIds);
                foreach (var item in list)
                {
                    var disModel = DisList.Where(x => x.UserId == item.Id).FirstOrDefault();//分销商信息
                    item.DistributorName = disModel?.Name ?? "";
                    item.DistributorMobile = disModel?.Mobile ?? "";
                    item.MemberGradeName = "默认等级";
                    if (HpEnabled == 1)
                    {
                        if ((disModel?.HPGradeId ?? 0) > 0)
                        {
                            item.MemberGradeName = HpGradeList.Where(x => x.Id == (disModel?.HPGradeId ?? 0)).FirstOrDefault()?.GradeName ?? "";
                        }
                    }
                    else
                    {
                        if ((disModel?.GradeId ?? 0) > 0)
                        {
                            item.MemberGradeName = GradeList.Where(x => x.Id == (disModel?.GradeId ?? 0)).FirstOrDefault()?.Name ?? "";
                        }

                    }

                    item.TotalCommission = disModel?.TotalCommission ?? 0;
                    item.Price = disModel?.CommissionWithdrawal ?? 0;
                    var commModel = commList.Where(x => x.UserId == item.Id).FirstOrDefault();//用户返佣
                    item.WaitCommission = commModel?.WaitCommission ?? 0;
                    item.Commission = commModel?.Commission ?? 0;
                }
            }
            return list.Select(x => new
            {
                UserId = x.Id,
                x.Name,
                x.Moblie,
                x.DistributorName,
                x.DistributorMobile,
                GradeName = x.MemberGradeName,
                x.TotalCommission,
                CommissionWithdrawal = x.Price,
                x.WaitCommission,
                x.Commission
            });
        }

        #endregion

        #region 获取分销海报

        /// <summary>
        /// 根据查询条件获取分销海报实体
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public RB_MiniProgram_FenXiaoPoster_Extend GetFenXiaoPosterEntityModule(RB_MiniProgram_FenXiaoPoster_Extend query)
        {
            return fenXiaoPosterRepository.GetEntityExtRepository(query);
        }

        #endregion

        #region 获取小程序码

        /// <summary>
        /// 生成小程序码
        /// </summary>
        /// <param name="path"></param>
        /// <param name="width"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string GetWeiXinQRCode(string path, int width, int mallBaseId)
        {
            var appletWeChatModel = miniProgramRepository.GetEntity(mallBaseId);
            string token = CacheManager.AppletWeChat.WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => CacheManager.AppletWeChat.WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (!string.IsNullOrEmpty(token))
            {
                //string GetImageUrl = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + token;//获取二维码
                string GetImageUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token;//获取小程序码
                var postData = new
                {
                    path,
                    width
                };
                string pathName = Guid.NewGuid().ToString() + ".jpg";
                string basepath = AppContext.BaseDirectory;
                string path_server = basepath + "\\upfile\\temporary\\" + pathName;
                //var Robj1 = HttpHelper.HttpPost(GetImageUrl, JsonHelper.Serialize(postData), "");
                var Robj = HttpHelper.HttpPostForGetWXQRCodePath(GetImageUrl, JsonHelper.Serialize(postData), path_server);

                return "/upfile/temporary/" + pathName;
                //if (Robj1.Length > 200)
                //{
                //    var Robj = HttpHelper.HttpPostForGetWXQRCodePath(GetImageUrl, JsonHelper.Serialize(postData), path_server);
                //    if (Robj != null)
                //    {
                //        return "/upfile/temporary/" + pathName;
                //    }
                //}
                //else
                //{
                //    JObject parms = JObject.Parse(Robj1);
                //    string errcode = parms.GetStringValue("errcode");//错误码
                //    if (errcode == "40001")//access_token失效那就重新在获取一次
                //    {
                //        token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                //        System.Threading.Tasks.Task.Run(() => CacheManager.AppletWeChat.WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
                //        if (!string.IsNullOrEmpty(token))
                //        {
                //            GetImageUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token;//获取小程序码
                //            postData = new
                //            {
                //                path,
                //                width
                //            };
                //            pathName = Guid.NewGuid().ToString() + ".jpg";
                //            basepath = AppContext.BaseDirectory;
                //            path_server = basepath + "\\upfile\\temporary\\" + pathName;
                //            Robj1 = HttpHelper.HttpPost(GetImageUrl, JsonHelper.Serialize(postData), "");
                //            var Robj = HttpHelper.HttpPostForGetWXQRCodePath(GetImageUrl, JsonHelper.Serialize(postData), path_server);
                //            if (Robj != null)
                //            {
                //                return "/upfile/temporary/" + pathName;
                //            }
                //        }
                //    }
                //    else
                //    {
                //        return "";
                //    }
                //}
                //

            }
            return "";
        }

        /// <summary>
        /// 获取微店小程序码
        /// </summary>
        /// <param name="path"></param>
        /// <param name="width"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public string GetWeiXinQRCodeForSmallShops(string path, int width, int mallBaseId, int userId)
        {
            var appletWeChatModel = miniProgramRepository.GetEntity(mallBaseId);
            string token = CacheManager.AppletWeChat.WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
            if (IsNormalServer != 1)
            {
                token = "36_isfBGeMx6esLrna2imlq-C4TY0TgMGECpaSqAvQb7nDl7BDshyR_7YEkT3eIcJJmJIDf2rGSeSOvpsM1TosaNelQ5q447QYgJ5TBot-jPQ5B1cxG_38yW2Kw_Pd44Cx0i1zMaII8AMbl8Q5-FFIeAJARRU";
            }
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => CacheManager.AppletWeChat.WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (!string.IsNullOrEmpty(token))
            {
                //string GetImageUrl = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + token;//获取二维码
                string GetImageUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token;//获取小程序码
                var postData = new
                {
                    path,
                    width
                };
                string pathName = Guid.NewGuid().ToString() + ".jpg";
                string basepath = AppContext.BaseDirectory;
                string path_server = basepath + "\\upfile\\temporary\\" + pathName;
                #region 微店头像
                var ssmodel = smallShopsInfoRepository.GetListForSingle(new RB_SmallShops_Info_Extend() { MallBaseId = mallBaseId, UserId = userId }).FirstOrDefault();
                string ssPhoto = ssmodel?.Logo ?? "";
                #endregion
                var Robj = HttpHelper.HttpPostForGetWXQRCodePathSmallShops(GetImageUrl, JsonHelper.Serialize(postData), path_server, ssPhoto);

                return "/upfile/temporary/" + pathName;
            }
            return "";
        }

        #endregion

        #region 推荐返佣账单

        /// <summary>
        /// 新增账单
        /// </summary>
        /// <param name="introductionIdList"></param>
        /// <param name="userId"></param>
        /// <param name="supplierId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetRecommendOrdersBillInfo(List<int> introductionIdList, int userId, int supplierId, int tenantId, int mallBaseId, int empId)
        {
            var list = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, IntroductionIds = string.Join(",", introductionIdList) });
            if (list.Any())
            {
                if (list.Where(x => x.CommissionState == 1 || x.RemitStatus == 1).Any())
                {
                    return false;
                }
                string OrderIds = string.Join(",", list.Select(x => x.OrderId ?? 0).Distinct());
                var olist = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderIds = OrderIds });
                decimal totalMoney = list.Sum(x => x.Commission ?? 0);
                int BillId = distributor_BillRepository.Insert(new Model.Entity.User.RB_Distributor_Bill()
                {
                    BillState = 1,
                    CreateDate = DateTime.Now,
                    EmpId = empId,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    Money = totalMoney,
                    Periods = DateTime.Now.ToString("yyyyMM"),
                    Remark = "",
                    Status = 0,
                    SupplierId = supplierId,
                    TenantId = tenantId,
                    UpdateDate = DateTime.Now,
                    UserId = userId
                });
                if (BillId > 0)
                {
                    //新增账单明细
                    foreach (var item in list)
                    {
                        distributor_BillDetailRepository.Insert(new Model.Entity.User.RB_Distributor_BillDetail()
                        {
                            BillId = BillId,
                            CommissionId = item.Id,
                            Id = 0,
                            CreateDate = DateTime.Now,
                            MallBaseId = mallBaseId,
                            OrderDetailId = item.OrderDetailId,
                            OrderId = item.OrderId,
                            Status = 0,
                            TenantId = tenantId,
                            UpdateDate = DateTime.Now
                        });
                        //更新返佣订单的佣金打款状态
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Goods_OrderIntroduction_Extend.RemitStatus),1}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods_OrderIntroduction_Extend.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        goods_OrderIntroductionRepository.Update(keyValues, wheres);

                        item.OrderNo = olist.Where(x => x.OrderId == item.OrderId).FirstOrDefault()?.OrderNo ?? "";
                    }
                    if (tenantId == 1)
                    {
                        //新增财务单据
                        OrderIncomeFinanceModuleForRecommend(userId, BillId, list, tenantId, mallBaseId);
                    }
                    return true;
                }
                return false;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取账单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Bill_Extend> GetRecommendOrdersBillPageList(int pageIndex, int pageSize, out long count, RB_Distributor_Bill_Extend demodel)
        {
            var list = distributor_BillRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询用户
                string userIds = string.Join(",", list.Select(x => x.UserId ?? 0));
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { UserIds = userIds });
                //查询供应商
                List<RB_Supplier_Extend> supplierList = new List<RB_Supplier_Extend>();
                if (list.Where(x => x.SupplierId > 0).Any())
                {
                    string supplierIds = string.Join(",", list.Where(x => x.SupplierId > 0).Select(x => x.SupplierId));
                    supplierList = supplierRepository.GetList(new RB_Supplier_Extend() { SupplierIds = supplierIds });
                }
                foreach (var item in list)
                {
                    item.UserName = ulist.Where(x => x.Id == item.UserId).FirstOrDefault()?.Name ?? "";
                    item.SupplierName = supplierList.Where(x => x.ID == item.SupplierId).FirstOrDefault()?.Name ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取账单明细列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public object GetRecommendOrdersBillDetailList(RB_Distributor_BillDetail_Extend demodel)
        {
            var bmodel = distributor_BillRepository.GetEntity(demodel.BillId);
            //获取用户  获取供应商
            var umodel = member_UserRepository.GetEntity(bmodel?.UserId ?? 0);
            var smodel = supplierRepository.GetEntity(bmodel?.SupplierId ?? 0);
            List<object> RList = new List<object>();
            var list = distributor_BillDetailRepository.GetList(new RB_Distributor_BillDetail_Extend() { BillId = demodel.BillId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
            if (list.Any())
            {
                //获取订单明细
                string DetailIds = string.Join(",", list.Select(x => x.OrderDetailId ?? 0));
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderDetailIds = DetailIds });
                //获取订单列表
                string OrderIds = string.Join(",", list.Select(x => x.OrderId ?? 0));
                var olist = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = OrderIds });
                //获取推荐返佣
                string IntroductionIds = string.Join(",", list.Select(x => x.CommissionId ?? 0));
                var introductionlist = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, IntroductionIds = IntroductionIds });
                decimal TotalMoney = introductionlist.Sum(x => x.Commission ?? 0);
                foreach (var item in introductionlist)
                {
                    var dmodel = dlist.Where(x => x.Id == item.OrderDetailId).FirstOrDefault();
                    if (dmodel != null)
                    {
                        var omodel = olist.Where(x => x.OrderId == item.OrderId).FirstOrDefault();
                        dmodel.OrderNo = omodel?.OrderNo ?? "";

                        var model = new
                        {
                            dmodel.OrderId,
                            dmodel.OrderNo,
                            dmodel.Id,
                            dmodel.CoverImage,
                            dmodel.GoodsName,
                            SpecificationList = JsonConvert.DeserializeObject<List<string>>(dmodel.Specification),
                            dmodel.ProductCode,
                            dmodel.Final_Price,
                            dmodel.Number,
                            OrderIntroduction = new
                            {
                                IntroductionId = item.Id,
                                UserName = item.UserName ?? "",
                                Name = item.Name ?? "",
                                Commission = item.Commission ?? 0,
                                CommissionState = item.CommissionState ?? 1,
                            }
                        };
                        RList.Add(model);
                    }
                }
                return new
                {
                    TotalMoney,
                    UserName = umodel.Name,
                    SupplierName = smodel?.Name ?? "",
                    RList
                };
            }
            return new
            {
                TotalMoney = 0,
                UserName = umodel.Name,
                SupplierName = smodel?.Name ?? "",
                RList
            };
        }

        /// <summary>
        /// 取消账单
        /// </summary>
        /// <param name="billId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public bool CancalRecommendOrdersBill(int billId, int tenantId, int mallBaseId, int empId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_Bill.BillState),3},
                { nameof(RB_Distributor_Bill.EmpId),empId},
                { nameof(RB_Distributor_Bill.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Distributor_Bill.Id),
                      FiledValue=billId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = distributor_BillRepository.Update(keyValues, wheres);

            if (flag)
            {
                //回滚 订单返佣状态
                var dlist = distributor_BillDetailRepository.GetList(new RB_Distributor_BillDetail_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, BillId = billId });
                if (dlist.Any())
                {
                    //查询所有返佣列表
                    string introductionIds = string.Join(",", dlist.Select(x => x.CommissionId ?? 0));
                    var iList = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, IntroductionIds = introductionIds });
                    foreach (var item in iList)
                    {
                        //回滚返佣订单的佣金打款状态
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            { nameof(RB_Goods_OrderIntroduction_Extend.RemitStatus),2}
                        };
                        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);
                    }
                }
            }
            return flag;
        }



        /// <summary>
        /// 获取商品订单介绍返佣表列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderIntroduction_Extend> GetOrderIntroductionList(RB_Goods_OrderIntroduction_Extend dmodel)
        {
            return goods_OrderIntroductionRepository.GetListByNormal(dmodel);
        }


        /// <summary>
        /// 获取用户分销订单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderIntroduction_Extend> GetOrderIntroductionPageList(int pageIndex, int pageSize, out long count, RB_Goods_OrderIntroduction_Extend demodel)
        {
            var oclist = goods_OrderIntroductionRepository.GetOrderIntroductionPageList(pageIndex, pageSize, out count, demodel);
            if (oclist.Any())
            {
                //获取用户
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });

                string orderIds = string.Join(",", oclist.Select(x => x.OrderId).Distinct());
                //查询订单明细
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = orderIds });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                    }
                }
                foreach (var item in oclist)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel?.Name ?? "";
                    item.Mobile = umodel?.Moblie ?? "";
                    item.Photo = umodel?.Photo ?? "";
                    item.OrderDetailList = new List<RB_Goods_OrderDetail_Extend>();
                    if (!string.IsNullOrWhiteSpace(item.OrderDetailIds))
                    {
                        var orderDetailIds = item.OrderDetailIds.Split(",");
                        foreach (var itemOrderDetailId in orderDetailIds)
                        {
                            if (!string.IsNullOrWhiteSpace(itemOrderDetailId))
                            {
                                item.OrderDetailList.AddRange(dlist.Where(x => x.OrderId == item.OrderId && x.Id == Convert.ToInt32(itemOrderDetailId)));
                            }
                        }
                    }
                    // item.OrderDetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();

                }
            }

            return oclist;
        }

        /// <summary>
        /// 获取我的账单详情
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_OrderIntroduction_Extend> GetOrderBilldetailPageList(int pageIndex, int pageSize, out long count, RB_Goods_OrderIntroduction_Extend demodel)
        {
            var oclist = goods_OrderIntroductionRepository.GetOrderBilldetailPageList(pageIndex, pageSize, out count, demodel);
            if (oclist.Any())
            {
                //获取用户
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });

                string orderIds = string.Join(",", oclist.Select(x => x.OrderId).Distinct());
                //查询订单明细
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, OrderIds = orderIds });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                    }
                }
                foreach (var item in oclist)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel?.Name ?? "";
                    item.Mobile = umodel?.Moblie ?? "";
                    item.Photo = umodel?.Photo ?? "";
                    item.OrderDetailList = new List<RB_Goods_OrderDetail_Extend>();
                    if (!string.IsNullOrWhiteSpace(item.OrderDetailIds))
                    {
                        var orderDetailIds = item.OrderDetailIds.Split(",");
                        foreach (var itemOrderDetailId in orderDetailIds)
                        {
                            if (!string.IsNullOrWhiteSpace(itemOrderDetailId))
                            {
                                item.OrderDetailList.AddRange(dlist.Where(x => x.OrderId == item.OrderId && x.Id == Convert.ToInt32(itemOrderDetailId)));
                            }
                        }
                    }
                }
            }

            return oclist;
        }





        /// <summary>
        /// 获取推荐供应商返佣账单列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Distributor_Bill_Extend> GetDistributorBillList(RB_Distributor_Bill_Extend dmodel)
        {
            return distributor_BillRepository.GetList(dmodel);
        }
        /// <summary>
        /// 修改备注
        /// </summary>
        /// <param name="billId"></param>
        /// <param name="remark"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public bool SetRecommendOrdersBillRemark(int billId, string remark, int tenantId, int mallBaseId, int empId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_Bill.Remark),remark},
                { nameof(RB_Distributor_Bill.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Distributor_Bill.Id),
                      FiledValue=billId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = distributor_BillRepository.Update(keyValues, wheres);
            return flag;
        }

        /// <summary>
        /// 获取账单实体
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Distributor_Bill GetBillModel(int Id)
        {
            var model = distributor_BillRepository.GetEntity(Id);
            return model;
        }

        /// <summary>
        /// 打款
        /// </summary>
        /// <param name="billId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public string SetRecommendOrdersBillRemit(int billId, int tenantId, int mallBaseId, int empId, string Remark = "")
        {
            var model = distributor_BillRepository.GetEntity(billId);
            if (model == null) { return "账单不存在"; }
            if (model.BillState != 1) { return "账单状态不正确"; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Distributor_Bill.BillState),2},
                { nameof(RB_Distributor_Bill.UpdateDate),DateTime.Now}
            };
            if (empId > 0)
            {
                keyValues.Add(nameof(RB_Distributor_Bill.EmpId), empId);
            }
            if (!string.IsNullOrEmpty(Remark))
            {
                keyValues.Add(nameof(RB_Distributor_Bill.Remark), (model.Remark ?? "") + " " + Remark);
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Distributor_Bill.Id),
                      FiledValue=billId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = distributor_BillRepository.Update(keyValues, wheres);
            if (flag)
            {
                return "";
            }
            else
            {
                return "保存失败";
            }
        }

        #endregion

        #region 会员购买
        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Member_Buy_Extend> GetMemberBuyPageList(int pageIndex, int pageSize, out long rowCount, RB_Member_Buy_Extend dmodel)
        {
            return memberBuyRepository.GetPageList(pageIndex, pageSize, out rowCount, dmodel);
        }


        /// <summary>
        /// 新增会员购买记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddMemberBuy(RB_Member_Buy_Extend model)
        {
            int id = 0;
            if (model.Id == 0)
            {
                id = memberBuyRepository.Insert(model);

            }
            return id;
        }



        /// <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}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper{
                         FiledName=nameof(RB_Member_Footmark.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 粉象返佣金额设置
        /// <summary>
        /// 返佣列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Distributor_FXCommission_Extend> GetFXCommissionList(RB_Distributor_FXCommission_Extend query)
        {
            return distributor_FXCommissionRepository.GetFXCommissionList(query);
        }


        /// <summary>
        /// 新增/修改返佣设置
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool AddOrUpdateFxCommission(List<RB_Distributor_FXCommission_Extend> list)
        {

            var trans = distributor_FXCommissionRepository.DbTransaction;
            try
            {
                foreach (var item in list)
                {
                    if (item.ID == 0)
                    {
                        item.CreateDate = System.DateTime.Now;
                        item.UpdateDate = System.DateTime.Now;
                        distributor_FXCommissionRepository.Insert(item, trans);
                    }
                    else if (item.ID > 0)
                    {
                        item.UpdateDate = System.DateTime.Now;
                        distributor_FXCommissionRepository.Update(item, trans);
                    }
                }
                distributor_FXCommissionRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                distributor_FXCommissionRepository.DBSession.Rollback("AddOrUpdateFxCommission");
                LogHelper.Write(ex, "AddOrUpdateFxCommission");
                return false;
            }
        }


        #endregion


        #region 申请微店



        public bool ApplySmallShopsInfo(RB_SmallShops_Info_Extend model)
        {
            if (model.Id == 0)
            {
                return smallShopsInfoRepository.Insert(model) > 0;
            }
            return false;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_SmallShops_Info_Extend> GetSmallShopsInfoList(RB_SmallShops_Info_Extend dmodel)
        {
            return smallShopsInfoRepository.GetList(dmodel);
        }

        /// <summary>
        /// 小程序用户更新微信名称、logo、公告
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateShopsInfo(RB_SmallShops_Info_Extend model)
        {
            if (model.Id > 0)
            {

                IDictionary<string, object> fileds = new Dictionary<string, object>()
                        {
                        { nameof(RB_SmallShops_Info.Name),model.Name},
                        { nameof(RB_SmallShops_Info.Logo),model.Logo},
                        { nameof(RB_SmallShops_Info.Notice),model.Notice},
                        { nameof(RB_SmallShops_Info.UpdateDate),model.UpdateDate},
                        };
                IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                        {
                            new WhereHelper (){ FiledName=nameof(RB_SmallShops_Info.Id),FiledValue=model.Id,OperatorEnum=OperatorEnum.Equal}
                        };
                return smallShopsInfoRepository.Update(fileds, whereHelpers);

            }
            return false;
        }

        /// <summary>
        /// 获取粉象我的团队标题列表
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GerSmallShopsMyTeamTitelListForFX(AppletUserInfo userInfo)
        {
            string UserIds = "-1";
            if (userInfo.SmallShopId > 0)
            {
                UserIds = member_UserRepository.GetSmallShopChildIdStr(userInfo.SmallShopId);
            }

            //获取下级所有等级
            var disList = distributor_InfoRepository.GetFXGreadeListForMyTeam(new RB_Distributor_Info_Extend() { UserIds = UserIds, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            var fxList = new List<RB_Distributor_FXGrade_Extend>();
            if (disList.Where(x => x.FXGradeId > 0).Any())
            {
                string fxgradeIds = string.Join(",", disList.Select(x => x.FXGradeId));
                fxList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { GradeIds = fxgradeIds, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                fxList = fxList.OrderByDescending(x => x.Grade).ToList();//倒序  最大的拍前面
            }
            else
            {
                //增加一个 普通会员等级
                fxList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { IsGuest = 1, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            }
            return fxList.Select(x => new
            {
                x.Id,
                x.GradeName
            });
        }

        /// <summary>
        /// 获取我的团队 (粉象)
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public object GetSmallShopsMyTeamPageListForFX(int pageIndex, int pageSize, out long count, RB_Distributor_Info_Extend demodel)
        {


            string UserIds = "-1";
            if ((demodel.UserId ?? 0) > 0)
            {
                UserIds = member_UserRepository.GetSmallShopChildIdStr(demodel.UserId ?? 0);
            }
            // string UserIds = member_UserRepository.GetSmallShopChildIdStr(demodel.UserId ?? 0);

            var list = member_UserRepository.GetPageListForFX(pageIndex, pageSize, out count, new RB_Member_User_Extend() { UserIds = UserIds, FXGradeId = demodel.FXGradeId, Name = demodel.Name, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
            List<object> RList = new List<object>();
            if (list.Any())
            {
                string userIds = string.Join(",", list.Select(x => x.Id));
                //获取推广人数
                var tList = member_UserRepository.GetDistributorReferralsNum(userIds, 1, demodel.TenantId, demodel.MallBaseId);
                //获取消费金额 + 订单数量
                var oList = goods_OrderRepository.GetUserOrderNumAndMoney(userIds, demodel.TenantId, demodel.MallBaseId);

                foreach (var item in list)
                {
                    int tgNum = tList.Where(x => x.SuperiorId == item.Id).FirstOrDefault()?.ReferralsNum ?? 0;
                    var orderModel = oList.Where(x => x.UserId == item.Id).FirstOrDefault();
                    RList.Add(new
                    {
                        UserId = item.Id,
                        UserName = item.Name,
                        item.Photo,
                        CreateDate = item.CreateDate.HasValue ? item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        GeneralizeNum = tgNum,
                        OrderNum = orderModel?.OrderNum ?? 0,
                        Income = orderModel?.Income ?? 0
                    });
                }
            }
            return RList;
        }





        /// <summary>
        /// 获取用户分销中心
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetSmallShopsCenter(AppletUserInfo userInfo)
        {
            // var basicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            var model = smallShopsInfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return "微店不存在";
            }
            if (model.AuditStatus != Common.Enum.User.DistributorAuditStatusEnum.Audited)
            {
                return "微店不存在";
            }

            //已提现佣金 //未结算佣金
            var commModel = smallShopsRemitRepository.GetDistributorCommissionStatiscs(userInfo.UserId);
            //提现总额
            var remitMoney = smallShopsRemitRepository.GetDistributorRemitCommission(userInfo.UserId);

            //分销订单
            decimal OrderCommission = smallShopsCommissionRepository.GetUserOrderCommissionStatistics(userInfo.UserId);
            //未结算返佣
            decimal WJSCommission = smallShopsCommissionRepository.GetSmallShopsCommissionNoSettlement(userInfo.UserId);



            //下线数量
            int smallShopsNum = 0;

            //求其所有下线的数量

            string UserIds = "";
            if (model.Id > 0)
            {
                UserIds = member_UserRepository.GetSmallShopChildIdStr(model.Id);
            }
            // UserIds = member_UserRepository.GetSmallShopChildIdStr(model.Id);
            if (!string.IsNullOrEmpty(UserIds))
            {
                string[] arr = UserIds.Split(',');
                smallShopsNum = arr.Length - 1;
            }

            //Vip购买返佣金额
            //decimal VipBuyCommission = vipBuy_CommissionRepository.getVipBuyCommissionMoney(userInfo.UserId);

            var CustomModel = smallShopsCustomRepository.GetSmallShopsCustomList(new RB_SmallShops_Custom { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (CustomModel == null)
            {
                return "";
            }
            return new
            {
                CustomModel = new
                {
                    CustomModel.HeadBackImage,
                    CustomModel.WithdrawalFilletPX,
                    CustomModel.WithdrawalText,
                    CustomModel.WithdrawalColor,
                    CustomModel.WithdrawalTextColor,
                    CustomModel.WithdrawalImage,
                    CustomModel.SmallShopOrderName,
                    CustomModel.SmallShopOrderImage,
                    CustomModel.WithdrawalDetailName,
                    CustomModel.WithdrawalDetailImage,
                    CustomModel.MyCustomerName,
                    CustomModel.MyCustomerImage,
                    CustomModel.SmallShopQRCodeName,
                    CustomModel.SmallShopQRCodeImage,
                    CustomModel.SmallShopSetUpName,
                    CustomModel.SmallShopSetUpImage,
                    CustomModel.LiveName,
                    CustomModel.LiveImage,
                    CustomModel.CommissionWithdrawnName,
                    CustomModel.OutstandingCommissionName,
                    CustomModel.WithdrawableName,
                    CustomModel.CommissionTobePaidName,
                    CustomModel.UserNotesName,
                    CustomModel.UserNotes,
                    CustomModel.IWantToWithdrawName,
                    CustomModel.WithdrawalAmountName,
                    CustomModel.WithdrawalWayName
                },
                UserInfo = new
                {
                    UserId = model.Id,
                    UserName = model.Name,
                    model.Logo,
                    Notice = string.IsNullOrWhiteSpace(model.Notice) ? "" : model.Notice,
                    GradeName = "",
                    CommissionWithdrawal = model.Commission ?? 0,//可提现佣金
                    TXCommission = commModel?.TXCommission ?? 0,//已提现佣金
                    WJSCommission, //未结算返佣
                    model.TotalCommission,//累计佣金
                    OrderCommission, //微店订单返佣
                    RemitMoney = remitMoney,  //提现总额
                    ReferralsNum = smallShopsNum,   //我的客户数    
                }
            };
        }


        #endregion
    }
}
