using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Mall.AOP.CustomerAttribute;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Entity.Product;
using Mall.Model.Entity.User;
using Mall.Model.Extend.BaseSetUp;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Model.Query;
using Mall.Repository;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Product;
using Mall.Repository.Reserve;
using Mall.Repository.User;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using VT.FW.DB;

namespace Mall.Module.Product
{
    /// <summary>
    /// 商品处理层
    /// </summary>
    public class ProductModule
    {
        /// <summary>
        /// 素材分组
        /// </summary>
        private readonly RB_Material_GroupRepository material_GroupRepository = new RB_Material_GroupRepository();
        /// <summary>
        /// 素材管理
        /// </summary>
        private readonly RB_Material_InfoRepository material_InfoRepository = new RB_Material_InfoRepository();
        /// <summary>
        /// 商品分类
        /// </summary>
        private readonly RB_Product_CategoryRepository product_CategoryRepository = new RB_Product_CategoryRepository();
        /// <summary>
        /// 商品分类样式
        /// </summary>
        private readonly RB_Product_CategoryStyleRepository product_CategoryStyleRepository = new RB_Product_CategoryStyleRepository();
        /// <summary>
        /// 商品规格
        /// </summary>
        private readonly RB_Product_SpecificationRepository product_SpecificationRepository = new RB_Product_SpecificationRepository();
        /// <summary>
        /// 快速购买
        /// </summary>
        private readonly RB_Product_QuickBuyRepository product_QuickBuyRepository = new RB_Product_QuickBuyRepository();
        /// <summary>
        /// 推荐设置
        /// </summary>
        private readonly RB_Product_RecommendRepository product_RecommendRepository = new RB_Product_RecommendRepository();
        /// <summary>
        /// 商品服务
        /// </summary>
        private readonly RB_Product_ServiceRepository product_ServiceRepository = new RB_Product_ServiceRepository();
        /// <summary>
        /// 商品
        /// </summary>
        private readonly RB_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 商品日志
        /// </summary>
        private readonly RB_Goods_LogRepository goods_LogRepository = new RB_Goods_LogRepository();
        /// <summary>
        /// 商品区域
        /// </summary>
        private readonly RB_Goods_AreaRepository goods_AreaRepository = new RB_Goods_AreaRepository();
        /// <summary>
        /// 商品分类
        /// </summary>
        private readonly RB_Goods_CategoryRepository goods_CategoryRepository = new RB_Goods_CategoryRepository();
        /// <summary>
        /// 商品规格
        /// </summary>
        private readonly RB_Goods_SpecificationRepository goods_SpecificationRepository = new RB_Goods_SpecificationRepository();
        /// <summary>
        /// 商品规格值
        /// </summary>
        private readonly RB_Goods_SpecificationValueRepository goods_SpecificationValueRepository = new RB_Goods_SpecificationValueRepository();
        /// <summary>
        /// 商品规格价格
        /// </summary>
        private readonly RB_Goods_SpecificationPriceRepository goods_SpecificationPriceRepository = new RB_Goods_SpecificationPriceRepository();
        /// <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_BasicsRepository distributor_BasicsRepository = new RB_Distributor_BasicsRepository();
        /// <summary>
        /// 会员等级
        /// </summary>
        private readonly RB_Member_GradeRepository member_GradeRepository = new RB_Member_GradeRepository();
        /// <summary>
        /// 用户管理
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 商品分销佣金
        /// </summary>
        private readonly RB_Goods_DistributionCommissionRepository goods_DistributionCommissionRepository = new RB_Goods_DistributionCommissionRepository();
        /// <summary>
        /// 商品会员价格
        /// </summary>
        private readonly RB_Goods_MemberPriceRepository goods_MemberPriceRepository = new RB_Goods_MemberPriceRepository();
        /// <summary>
        /// 运费
        /// </summary>
        private readonly RB_Logistics_RulesRepository logistics_RulesRepository = new RB_Logistics_RulesRepository();
        private readonly RB_Logistics_RulesRegionRepository logistics_RulesRegionRepository = new RB_Logistics_RulesRegionRepository();
        private readonly RB_Logistics_RulesPriceRepository logistics_RulesPriceRepository = new RB_Logistics_RulesPriceRepository();
        /// <summary>
        /// 商户仓储层对象
        /// </summary>
        private Mall.Repository.User.RB_MiniProgramRepository programRepository = new Repository.User.RB_MiniProgramRepository();
        /// <summary>
        /// 商品收藏
        /// </summary>
        private readonly RB_Member_CollectionRepository member_CollectionRepository = new RB_Member_CollectionRepository();
        /// <summary>
        /// 收货地址
        /// </summary>
        private readonly RB_Member_ShippingAddressRepository member_ShippingAddressRepository = new RB_Member_ShippingAddressRepository();
        /// <summary>
        /// 订单商品
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 地区处理
        /// </summary>
        private readonly Rb_destinationRepository destinationRepository = new Rb_destinationRepository();

        /// <summary>
        /// 和平返佣
        /// </summary>
        private readonly RB_Distributor_HPCommissionRepository distributor_HPCommissionRepository = new RB_Distributor_HPCommissionRepository();
        /// <summary>
        /// 和平返佣比例
        /// </summary>
        private readonly RB_Distributor_HPGradeRatioRepository distributor_HPGradeRatioRepository = new RB_Distributor_HPGradeRatioRepository();

        /// <summary>
        /// 商品分销
        /// </summary>
        private readonly RB_MiniProgram_GoodPosterRepository miniProgram_GoodPosterRepository = new RB_MiniProgram_GoodPosterRepository();
        /// <summary>
        /// 商品代理
        /// </summary>
        private readonly RB_Goods_ProxyRepository goods_ProxyRepository = new RB_Goods_ProxyRepository();
        /// <summary>
        /// 粉象返佣
        /// </summary>
        private readonly RB_Distributor_FXGradeRepository distributor_FXGradeRepository = new RB_Distributor_FXGradeRepository();
        /// <summary>
        /// 粉象VIP返佣比例
        /// </summary>
        private readonly RB_Distributor_FXCommissionRepository distributor_FXCommissionRepository = new RB_Distributor_FXCommissionRepository();

        private RB_FreeShippingRepository freeShippingRepository = new RB_FreeShippingRepository();

        /// <summary>
        /// 微店
        /// </summary>
        private RB_SmallShops_InfoRepository smallShops_InfoRepository = new RB_SmallShops_InfoRepository();
        /// <summary>
        /// 微店商品价格
        /// </summary>
        private RB_SmallShops_PriceRepository smallShops_PriceRepository = new RB_SmallShops_PriceRepository();
        /// <summary>
        /// 课程
        /// </summary>
        private readonly RB_Goods_WK_CourseRepository goods_WK_CourseRepository = new RB_Goods_WK_CourseRepository();
        /// <summary>
        /// 教师
        /// </summary>
        private readonly RB_Goods_WK_TeacherRepository goods_WK_TeacherRepository = new RB_Goods_WK_TeacherRepository();
        /// <summary>
        /// 网课学习
        /// </summary>
        private readonly RB_Goods_WK_CourseStudyRepository goods_WK_CourseStudyRepository = new RB_Goods_WK_CourseStudyRepository();

        /// <summary>
        /// 服务人员仓储仓储层对象
        /// </summary>
        private readonly RB_Reserve_ServicePersonalRepository reserve_ServicePersonalRepository = new RB_Reserve_ServicePersonalRepository();

        /// <summary>
        /// 门店仓储层对象
        /// </summary>
        private readonly RB_StoresRepository storesRepository = new RB_StoresRepository();

        #region 小程序接口

        /// <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="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetAppletGoodsPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetAppletGoodsPageList(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="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <param name="IsGetShare">1-获取分销佣金</param>
        /// <param name="GoodsClassify">商品类型</param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetAppletGoodsPageListForZY(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel, int IsGetShare = 0, int GoodsClassify = 0)
        {
            var list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out count, demodel, GoodsClassify: GoodsClassify);
            if (list.Any())
            {
                var SpecificationList = new List<RB_Goods_Specification_Extend>();
                var SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                if (list.Where(x => x.IsCustomSpecification == 1).Any())
                {
                    string goodsIds = string.Join(",", list.Where(x => x.IsCustomSpecification == 1).Select(x => x.Id));
                    SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (SpecificationList.Any())
                    {
                        var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        foreach (var item in svlist)
                        {
                            item.ImagePath = item.Image;
                        }
                        foreach (var item in SpecificationList)
                        {
                            item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                        }
                    }
                    SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                //会员价格
                var MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
                if (list.Where(x => x.EnjoyMember == 1 && x.SeparateSetMember == 1).Any())
                {
                    string goodsIds = string.Join(",", list.Where(x => x.EnjoyMember == 1 && x.SeparateSetMember == 1).Select(x => x.Id));
                    MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                string goodsIds2 = string.Join(",", list.Select(x => x.Id));
                List<RB_Goods_Order_Extend> orderlist = goods_OrderRepository.GetGoodsOrderNum(goodsIds: goodsIds2);

                //2020-08-06 Add by:W 查询商品分类获取分类包邮规则
                string allGoodsIds = string.Join(",", list.Where(x => ((x.FullMoneyPinkage ?? 0) == 0) && ((x.FullNumPinkage ?? 0) == 0)).Select(x => x.Id));
                var goodsCategoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = allGoodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                string categoryIds = string.Join(",", goodsCategoryList.Select(x => x.CategoryId).Distinct());
                List<RB_FreeShipping_Extend> freeShippingList = new List<RB_FreeShipping_Extend>();
                if (!string.IsNullOrWhiteSpace(categoryIds))
                {
                    freeShippingList = freeShippingRepository.GetFreeShippingListByCategoryIds(new RB_FreeShipping_Extend { MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId, CategoryIds = categoryIds });
                }
                //2020-08-06 Add by:W End
                #region 微店价格
                RB_SmallShops_Info smallModel = new RB_SmallShops_Info();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                if (demodel.SmallShopsId > 0)
                {
                    smallModel = smallShops_InfoRepository.GetEntity(demodel.SmallShopsId);
                    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = demodel.SmallShopsId, GoodsIds = goodsIds2 });
                }
                #endregion
                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];
                    }

                    item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                    item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                    if (item.IsCustomSpecification == 1)
                    {
                        item.SpecificationList = SpecificationList.Where(x => x.GoodsId == item.Id).ToList();
                        item.SpecificationPriceList = SpecificationPriceList.Where(x => x.GoodsId == item.Id).ToList();

                        if (demodel.SmallShopsId > 0)
                        {
                            if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                            {
                                foreach (var qitem in item.SpecificationPriceList)
                                {
                                    var sspModel = smallPList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == qitem.SpecificationSort).FirstOrDefault();
                                    if (sspModel != null)
                                    {
                                        //单商品设置的
                                        if (sspModel.PriceType == 1)
                                        {
                                            qitem.SellingPrice = (qitem.SellingPrice ?? 0) + Math.Ceiling((qitem.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            qitem.SellingPrice = (qitem.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                qitem.SellingPrice = (qitem.SellingPrice ?? 0) + Math.Ceiling((qitem.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                qitem.SellingPrice = (qitem.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                                item.SellingPrice = item.SpecificationPriceList.Min(x => x.SellingPrice);
                            }
                        }
                    }
                    else
                    {
                        if (demodel.SmallShopsId > 0)
                        {
                            if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                            {
                                var sspModel = smallPList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == "").FirstOrDefault();
                                if (sspModel != null)
                                {
                                    //单商品设置的
                                    if (sspModel.PriceType == 1)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                    }
                                    else if (sspModel.PriceType == 2)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                    }
                                }
                                else
                                {
                                    if ((smallModel.UpPrice ?? 0) > 0)
                                    {
                                        if (smallModel.PriceType == 1)
                                        {
                                            item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (smallModel.PriceType == 2)
                                        {
                                            item.SellingPrice = (item.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (item.EnjoyMember == 1 && item.SeparateSetMember == 1)
                    {
                        item.MemberPriceList = MemberPriceList.Where(x => x.GoodsId == item.Id).ToList();
                        #region 微店处理会员价格
                        if (item.MemberPriceList.Any() && demodel.SmallShopsId > 0)
                        {
                            if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                            {
                                foreach (var mqitem in item.MemberPriceList)
                                {
                                    var sspModel = smallPList.Where(x => x.SpecificationKey == mqitem.SpecificationSort).FirstOrDefault();
                                    if (sspModel != null)
                                    {
                                        //单商品设置的
                                        if (sspModel.PriceType == 1)
                                        {
                                            mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + Math.Ceiling((mqitem.MemberPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + Math.Ceiling((mqitem.MemberPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                    }

                    item.SalesNum += (orderlist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0);
                    //2020-08-06 Add by:W 查询商品分类获取分类包邮规则
                    if (freeShippingList != null && freeShippingList.Any() && ((item.FullMoneyPinkage ?? 0) == 0) && ((item.FullNumPinkage ?? 0) == 0))
                    {
                        var nowcategory = goodsCategoryList.Where(x => x.GoodsId == item.Id).Select(x => x.CategoryId);

                        var fullNumPinkageModel = freeShippingList.Where(x => nowcategory.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                        if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                        {
                            fullNumPinkageModel = freeShippingList.Where(x => nowcategory.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                        }
                        if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                        {
                            fullNumPinkageModel = freeShippingList.Where(x => nowcategory.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                        }
                        if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                        {
                            fullNumPinkageModel = freeShippingList.Where(x => nowcategory.Contains(x.CategoryId) && x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                        }
                        item.FreeShippingModel = (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0) ? new RB_FreeShipping_Extend() : fullNumPinkageModel;
                    }
                    else
                    {
                        item.FreeShippingModel = new RB_FreeShipping_Extend();
                    }
                    //2020-08-06 Add by:W End
                    //HK 2020-09-08新增
                    if (IsGetShare == 1)
                    {
                        var obj = GetAppletGoodsInfo_V2(item.Id, (demodel?.UserId ?? 0), (demodel?.SmallShopsId ?? 0), demodel.TenantId, demodel.MallBaseId);
                        if (obj != null)
                        {
                            item.ERPGoodObj = obj;
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 设置分类显示隐藏
        /// </summary>
        /// <param name="isShow"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetProductCategoryShow(int isShow, int tenantId, int mallBaseId)
        {
            return product_CategoryRepository.SetProductCategoryShow(isShow, tenantId, mallBaseId);
        }

        /// <summary>
        /// 获取商品推荐列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="RecommendStatus"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetAppletGoodsRecommendList(int pageIndex, int pageSize, out int RecommendStatus, RB_Goods_Extend demodel)
        {
            var rmodel = product_RecommendRepository.GetList(new RB_Product_Recommend_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            RecommendStatus = 2;
            if (rmodel == null)
            {
                return new List<RB_Goods_Extend>();
            }
            pageSize = rmodel.DetailRecommendNum ?? 0;
            if (demodel.RecommendType == 1)
            {
                RecommendStatus = rmodel.DetailRecommendStatus ?? 2;
                if (rmodel.DetailRecommendStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
            }
            else if (demodel.RecommendType == 2)
            {
                RecommendStatus = rmodel.OrderCompleteStatus ?? 2;
                if (rmodel.OrderCompleteStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
                if (rmodel.IsOrderRecommend == 1)
                {
                    pageSize = 20;
                    if (!string.IsNullOrEmpty(rmodel.OrderProductIds))
                    {
                        demodel.GoodsIds = rmodel.OrderProductIds;
                    }
                }
            }
            else if (demodel.RecommendType == 3)
            {
                RecommendStatus = rmodel.CommentRecommentStatus ?? 2;
                if (rmodel.CommentRecommentStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
                if (rmodel.IsCommentRecommend == 1)
                {
                    pageSize = 20;
                    if (!string.IsNullOrEmpty(rmodel.CommentProductIds))
                    {
                        demodel.GoodsIds = rmodel.CommentProductIds;
                    }
                }
            }

            List<RB_Goods_Extend> RList = new List<RB_Goods_Extend>();
            List<RB_Goods_Extend> list = new List<RB_Goods_Extend>();
            if (demodel.RecommendType == 1 && rmodel.DetailRecommendSame == 1 && demodel.GoodsId > 0)
            {
                //根据商品查询出分类
                var categoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = demodel.GoodsId });
                if (categoryList.Any())
                {
                    demodel.CategoryIds = string.Join(",", categoryList.Select(x => x.CategoryId ?? 0).Distinct());
                    demodel.NoGoodsId = demodel.GoodsId;
                    demodel.GoodsId = 0;
                    //根据分类 查询出商品列表
                    list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out long count, demodel);
                    //查看商品数量  不足的  根据以前逻辑查询出来补充
                    if (list.Count() < pageSize)
                    {
                        demodel.CategoryIds = "";
                        int pageSize2 = pageSize - list.Count();
                        var list2 = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize2, out long count2, demodel);
                        if (list2.Any())
                        {
                            foreach (var item in list2)
                            {
                                list.Add(item);
                            }
                        }
                    }
                    RList = list;
                }
                else
                {
                    demodel.GoodsId = 0;
                    list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out long count, demodel);
                    RList = list;
                }
            }
            else
            {
                list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out long count, demodel);
                RList = list;
            }
            if (list.Any())
            {
                if (demodel.RecommendType == 2 && rmodel.IsOrderRecommend == 1 && !string.IsNullOrEmpty(rmodel.OrderProductIds))
                {
                    List<int> gidList = JsonConvert.DeserializeObject<List<int>>(rmodel.OrderProductIds);
                    var gList = gidList.Where(x => list.Select(y => y.Id).Contains(x)).Take(10).ToList();
                    if (gList.Any())
                    {
                        RList = new List<RB_Goods_Extend>();
                        foreach (var item in gList)
                        {
                            RList.Add(list.Where(x => x.Id == item).FirstOrDefault());
                        }
                    }

                }
                else if (demodel.RecommendType == 3 && rmodel.IsCommentRecommend == 1 && !string.IsNullOrEmpty(rmodel.CommentProductIds))
                {
                    List<int> gidList = JsonConvert.DeserializeObject<List<int>>(rmodel.CommentProductIds);
                    var gList = gidList.Where(x => list.Select(y => y.Id).Contains(x)).Take(10).ToList();
                    if (gList.Any())
                    {
                        RList = new List<RB_Goods_Extend>();
                        foreach (var item in gList)
                        {
                            RList.Add(list.Where(x => x.Id == item).FirstOrDefault());
                        }
                    }
                }
                foreach (var item in RList)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                }
            }
            return RList;
        }

        /// <summary>
        /// 获取商品推荐列表(赞羊字段)
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="RecommendStatus"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetAppletGoodsRecommendListForZY(int pageIndex, int pageSize, out int RecommendStatus, RB_Goods_Extend demodel)
        {
            var rmodel = product_RecommendRepository.GetList(new RB_Product_Recommend_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            RecommendStatus = 2;
            if (rmodel == null)
            {
                return new List<RB_Goods_Extend>();
            }
            pageSize = rmodel.DetailRecommendNum ?? 0;
            if (demodel.RecommendType == 1)
            {
                RecommendStatus = rmodel.DetailRecommendStatus ?? 2;
                if (rmodel.DetailRecommendStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
            }
            else if (demodel.RecommendType == 2)
            {
                RecommendStatus = rmodel.OrderCompleteStatus ?? 2;
                if (rmodel.OrderCompleteStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
                if (rmodel.IsOrderRecommend == 1)
                {
                    pageSize = 20;
                    if (!string.IsNullOrEmpty(rmodel.OrderProductIds))
                    {
                        demodel.GoodsIds = rmodel.OrderProductIds;
                    }
                }
            }
            else if (demodel.RecommendType == 3)
            {
                RecommendStatus = rmodel.CommentRecommentStatus ?? 2;
                if (rmodel.CommentRecommentStatus != 1)
                {
                    return new List<RB_Goods_Extend>();
                }
                if (rmodel.IsCommentRecommend == 1)
                {
                    pageSize = 20;
                    if (!string.IsNullOrEmpty(rmodel.CommentProductIds))
                    {
                        demodel.GoodsIds = rmodel.CommentProductIds;
                    }
                }
            }

            List<RB_Goods_Extend> RList = new List<RB_Goods_Extend>();
            List<RB_Goods_Extend> list = new List<RB_Goods_Extend>();
            if (demodel.RecommendType == 1 && rmodel.DetailRecommendSame == 1 && demodel.GoodsId > 0)
            {
                //根据商品查询出分类
                var categoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = demodel.GoodsId });
                if (categoryList.Any())
                {
                    demodel.CategoryIds = string.Join(",", categoryList.Select(x => x.CategoryId ?? 0).Distinct());
                    demodel.NoGoodsId = demodel.GoodsId;
                    demodel.GoodsId = 0;
                    //根据分类 查询出商品列表
                    list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out long count, demodel);
                    //查看商品数量  不足的  根据以前逻辑查询出来补充
                    if (list.Count() < pageSize)
                    {
                        demodel.CategoryIds = "";
                        int pageSize2 = pageSize - list.Count();
                        var list2 = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize2, out long count2, demodel);
                        if (list2.Any())
                        {
                            foreach (var item in list2)
                            {
                                list.Add(item);
                            }
                        }
                    }
                    RList = list;
                }
                else
                {
                    list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out long count, demodel);
                    RList = list;
                }
            }
            else
            {
                demodel.GoodsId = 0;
                list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out long count, demodel);
                RList = list;
            }
            if (list.Any())
            {
                if (demodel.RecommendType == 2 && rmodel.IsOrderRecommend == 1 && !string.IsNullOrEmpty(rmodel.OrderProductIds))
                {
                    List<int> gidList = JsonConvert.DeserializeObject<List<int>>(rmodel.OrderProductIds);
                    var gList = gidList.Where(x => list.Select(y => y.Id).Contains(x)).Take(10).ToList();
                    if (gList.Any())
                    {
                        RList = new List<RB_Goods_Extend>();
                        foreach (var item in gList)
                        {
                            RList.Add(list.Where(x => x.Id == item).FirstOrDefault());
                        }
                    }

                }
                else if (demodel.RecommendType == 3 && rmodel.IsCommentRecommend == 1 && !string.IsNullOrEmpty(rmodel.CommentProductIds))
                {
                    List<int> gidList = JsonConvert.DeserializeObject<List<int>>(rmodel.CommentProductIds);
                    var gList = gidList.Where(x => list.Select(y => y.Id).Contains(x)).Take(10).ToList();
                    if (gList.Any())
                    {
                        RList = new List<RB_Goods_Extend>();
                        foreach (var item in gList)
                        {
                            RList.Add(list.Where(x => x.Id == item).FirstOrDefault());
                        }
                    }
                }


                var SpecificationList = new List<RB_Goods_Specification_Extend>();
                var SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                if (RList.Where(x => x.IsCustomSpecification == 1).Any())
                {
                    string goodsIds = string.Join(",", RList.Where(x => x.IsCustomSpecification == 1).Select(x => x.Id));
                    SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (SpecificationList.Any())
                    {
                        var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        foreach (var item in svlist)
                        {
                            item.ImagePath = item.Image;
                        }
                        foreach (var item in SpecificationList)
                        {
                            item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                        }
                    }
                    SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                //会员价格
                var MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
                if (RList.Where(x => x.EnjoyMember == 1 && x.SeparateSetMember == 1).Any())
                {
                    string goodsIds = string.Join(",", RList.Where(x => x.EnjoyMember == 1 && x.SeparateSetMember == 1).Select(x => x.Id));
                    MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                string goodsIds2 = string.Join(",", RList.Select(x => x.Id));
                List<RB_Goods_Order_Extend> orderlist = goods_OrderRepository.GetGoodsOrderNum(goodsIds: goodsIds2);

                #region 微店价格
                RB_SmallShops_Info smallModel = new RB_SmallShops_Info();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                if (demodel.SmallShopsId > 0)
                {
                    smallModel = smallShops_InfoRepository.GetEntity(demodel.SmallShopsId);
                    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = demodel.SmallShopsId, GoodsIds = goodsIds2 });
                }
                #endregion
                foreach (var item in RList)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }

                    item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                    item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                    if (item.IsCustomSpecification == 1)
                    {
                        item.SpecificationList = SpecificationList.Where(x => x.GoodsId == item.Id).ToList();
                        item.SpecificationPriceList = SpecificationPriceList.Where(x => x.GoodsId == item.Id).ToList();

                        if (demodel.SmallShopsId > 0)
                        {
                            if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                            {
                                foreach (var qitem in item.SpecificationPriceList)
                                {
                                    var sspModel = smallPList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == qitem.SpecificationSort).FirstOrDefault();
                                    if (sspModel != null)
                                    {
                                        //单商品设置的
                                        if (sspModel.PriceType == 1)
                                        {
                                            qitem.SellingPrice = (qitem.SellingPrice ?? 0) + Math.Ceiling((qitem.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            qitem.SellingPrice = (qitem.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                qitem.SellingPrice = (qitem.SellingPrice ?? 0) + Math.Ceiling((qitem.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                qitem.SellingPrice = (qitem.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                                item.SellingPrice = item.SpecificationPriceList.Min(x => x.SellingPrice);
                            }
                        }
                    }
                    else
                    {
                        if (demodel.SmallShopsId > 0)
                        {
                            if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                            {
                                var sspModel = smallPList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == "").FirstOrDefault();
                                if (sspModel != null)
                                {
                                    //单商品设置的
                                    if (sspModel.PriceType == 1)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                    }
                                    else if (sspModel.PriceType == 2)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                    }
                                }
                                else
                                {
                                    if ((smallModel.UpPrice ?? 0) > 0)
                                    {
                                        if (smallModel.PriceType == 1)
                                        {
                                            item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (smallModel.PriceType == 2)
                                        {
                                            item.SellingPrice = (item.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (item.EnjoyMember == 1 && item.SeparateSetMember == 1)
                    {
                        item.MemberPriceList = MemberPriceList.Where(x => x.GoodsId == item.Id).ToList();
                        #region 微店处理会员价格
                        if (item.MemberPriceList.Any() && demodel.SmallShopsId > 0)
                        {
                            if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                            {
                                foreach (var mqitem in item.MemberPriceList)
                                {
                                    var sspModel = smallPList.Where(x => x.SpecificationKey == mqitem.SpecificationSort).FirstOrDefault();
                                    if (sspModel != null)
                                    {
                                        //单商品设置的
                                        if (sspModel.PriceType == 1)
                                        {
                                            mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + Math.Ceiling((mqitem.MemberPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + Math.Ceiling((mqitem.MemberPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                    }

                    item.SalesNum += (orderlist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0);
                }
            }
            return RList;
        }

        /// <summary>
        /// 获取小程序商品详情
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="UserId"></param>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public RB_Goods_Extend GetAppletGoodsInfo(int goodsId, int UserId, int TenantId, int MallBaseId)
        {
            var model = goodsRepository.GetEntity(goodsId).RefMapperTo<RB_Goods_Extend>();
            if (model == null || model.TenantId != TenantId || model.MallBaseId != MallBaseId)
            {
                return null;
            }
            //小程序名称
            model.MallName = programRepository.GetEntity(model.MallBaseId)?.MallName ?? "";

            #region 基本信息
            //查询分类
            model.CategoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            //最大售价
            decimal MaxSellMoney = model.SellingPrice ?? 0;
            model.SpecificationList = new List<RB_Goods_Specification_Extend>();
            model.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
            if (model.IsCustomSpecification == 1)
            {
                model.SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (model.SpecificationList.Any())
                {
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in svlist)
                    {
                        item.ImagePath = item.Image;
                    }
                    foreach (var item in model.SpecificationList)
                    {
                        item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                    }
                }
                model.SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                MaxSellMoney = model.SpecificationPriceList.Max(x => x.SellingPrice ?? 0);
            }
            //区域
            model.AreaList = new List<RB_Goods_Area_Extend>();
            if (model.IsAreaBuy == 1)
            {
                model.AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //返佣
            model.DistributionCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
            if (model.SeparateDistribution == 1)
            {
                model.DistributionCommissionList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //会员价格
            model.MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
            {
                model.MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //轮播
            model.CarouselImageList = new List<RB_ImageCommonModel>();
            if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
            {
                List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                //轮播图
                foreach (var item in CarouselIdList)
                {
                    model.CarouselImageList.Add(new RB_ImageCommonModel()
                    {
                        Id = 0,
                        Name = "",
                        Path = item
                    });
                }
            }

            model.CustomShareImagePath = model.CustomShareImage;

            //服务列表
            model.ServiceList = new List<RB_ImageCommonModel>();
            if (model.IsDefaultService == 2)
            {
                if (!string.IsNullOrEmpty(model.GoodsService) && model.GoodsService != "[]")
                {
                    List<int> ServiceIds = JsonConvert.DeserializeObject<List<int>>(model.GoodsService);
                    var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { ServiceIds = string.Join(",", ServiceIds), TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in slist)
                    {
                        model.ServiceList.Add(new RB_ImageCommonModel()
                        {
                            Id = item.Id,
                            Name = item.Name
                        });
                    }
                }
            }
            else if (model.IsDefaultService == 1)
            {
                var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { IsDefault = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                foreach (var item in slist)
                {
                    model.ServiceList.Add(new RB_ImageCommonModel()
                    {
                        Id = item.Id,
                        Name = item.Name
                    });
                }
            }
            //表单
            if (model.FormsId > 0)
            {
                model.FormsName = "未建表";
            }
            else
            {
                model.FormsName = "默认表单";
            }
            #endregion

            #region 是否收藏
            model.Favorite = false;
            if (UserId > 0)
            {
                List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.UserId),
                      FiledValue=UserId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.GoodsId),
                      FiledValue=goodsId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.TenantId),
                      FiledValue=TenantId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.MallBaseId),
                      FiledValue=MallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                },
            };
                if (member_CollectionRepository.Exists(wheres))
                {
                    model.Favorite = true;
                }
            }
            #endregion

            #region 快递费用
            //运费
            Model.Entity.BaseSetUp.RB_Logistics_Rules rulesModel = new Model.Entity.BaseSetUp.RB_Logistics_Rules();
            if (model.FreightId > 0)
            {
                rulesModel = logistics_RulesRepository.GetEntity(model.FreightId);
                model.FreightName = rulesModel?.RulesName ?? "";
            }
            else
            {
                model.FreightName = "默认运费";
            }
            model.Express = 0;
            if (UserId > 0 && model.FreightId >= 0)
            {
                int FreightId = 0;
                if (model.FreightId == 0)
                {
                    //查询默认
                    FreightId = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { IsDefault = 1, TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault()?.ID ?? 0;
                }
                if (FreightId > 0)
                {
                    var samodel = member_ShippingAddressRepository.GetList(new RB_Member_ShippingAddress_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, IsDefault = 1 }).FirstOrDefault();
                    List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList = logistics_RulesPriceRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, RulesId = FreightId });
                    if (priceList.Any() && samodel != null)
                    {
                        string priceIds = string.Join(",", priceList.Select(x => x.ID));
                        var regionList = logistics_RulesRegionRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, PriceIds = priceIds });
                        List<int> disList = new List<int>();
                        disList.Add(samodel.Province ?? 0);
                        disList.Add(samodel.City ?? 0);
                        disList.Add(samodel.District ?? 0);
                        var regionModel = regionList.Where(x => disList.Contains(x.RegionId)).FirstOrDefault();
                        if (regionModel != null)
                        {
                            var pmodel = priceList.Where(x => x.ID == regionModel.RulesPriceId).FirstOrDefault();
                            if (pmodel != null && rulesModel != null)
                            {
                                if (rulesModel.ChargeMode == Common.Enum.MallBase.ChargeModeEnum.Num)
                                {
                                    model.Express = pmodel.FirstPrice;
                                }
                                else
                                {
                                    //重量计费
                                    int TotalW = model.GoodsWeight ?? 0;
                                    if (TotalW <= pmodel.First)
                                    {
                                        model.Express = pmodel.FirstPrice;
                                    }
                                    else
                                    {
                                        if (pmodel.Second > 0)
                                        {
                                            if ((TotalW - pmodel.First) % pmodel.Second == 0)
                                            {
                                                model.Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                            }
                                            else
                                            {
                                                model.Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                            }
                                        }
                                        else
                                        {
                                            model.Express = pmodel.FirstPrice;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region 最高返佣
            model.MaxShare = 0;
            if (UserId > 0)
            {
                //获取分销商信息
                var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                if (disModel != null)
                {
                    //判断是否开启和平返佣
                    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
                        }
                    };
                    if (distributor_HPCommissionRepository.Exists(wheres))
                    {
                        //获取和平分销返佣
                        if (disModel.HPGradeId > 0 && model.CostPrice > 0)
                        {
                            string categoryids = string.Join(",", model.CategoryList.Select(x => x.CategoryId));
                            var hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, CategoryIdsT = categoryids, TenantId = TenantId, MallBaseId = MallBaseId });
                            if (hpcList.Any())
                            {
                                RB_Distributor_HPCommission_Extend hpcModel;
                                if (hpcList.Where(x => x.IsCommon != 1).Any())
                                {
                                    //有使用非通用返佣
                                    hpcModel = hpcList.Where(x => x.IsCommon != 1).FirstOrDefault();
                                }
                                else
                                {
                                    //查询通用返佣
                                    hpcModel = hpcList.Where(x => x.IsCommon == 1).FirstOrDefault();
                                }
                                //查询所有返佣比例
                                var gList = distributor_HPGradeRatioRepository.GetList(new RB_Distributor_HPGradeRatio_Extend() { CommissionId = hpcModel.Id, TenantId = TenantId, MallBaseId = MallBaseId });

                                var ratioModel = gList.Where(x => x.GradeId == disModel.HPGradeId).FirstOrDefault();
                                decimal MPrice = (model.CostPrice ?? 0) / (1 - ((ratioModel.CommissionRatio ?? 0) / 100));
                                model.MaxShare = MaxSellMoney - MPrice > 0 ? MaxSellMoney - MPrice : 0;
                                if (hpcModel.DecimalType == 1)
                                {
                                    model.MaxShare = Math.Ceiling(model.MaxShare);
                                }
                                else if (hpcModel.DecimalType == 2)
                                {
                                    model.MaxShare = Math.Ceiling(model.MaxShare * 100) / 100;
                                }
                            }
                        }
                    }
                    else
                    {
                        var BasicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
                        if (model.SeparateDistribution == 1)
                        {
                            var dcList = model.DistributionCommissionList.Where(x => x.DistributorGrade == disModel.GradeId).ToList();
                            if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                            {
                                model.MaxShare = dcList.Max(x => (x.OneCommission ?? 0) + (x.TwoCommission ?? 0) + (x.ThreeCommission ?? 0));
                            }
                            else
                            {
                                model.MaxShare = dcList.Max(x => x.OneCommission ?? 0);
                            }
                            // 这里需注意，可能需要分销 是否提所有返佣控制
                            if (model.SeparateDistributionMoneyType == 1)
                            {
                                model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                            }
                        }
                        else
                        {
                            if (disModel.GradeId == 0)
                            {
                                //拿分销基础配置
                                if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                {
                                    model.MaxShare = (BasicsModel?.OneCommission ?? 0) + (BasicsModel?.TwoCommission ?? 0) + (BasicsModel?.ThreeCommission ?? 0);
                                }
                                else
                                {
                                    model.MaxShare = BasicsModel?.OneCommission ?? 0;
                                }
                                if ((BasicsModel?.DistributorCommissionType ?? 2) == 1)
                                {
                                    model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                }
                            }
                            else if (disModel.GradeId > 0)
                            {
                                //获取分销商等级
                                var disgradeModel = distributor_GradeRepository.GetEntity(disModel.GradeId);
                                if (disgradeModel != null)
                                {
                                    if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                    {
                                        model.MaxShare = (disgradeModel?.OneCommission ?? 0) + (disgradeModel?.TwoCommission ?? 0) + (disgradeModel?.ThreeCommission ?? 0);
                                    }
                                    else
                                    {
                                        model.MaxShare = disgradeModel?.OneCommission ?? 0;
                                    }
                                    if ((disgradeModel?.DistributionCommissionType ?? 2) == 1)
                                    {
                                        model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion
            return model;
        }

        /// <summary>
        /// 获取商品分享
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="userId"></param>
        /// <param name="path"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="IsOpenSchool">是否开启校园版(1-开启)</param>
        /// <returns></returns>
        public object GetAppletGoodsShareInfo(int goodsId, int userId, string path, int mallBaseId, int IsOpenSchool = 0)
        {
            string QRPath = GetWeiXinQRCode(path, 430, mallBaseId);
            var umodel = member_UserRepository.GetEntity(userId);
            var goodsModel = goodsRepository.GetEntity(goodsId);
            //商品海报配置信息
            var config = new object();
            //商品信息
            var info = new object();
            var goodsPoster = miniProgram_GoodPosterRepository.GetEntityExtRepository(new RB_MiniProgram_GoodPoster_Extend()
            {
                MallBaseId = mallBaseId,
                IsOpenSchool = IsOpenSchool
            });
            config = new
            {
                poster_style = goodsPoster?.PosterStyleList ?? new List<int>() { 1 },
                image_style = goodsPoster?.GoodsImgCountList ?? new List<int>() { 1 },
                color = new List<string>()
                {
                 "#fc4a3b",
                 "#ff7b22",
                 "#ffc73f",
                 "#3e9b6a",
                 "#4bb1ff",
                 "#8548ef",
                 "#000000",
                 "#a0a0a0",
                 "#FFFFFF"
                }
            };
            if (goodsModel == null)
            {
                info = new
                {
                    goods_name = "",
                    multi_map = new List<string>(),
                    is_negotiable = 0,
                    min_price = 0,
                    max_price = 0,
                    nickname = umodel?.Name ?? "",
                    avatar = umodel?.Photo ?? "",
                    qrcode_url = QRPath,
                    sign = ""
                };
            }
            else
            {
                //商品图片处理
                var imgList = new List<string>();
                if (!string.IsNullOrEmpty(goodsModel.CarouselImage) && goodsModel.CarouselImage != "[]")
                {
                    imgList = JsonConvert.DeserializeObject<List<string>>(goodsModel.CarouselImage);
                }
                if (imgList.Any())
                {
                    if (imgList.Count() < 8)
                    {
                        var imgList2 = new List<string>();
                        int Num = 8 / imgList.Count();
                        for (var i = 0; i < Num + 1; i++)
                        {
                            imgList2.AddRange(imgList);
                        }
                        imgList = imgList2.Take(8).ToList();
                    }
                }
                info = new
                {
                    goods_name = goodsModel.Name,
                    multi_map = imgList,
                    is_negotiable = 0,
                    min_price = goodsModel.SellingPrice,
                    max_price = goodsModel.SellingPrice,
                    nickname = umodel?.Name ?? "",
                    avatar = umodel?.Photo ?? "",
                    qrcode_url = QRPath,
                    sign = ""
                };
            }
            var obj = new
            {
                config,
                info
            };
            return obj;
        }

        #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 = programRepository.GetEntity(mallBaseId);
            string token = CacheManager.AppletWeChat.WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            int IsNormalServer = Convert.ToInt32(Config.IsNormalServer);
            if (IsNormalServer != 1)
            {
                token = "38_LJMrD0ffPj7GXvXxgGMwDMx9Qs_tXYe0HObmYw_2IGQUTRWSk9WbmrROPvEHEGgroSkhOctTFXFO1RAcYKo0uxrTHw5aRz9NXZ_t3Tp4M486c5XkLvPamTfWg_LaegNpvAqfVGWR-IiBbVL9GURgACAUIF";
            }
            if (string.IsNullOrEmpty(token))
            {
                token = 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 Robj = HttpHelper.HttpPostForGetWXQRCodePath(GetImageUrl, JsonHelper.Serialize(postData), path_server);
                //var Robj1 = HttpHelper.HttpPost(GetImageUrl, JsonHelper.Serialize(postData), "");
                return "/upfile/temporary/" + pathName;
            }
            return "";
        }

        #endregion

        /// <summary>
        /// 获取小程序商品详情
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="UserId"></param>
        /// <param name="SmallShopsId"></param>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public object GetAppletGoodsInfo_V2(int goodsId, int UserId, int SmallShopsId, int TenantId, int MallBaseId)
        {
            var model = goodsRepository.GetEntity(goodsId).RefMapperTo<RB_Goods_Extend>();
            if (model == null || model.TenantId != TenantId || model.MallBaseId != MallBaseId)
            {
                return null;
            }
            else
            {
                model.CoverImage = "";
                if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
                {
                    List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                    //封面图
                    model.CoverImage = CarouselIdList[0];
                }
            }
            //小程序名称
            model.MallName = programRepository.GetEntity(model.MallBaseId)?.MallName ?? "";

            RB_Member_User_Extend userModel = new RB_Member_User_Extend();
            if (UserId > 0)
            {
                userModel = GetMemberUserInfo(UserId);
                if (SmallShopsId == 0)
                {
                    SmallShopsId = userModel.SmallShopId;
                }
            }

            #region 基本信息
            //查询分类
            model.CategoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });

            //2020-08-05  根据分类查找商品对应的分类包邮规则 add by :W 
            if (model.CategoryList != null && model.CategoryList.Any())
            {
                string categoryIds = string.Join(",", model.CategoryList.Select(x => x.CategoryId));
                var freeShippingList = freeShippingRepository.GetFreeShippingListByCategoryIds(new RB_FreeShipping_Extend { MallBaseId = model.MallBaseId, TenantId = model.TenantId, CategoryIds = categoryIds });
                if (freeShippingList != null && freeShippingList.Any() && ((model.FullNumPinkage ?? 0) == 0) && ((model.FullMoneyPinkage ?? 0) == 0))
                {
                    var fullNumPinkageModel = freeShippingList.Where(x => x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                    if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                    {
                        fullNumPinkageModel = freeShippingList.Where(x => x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId > 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                    }
                    if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                    {
                        fullNumPinkageModel = freeShippingList.Where(x => x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullNumPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullNumPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                    }
                    if (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0)
                    {
                        fullNumPinkageModel = freeShippingList.Where(x => x.IsFreeShipping == 1 && x.IsEnable == 1 && x.FullMoneyPinkage > 0 && x.CategoryId == 0).OrderBy(x => x.FullMoneyPinkage).ThenByDescending(x => x.ID).FirstOrDefault();
                    }
                    model.FreeShippingModel = (fullNumPinkageModel == null || fullNumPinkageModel.ID <= 0) ? new RB_FreeShipping_Extend() : fullNumPinkageModel;
                }
                else
                {
                    model.FreeShippingModel = new RB_FreeShipping_Extend();
                }
            }

            #region 微店价格
            RB_SmallShops_Info smallModel = new RB_SmallShops_Info();
            List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
            if (SmallShopsId > 0)
            {
                smallModel = smallShops_InfoRepository.GetEntity(SmallShopsId);
                smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = SmallShopsId, GoodsId = goodsId });
                if (((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.UpPrice > 0).Any()))
                {
                    var sspModel = smallPList.Where(x => x.SpecificationKey == "").FirstOrDefault();
                    if (sspModel != null)
                    {
                        //单商品设置的
                        if (sspModel.PriceType == 1)
                        {
                            model.SellingPrice = (model.SellingPrice ?? 0) + Math.Ceiling((model.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                            model.OriginalPrice = (model.OriginalPrice ?? 0) + Math.Ceiling((model.OriginalPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                        }
                        else if (sspModel.PriceType == 2)
                        {
                            model.SellingPrice = (model.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                            model.OriginalPrice = (model.OriginalPrice ?? 0) + (sspModel.UpPrice ?? 0);
                        }
                    }
                    else
                    {
                        if ((smallModel.UpPrice ?? 0) > 0)
                        {
                            if (smallModel.PriceType == 1)
                            {
                                model.SellingPrice = (model.SellingPrice ?? 0) + Math.Ceiling((model.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                model.OriginalPrice = (model.OriginalPrice ?? 0) + Math.Ceiling((model.OriginalPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                            }
                            else if (smallModel.PriceType == 2)
                            {
                                model.SellingPrice = (model.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                model.OriginalPrice = (model.OriginalPrice ?? 0) + (smallModel.UpPrice ?? 0);
                            }
                        }
                    }
                }
            }
            #endregion

            //最大售价
            decimal MaxSellMoney = model.SellingPrice ?? 0;
            model.SpecificationList = new List<RB_Goods_Specification_Extend>();
            model.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
            if (model.IsCustomSpecification == 1)
            {
                model.SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (model.SpecificationList.Any())
                {
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in svlist)
                    {
                        item.ImagePath = item.Image;
                    }
                    foreach (var item in model.SpecificationList)
                    {
                        item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                    }
                }
                model.SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (SmallShopsId > 0)
                {
                    if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.UpPrice > 0).Any())
                    {
                        foreach (var item in model.SpecificationPriceList)
                        {
                            var sspModel = smallPList.Where(x => x.SpecificationKey == item.SpecificationSort).FirstOrDefault();
                            if (sspModel != null)
                            {
                                //单商品设置的
                                if (sspModel.PriceType == 1)
                                {
                                    item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                }
                                else if (sspModel.PriceType == 2)
                                {
                                    item.SellingPrice = (item.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                }
                            }
                            else
                            {
                                if ((smallModel.UpPrice ?? 0) > 0)
                                {
                                    if (smallModel.PriceType == 1)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                    }
                                    else if (smallModel.PriceType == 2)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                    }
                                }
                            }
                        }
                    }
                }
                MaxSellMoney = model.SpecificationPriceList.Max(x => x.SellingPrice ?? 0);
                model.SellingPrice = model.SpecificationPriceList.Min(x => x.SellingPrice ?? 0);
                decimal MaxPrice = MaxSellMoney + Math.Ceiling(MaxSellMoney / 10);
                if (MaxPrice > model.OriginalPrice)
                {
                    model.OriginalPrice = MaxPrice;
                }
            }
            //区域
            model.AreaList = new List<RB_Goods_Area_Extend>();
            if (model.IsAreaBuy == 1)
            {
                model.AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //返佣
            model.DistributionCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
            if (model.SeparateDistribution == 1)
            {
                model.DistributionCommissionList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //会员价格
            model.MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
            {
                model.MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }

            #region 微店处理会员价格
            if (model.MemberPriceList.Any() && SmallShopsId > 0)
            {
                if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.UpPrice > 0).Any())
                {
                    foreach (var item in model.MemberPriceList)
                    {
                        var sspModel = smallPList.Where(x => x.SpecificationKey == item.SpecificationSort).FirstOrDefault();
                        if (sspModel != null)
                        {
                            //单商品设置的
                            if (sspModel.PriceType == 1)
                            {
                                item.MemberPrice = (item.MemberPrice ?? 0) + Math.Ceiling((item.MemberPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                            }
                            else if (sspModel.PriceType == 2)
                            {
                                item.MemberPrice = (item.MemberPrice ?? 0) + (sspModel.UpPrice ?? 0);
                            }
                        }
                        else
                        {
                            if ((smallModel.UpPrice ?? 0) > 0)
                            {
                                if (smallModel.PriceType == 1)
                                {
                                    item.MemberPrice = (item.MemberPrice ?? 0) + Math.Ceiling((item.MemberPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                }
                                else if (smallModel.PriceType == 2)
                                {
                                    item.MemberPrice = (item.MemberPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            //轮播
            model.CarouselImageList = new List<RB_ImageCommonModel>();
            if (!string.IsNullOrWhiteSpace(model.VideoAddress))
            {
                model.CarouselImageList.Add(new RB_ImageCommonModel()
                {
                    Id = 0,
                    Name = "",
                    Type = 1,
                    Path = model.VideoAddress
                });
            }
            if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
            {
                List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                //轮播图
                foreach (var item in CarouselIdList)
                {
                    model.CarouselImageList.Add(new RB_ImageCommonModel()
                    {
                        Id = 0,
                        Name = "",
                        Path = item
                    });
                }
            }

            model.CustomShareImagePath = model.CustomShareImage;

            //服务列表
            model.ServiceList = new List<RB_ImageCommonModel>();
            if (model.IsDefaultService == 2)
            {
                if (!string.IsNullOrEmpty(model.GoodsService) && model.GoodsService != "[]")
                {
                    List<int> ServiceIds = JsonConvert.DeserializeObject<List<int>>(model.GoodsService);
                    var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { ServiceIds = string.Join(",", ServiceIds), TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in slist)
                    {
                        model.ServiceList.Add(new RB_ImageCommonModel()
                        {
                            Id = item.Id,
                            Name = item.Name
                        });
                    }
                }
            }
            else if (model.IsDefaultService == 1)
            {
                var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { IsDefault = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                foreach (var item in slist)
                {
                    model.ServiceList.Add(new RB_ImageCommonModel()
                    {
                        Id = item.Id,
                        Name = item.Name
                    });
                }
            }
            //表单
            if (model.FormsId > 0)
            {
                model.FormsName = "未建表";
            }
            else
            {
                model.FormsName = "默认表单";
            }
            #endregion

            #region 是否收藏
            model.Favorite = false;
            if (UserId > 0)
            {
                List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.UserId),
                      FiledValue=UserId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.GoodsId),
                      FiledValue=goodsId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.TenantId),
                      FiledValue=TenantId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.MallBaseId),
                      FiledValue=MallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                },
            };
                if (member_CollectionRepository.Exists(wheres))
                {
                    model.Favorite = true;
                }
            }
            #endregion

            #region 快递费用
            //运费
            Model.Entity.BaseSetUp.RB_Logistics_Rules rulesModel = new Model.Entity.BaseSetUp.RB_Logistics_Rules();
            if (model.FreightId > 0)
            {
                rulesModel = logistics_RulesRepository.GetEntity(model.FreightId);
                model.FreightName = rulesModel?.RulesName ?? "";
            }
            else
            {
                model.FreightName = "默认运费";
            }
            model.Express = 0;
            if (UserId > 0 && model.FreightId >= 0)
            {
                int FreightId = model.FreightId ?? 0;
                if (model.FreightId == 0)
                {
                    //查询默认
                    FreightId = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { IsDefault = 1, TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault()?.ID ?? 0;
                }
                if (FreightId > 0)
                {
                    var samodel = member_ShippingAddressRepository.GetList(new RB_Member_ShippingAddress_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, IsDefault = 1 }).FirstOrDefault();
                    List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList1 = logistics_RulesPriceRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, RulesId = FreightId });
                    if (priceList1.Any() && samodel != null)
                    {
                        string priceIds = string.Join(",", priceList1.Select(x => x.ID));
                        var regionList = logistics_RulesRegionRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, PriceIds = priceIds });
                        List<int> disList = new List<int>();
                        disList.Add(samodel.Province ?? 0);
                        disList.Add(samodel.City ?? 0);
                        disList.Add(samodel.District ?? 0);
                        var regionModel = regionList.Where(x => disList.Contains(x.RegionId)).FirstOrDefault();
                        if (regionModel != null)
                        {
                            var pmodel = priceList1.Where(x => x.ID == regionModel.RulesPriceId).FirstOrDefault();
                            if (pmodel != null && rulesModel != null)
                            {
                                if (rulesModel.ChargeMode == Common.Enum.MallBase.ChargeModeEnum.Num)
                                {
                                    model.Express = pmodel.FirstPrice;
                                }
                                else
                                {
                                    //重量计费
                                    int TotalW = model.GoodsWeight ?? 0;
                                    if (TotalW <= pmodel.First)
                                    {
                                        model.Express = pmodel.FirstPrice;
                                    }
                                    else
                                    {
                                        if (pmodel.Second > 0)
                                        {
                                            if ((TotalW - pmodel.First) % pmodel.Second == 0)
                                            {
                                                model.Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                            }
                                            else
                                            {
                                                model.Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                            }
                                        }
                                        else
                                        {
                                            model.Express = pmodel.FirstPrice;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region 最高返佣
            model.MaxShare = 0;
            decimal MyBuyCommission = 0;//自购返利
            var BasicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (UserId > 0)
            {
                //获取分销商信息
                var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                if (disModel != null)
                {
                    if ((BasicsModel?.IsEnableFXGrade ?? 2) == 1)
                    {
                        if ((model.PresentFXGrade ?? 0) == 0)
                        {
                            var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = TenantId, MallBaseId = MallBaseId });
                            if (FXList.Any() && FXList.Where(x => x.IsGuest == 1).Any())
                            {
                                var FXModel = FXList.Where(x => x.Id == disModel.FXGradeId).FirstOrDefault();
                                var PModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
                                if (FXModel != null && PModel != null)
                                {
                                    decimal CRate = 0;
                                    if (FXModel.Id == PModel.Id)
                                    {
                                        CRate = FXModel.SiblingRatio ?? 0;
                                    }
                                    else
                                    {
                                        CRate = (FXModel.CommissionRatio ?? 0) - (PModel.CommissionRatio ?? 0);
                                    }

                                    if (model.IsCustomSpecification == 1)
                                    {
                                        var dcModel = model.SpecificationPriceList.OrderByDescending(x => x.Commission).FirstOrDefault();
                                        if (dcModel.Commission > 0)
                                        {
                                            if (FXModel.DecimalType == 1)
                                            {
                                                model.MaxShare = Math.Ceiling(dcModel.Commission * CRate / 100);
                                                MyBuyCommission = Math.Ceiling(dcModel.Commission * (FXModel.CommissionRatio ?? 0) / 100);
                                            }
                                            else
                                            {
                                                model.MaxShare = Math.Ceiling(dcModel.Commission * CRate) / 100;
                                                MyBuyCommission = Math.Ceiling(dcModel.Commission * (FXModel.CommissionRatio ?? 0)) / 100;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (model.Commission > 0)
                                        {
                                            if (FXModel.DecimalType == 1)
                                            {
                                                model.MaxShare = Math.Ceiling(model.Commission * CRate / 100);
                                                MyBuyCommission = Math.Ceiling(model.Commission * (FXModel.CommissionRatio ?? 0) / 100);
                                            }
                                            else
                                            {
                                                model.MaxShare = Math.Ceiling(model.Commission * CRate) / 100;
                                                MyBuyCommission = Math.Ceiling(model.Commission * (FXModel.CommissionRatio ?? 0)) / 100;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //是否展示分享vip佣金
                            var fxcommissionList = distributor_FXCommissionRepository.GetFXCommissionList(new RB_Distributor_FXCommission_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, FXGradeId = disModel.FXGradeId ?? 0 });
                            if (fxcommissionList.Any())
                            {
                                model.MaxShare = fxcommissionList.Max(x => x.CommissionPrice ?? 0);
                            }
                        }
                    }
                    else
                    {
                        //判断是否开启和平返佣
                        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
                        }
                    };
                        if (distributor_HPCommissionRepository.Exists(wheres))
                        {
                            //获取和平分销返佣
                            if (disModel.HPGradeId > 0 && model.CostPrice > 0)
                            {
                                string categoryids = string.Join(",", model.CategoryList.Select(x => x.CategoryId));
                                var hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, CategoryIdsT = categoryids, TenantId = TenantId, MallBaseId = MallBaseId });
                                if (hpcList.Any())
                                {
                                    RB_Distributor_HPCommission_Extend hpcModel;
                                    if (hpcList.Where(x => x.IsCommon != 1).Any())
                                    {
                                        //有使用非通用返佣
                                        hpcModel = hpcList.Where(x => x.IsCommon != 1).FirstOrDefault();
                                    }
                                    else
                                    {
                                        //查询通用返佣
                                        hpcModel = hpcList.Where(x => x.IsCommon == 1).FirstOrDefault();
                                    }
                                    //查询所有返佣比例
                                    var gList = distributor_HPGradeRatioRepository.GetList(new RB_Distributor_HPGradeRatio_Extend() { CommissionId = hpcModel.Id, TenantId = TenantId, MallBaseId = MallBaseId });

                                    var ratioModel = gList.Where(x => x.GradeId == disModel.HPGradeId).FirstOrDefault();
                                    decimal MPrice = (model.CostPrice ?? 0) / (1 - ((ratioModel.CommissionRatio ?? 0) / 100));
                                    model.MaxShare = MaxSellMoney - MPrice > 0 ? MaxSellMoney - MPrice : 0;
                                    if (hpcModel.DecimalType == 1)
                                    {
                                        model.MaxShare = Math.Ceiling(model.MaxShare);
                                    }
                                    else if (hpcModel.DecimalType == 2)
                                    {
                                        model.MaxShare = Math.Ceiling(model.MaxShare * 100) / 100;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (model.SeparateDistribution == 1)
                            {
                                var dcList = model.DistributionCommissionList.Where(x => x.DistributorGrade == disModel.GradeId).ToList();
                                //if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                //{
                                //    model.MaxShare = dcList.Max(x => (x.OneCommission ?? 0) + (x.TwoCommission ?? 0) + (x.ThreeCommission ?? 0));
                                //}
                                //else
                                //{
                                model.MaxShare = dcList.Max(x => x.OneCommission ?? 0);
                                //}
                                // 这里需注意，可能需要分销 是否提所有返佣控制
                                if (model.SeparateDistributionMoneyType == 1)
                                {
                                    model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                }
                            }
                            else
                            {
                                if (disModel.GradeId == 0)
                                {
                                    //拿分销基础配置
                                    //if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                    //{
                                    //    model.MaxShare = (BasicsModel?.OneCommission ?? 0) + (BasicsModel?.TwoCommission ?? 0) + (BasicsModel?.ThreeCommission ?? 0);
                                    //}
                                    //else
                                    //{
                                    model.MaxShare = BasicsModel?.OneCommission ?? 0;
                                    //}
                                    if ((BasicsModel?.DistributorCommissionType ?? 2) == 1)
                                    {
                                        model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                    }
                                }
                                else if (disModel.GradeId > 0)
                                {
                                    //获取分销商等级
                                    var disgradeModel = distributor_GradeRepository.GetEntity(disModel.GradeId);
                                    if (disgradeModel != null)
                                    {
                                        //if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                        //{
                                        //    model.MaxShare = (disgradeModel?.OneCommission ?? 0) + (disgradeModel?.TwoCommission ?? 0) + (disgradeModel?.ThreeCommission ?? 0);
                                        //}
                                        //else
                                        //{
                                        model.MaxShare = disgradeModel?.OneCommission ?? 0;
                                        //}
                                        if ((disgradeModel?.DistributionCommissionType ?? 2) == 1)
                                        {
                                            model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region 最外层组装参数
            List<RB_Member_Grade_Extend> memeberList = new List<RB_Member_Grade_Extend>();
            if (UserId > 0)
            {
                if (userModel.MemberGrade > 0)
                {
                    memeberList = GetMemberGradeList(new RB_Member_Grade_Extend() { Enabled = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                }
            }

            #region 组装价格
            List<object> priceList = new List<object>();
            if (model.IsCustomSpecification == 1)
            {
                if (model.SpecificationPriceList.Any() && model.SpecificationList.Any())
                {
                    List<RB_Goods_Specification_Extend> SpecificationListToPrice = new List<RB_Goods_Specification_Extend>();
                    List<RB_Goods_SpecificationValue_Extend> SpecificationValueListToPrice = new List<RB_Goods_SpecificationValue_Extend>();
                    bool IsHaveSellingPriceZero = false;
                    if (model.SpecificationPriceList.Where(x => x.SellingPrice > 0).Count() != model.SpecificationPriceList.Count())
                    {
                        //有数量为0的
                        IsHaveSellingPriceZero = true;
                    }
                    foreach (var item in model.SpecificationPriceList.Where(x => x.SellingPrice > 0))
                    {
                        var ssarr = item.SpecificationSort.Split(':');
                        int Sort = Convert.ToInt32(ssarr[0]);
                        string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                        List<object> attr_list = new List<object>();
                        for (int i = 0; i < ssarr.Length; i++)
                        {
                            var smodel = model.SpecificationList[i];
                            if (IsHaveSellingPriceZero && !SpecificationListToPrice.Where(x => x.Id == smodel.Id).Any())
                            {
                                SpecificationListToPrice.Add(smodel);
                            }
                            var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                            if (IsHaveSellingPriceZero && !SpecificationValueListToPrice.Where(x => x.Id == svmodel.Id).Any())
                            {
                                SpecificationValueListToPrice.Add(svmodel);
                            }
                            attr_list.Add(new
                            {
                                attr_group_name = smodel.Name,
                                attr_group_id = smodel.Sort,
                                attr_id = svmodel.Id,
                                attr_name = svmodel.Name
                            });
                        }
                        decimal price_member = item.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                        List<object> member_price_list = new List<object>();
                        if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                        {
                            if (model.MemberPriceList.Any())
                            {
                                var mlist = model.MemberPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).ToList();
                                foreach (var qitem in mlist)
                                {
                                    member_price_list.Add(new
                                    {
                                        member_grade = qitem.MemberGrade,
                                        member_price = qitem.MemberPrice
                                    });
                                }
                                if (UserId > 0 && userModel.MemberGrade > 0)
                                {
                                    var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                    price_member = gmodel.MemberPrice ?? 0;
                                }
                                else
                                {
                                    price_member = mlist.Max(x => x.MemberPrice ?? 0);
                                }
                            }
                        }
                        else
                        {
                            //根据会员等级查找会员价格
                            foreach (var qitem in memeberList)
                            {
                                var mprice = Math.Round((item.SellingPrice ?? 0) * (qitem.Discount ?? 0) / 10, 2, MidpointRounding.AwayFromZero);
                                member_price_list.Add(new
                                {
                                    member_grade = qitem.Grade,
                                    member_price = mprice
                                });
                            }
                            if (UserId > 0 && userModel.MemberGrade > 0 && memeberList.Any())
                            {
                                var gmodel = memeberList.Where(x => x.Grade == userModel.MemberGrade).FirstOrDefault();
                                price_member = Math.Round((model.SellingPrice ?? 0) * (gmodel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                            else if (memeberList.Any())
                            {
                                price_member = Math.Round((model.SellingPrice ?? 0) * (memeberList.Max(x => x.Discount) ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                        }
                        priceList.Add(new
                        {
                            id = item.Id,
                            goods_id = model.Id,
                            sign_id = item.SpecificationSort,
                            stock = item.InventoryNum,
                            price = item.SellingPrice,
                            no = item.GoodsNumbers,
                            weight = item.GoodsWeight,
                            pic_url,
                            is_delete = item.Status,
                            attr_list,
                            price_member,
                            member_price_list
                        });
                    }
                    //当只有一组规格项目时  
                    if (IsHaveSellingPriceZero && SpecificationListToPrice.Any() && model.SpecificationList.Count() == 1)
                    {
                        foreach (var item in SpecificationListToPrice)
                        {
                            item.SpecificationValueList = SpecificationValueListToPrice.Where(x => x.SpecificationId == item.Id).OrderBy(x => x.Sort).ToList();
                        }
                        SpecificationListToPrice = SpecificationListToPrice.Where(x => x.SpecificationValueList.Any()).ToList();
                        //有价格小于等于0的   在前端展示时   需屏蔽掉
                        model.SpecificationList = SpecificationListToPrice;
                    }
                }
            }
            else
            {
                decimal price_member = model.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                List<object> member_price_list = new List<object>();
                if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                {
                    if (model.MemberPriceList.Any())
                    {
                        var mlist = model.MemberPriceList;
                        foreach (var qitem in mlist)
                        {
                            member_price_list.Add(new
                            {
                                member_grade = qitem.MemberGrade,
                                member_price = qitem.MemberPrice
                            });
                        }
                        if (UserId > 0 && userModel.MemberGrade > 0)
                        {
                            var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                            price_member = gmodel.MemberPrice ?? 0;
                        }
                        else
                        {
                            price_member = mlist.Max(x => x.MemberPrice ?? 0);
                        }
                    }
                }
                else
                {
                    //根据会员等级查找会员价格
                    foreach (var qitem in memeberList)
                    {
                        var mprice = Math.Round((model.SellingPrice ?? 0) * (qitem.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                        member_price_list.Add(new
                        {
                            member_grade = qitem.Grade,
                            member_price = mprice
                        });
                    }
                    if (UserId > 0 && userModel.MemberGrade > 0 && memeberList.Any())
                    {
                        var gmodel = memeberList.Where(x => x.Grade == userModel.MemberGrade).FirstOrDefault();
                        price_member = Math.Round((model.SellingPrice ?? 0) * (gmodel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                    }
                    else if (memeberList.Any())
                    {
                        price_member = Math.Round((model.SellingPrice ?? 0) * (memeberList.Max(x => x.Discount) ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                    }
                }


                priceList.Add(new
                {
                    id = 0,
                    goods_id = model.Id,
                    sign_id = "",
                    stock = model.InventoryNum,
                    price = model.SellingPrice ?? 0,
                    no = model.GoodsNumbers,
                    weight = model.GoodsWeight,
                    pic_url = "",
                    is_delete = 0,
                    attr_list = new List<object>(){ new
                    {
                        attr_group_name = "规格",
                        attr_group_id = 0,
                        attr_id = 0,
                        attr_name = model.DefaultSpecificationName
                    } },
                    price_member,
                    member_price_list
                });
            }
            #endregion

            #region 赠送积分
            int Integral = 0;
            if (model.IntegralPresent > 0)
            {
                Integral = model.IntegralPresent ?? 0;
                if (model.IntegralPresentType == 1)
                {
                    Integral = Convert.ToInt32(Math.Floor((model.SellingPrice ?? 0) * (model.IntegralPresent ?? 0) / 100));
                }
            }
            int CommentIntegral = 0;
            if (model.IntegralComment > 0)
            {
                CommentIntegral = model.IntegralComment ?? 0;
                if (model.IntegralCommentType == 1)
                {
                    CommentIntegral = Convert.ToInt32(Math.Floor((model.SellingPrice ?? 0) * (model.IntegralComment ?? 0) / 100));
                }
            }
            #endregion

            #region 赠送vip会员
            string PresentFXGradeMsg = "";
            if ((BasicsModel?.IsEnableFXGrade ?? 2) == 1)
            {
                if (model.PresentFXGrade > 0)
                {
                    var fxmodel = distributor_FXGradeRepository.GetEntity(model.PresentFXGrade);
                    if (fxmodel != null)
                    {
                        PresentFXGradeMsg = "购买后赠送" + fxmodel.GradeName + " ";
                        if (model.PresentFXMonth > 0)
                        {
                            PresentFXGradeMsg += (model.PresentFXMonth ?? 0) + "个月";
                        }
                    }
                }
            }
            #endregion

            #region 会员价格
            decimal price_member_max = 0, price_member_min = 0, price_min = 0, price_max = 0;
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1 && model.MemberPriceList.Any())
            {
                price_member_min = model.MemberPriceList.Min(x => x.MemberPrice ?? 0);
                price_member_max = model.MemberPriceList.Max(x => x.MemberPrice ?? 0);
                if (userModel.MemberGrade > 0)
                {
                    price_min = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Min(x => x.MemberPrice ?? 0);
                    price_max = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Max(x => x.MemberPrice ?? 0);
                }
            }
            else
            {

                if (model.IsCustomSpecification == 1)
                {
                    price_member_min = price_min = model.SpecificationPriceList.Where(x => x.SellingPrice > 0).Min(x => x.SellingPrice ?? 0);
                    price_member_max = price_max = model.SpecificationPriceList.Where(x => x.SellingPrice > 0).Max(x => x.SellingPrice ?? 0);
                }
                else
                {
                    price_member_min = price_member_max = price_min = price_max = model.SellingPrice ?? 0;
                }
                if (memeberList.Any())
                {
                    List<decimal> pricelist = new List<decimal>();
                    foreach (var item in memeberList)
                    {
                        pricelist.Add(price_member_min * (item.Discount ?? 10) / 10);
                        pricelist.Add(price_member_max * (item.Discount ?? 10) / 10);
                    }
                    price_member_min = pricelist.Min(x => x);
                    price_member_max = pricelist.Max(x => x);
                    if (userModel.MemberGrade > 0)
                    {
                        if (price_min > (model.SellingPrice ?? 0)) { price_min = model.SellingPrice ?? 0; }
                        if (price_max < (model.SellingPrice ?? 0)) { price_max = model.SellingPrice ?? 0; }
                        price_min = price_member_min * (memeberList.Where(x => x.Id == userModel.MemberGrade).FirstOrDefault()?.Discount ?? 10) / 10;
                        price_max = price_member_max * (memeberList.Where(x => x.Id == userModel.MemberGrade).FirstOrDefault()?.Discount ?? 10) / 10;
                    }
                }
            }
            price_member_max = Math.Round(price_member_max, 2, MidpointRounding.AwayFromZero);
            price_member_min = Math.Round(price_member_min, 2, MidpointRounding.AwayFromZero);
            //price_min = Math.Round(price_min, 2, MidpointRounding.AwayFromZero);
            //price_max = Math.Round(price_max, 2, MidpointRounding.AwayFromZero);//先使用会员的  
            price_min = price_member_min;
            price_max = price_member_max;
            #endregion

            #region 订单信息

            int payment_people = 0, payment_num = 0, payment_order = 0;//订单用户  商品数量   订单数量
            decimal payment_amount = 0;//订单总金额
            GetGoodsOrderPeopleInfo(out payment_amount, out payment_num, out payment_order, out payment_people, goodsId);
            #endregion

            #region 返回参数

            string shipping = "";
            if (model.FullNumPinkage > 0)
            {
                shipping += "单品满" + model.FullNumPinkage + "件包邮";
            }
            if (model.FullMoneyPinkage > 0)
            {
                if (model.FullNumPinkage > 0)
                {
                    shipping += "，单品满￥" + model.FullMoneyPinkage.Value.ToString("#0.00") + "包邮";
                }
                else
                {
                    shipping += "单品满￥" + model.FullMoneyPinkage.Value.ToString("#0.00") + "包邮";
                }
            }
            string limit = "";
            if (model.AreaList.Any())
            {
                limit = "仅限" + string.Join(",", model.AreaList.Select(x => x.AreaName)) + "购买";
            }
            int IsAllowShare = 1;
            if (model.CategoryList.Where(x => x.IsForeignShare == 2).Any())
            {
                IsAllowShare = 2;
            }

            if ((model.IsCustomSpecification ?? 2) != 1)
            {
                var VauleL = new List<RB_Goods_SpecificationValue_Extend>
                {
                    new RB_Goods_SpecificationValue_Extend()
                    {
                        Sort = 0,
                        Name = model.DefaultSpecificationName,
                        ImagePath = ""
                    }
                };
                model.SpecificationList = new List<RB_Goods_Specification_Extend> {
                    new RB_Goods_Specification_Extend()
                    {
                        Sort = 0,
                        Name = "规格",
                        SpecificationValueList = VauleL
                    }
                };
            }

            return new
            {
                goods = new
                {
                    id = model.Id,
                    mall_id = model.MallBaseId,
                    mch_id = model.TenantId,//暂  商户id
                    //goods_warehouse_id = 0,//
                    status = model.GoodsStatus,
                    isAllowShare = IsAllowShare,//是否可以分享
                    advertising = model.Advertising,//广告词
                    price = model.SellingPrice,
                    sendArea = model.SendArea,
                    use_attr = model.IsCustomSpecification,
                    attr_groups = model.SpecificationList.Select(x => new
                    {
                        attr_group_id = x.Sort,
                        attr_group_name = x.Name,
                        attr_list = x.SpecificationValueList.Select(z => new
                        {
                            attr_id = z.Sort,
                            attr_name = z.Name,
                            pic_url = z.ImagePath
                        })
                    }),
                    goods_stock = model.InventoryNum,
                    virtual_sales = (model.SalesNum ?? 0),
                    confine_count = model.LimitBuyGoodsNum,
                    pieces = model.FullNumPinkage,//满件包邮
                    forehead = model.FullMoneyPinkage,//满额包邮
                    freight_id = model.FreightId,
                    give_integral = model.IntegralPresent,
                    give_integral_type = model.IntegralPresentType,
                    forehead_integral = model.PointsDeduction,//暂  积分抵扣
                    forehead_integral_type = model.PointsDeductionType,//暂  积分抵扣类型
                    accumulative = model.IsMultipleDeduction,//多件抵扣
                    individual_share = userModel?.IsDistributor ?? 2,// 是否分销商
                    attr_setting_type = model.SeparateDistributionType,//分销类型
                    is_level = model.EnjoyMember,//是否销售会员价格
                    is_level_alone = model.SeparateSetMember,//是否单独设置会员价
                    share_type = model.SeparateDistributionMoneyType,//分销佣金类型
                    //sign = "",
                    app_share_pic = model.CustomShareImagePath,
                    app_share_title = model.CustomShareTitles,
                    is_default_services = model.IsDefaultService,
                    sort = model.Sort,
                    created_at = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    updated_at = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    //deleted_at = "",
                    is_delete = model.Status,
                    payment_people,//用户数量
                    payment_num,//商品数量
                    payment_amount,//销售总额
                    payment_order,//订单数量
                    confine_order_count = model.LimitBuyOrderNum,
                    is_area_limit = model.IsAreaBuy,
                    area_limit = new List<object>() { new { list = model.AreaList.Select(x => new {
                        area_id=x.AreaId,
                        area_name=x.AreaName,
                        area_type=x.AreaType
                    }) } },
                    form_id = model.FormsId,
                    sales = (model.SalesNum ?? 0) + payment_num,//已售出数量 + 订单商品数量//
                    name = model.Name,
                    original_price = model.OriginalPrice,
                    cover_pic = model.CoverImage,
                    unit = model.Unit,
                    detail = model.GoodsDetails,
                    video_url = model.VideoAddress,
                    level_show = (userModel?.MemberGrade ?? 0) > 0 ? 1 : 2,//是否显示会员价
                    is_sales = model.GoodsStatus == 1 && model.InventoryNum > 0 ? 1 : 2,//是否可购买
                    attr = priceList,
                    //goods_num = model.InventoryNum,
                    goods_no = model.GoodsNumbers,
                    goods_weight = model.GoodsWeight,
                    services = model.ServiceList.Select(x => new
                    {
                        id = x.Id,
                        name = x.Name
                    }),
                    price_min,
                    price_max,
                    pic_url = model.CarouselImageList.Select(x => new
                    {
                        id = x.Id,
                        pic_url = x.Path,
                        type = x.Type
                    }),
                    share = model.MaxShare,//分销佣金
                    myBuyCommission = MyBuyCommission,//粉象模式  自购返利
                    favorite = model.Favorite,//是否收藏
                    goods_marketing = new
                    {
                        limit,
                        pickup = "",
                        shipping
                    },
                    goods_marketing_award = new
                    {
                        integral = new
                        {
                            title = Integral > 0 ? "购买可得" + Integral + "积分" : ""
                        },
                        commentIntegral = new
                        {
                            title = CommentIntegral > 0 ? "购买并评论可得" + Integral + "积分" : ""
                        },
                        PresentFXGradeMsg
                    },
                    //plugin_extra = new List<object>(),
                    express = model.Express,//快递费用   读取默认收货地址 如果没有为0  如果有 根据商品运费匹配 找出快递费用
                    price_member_max,
                    price_member_min,
                    extra_quick_share = new
                    {
                        share_pic = model.CarouselImageList.Select(x => new
                        {
                            id = x.Id,
                            pic_url = x.Path
                        }),
                        share_text = model.Name,
                        mall_name = model.MallName,
                        format_time = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
                    },
                    is_quick_shop = model.IsQuickBuy,
                    is_sell_well = model.IsSellWell,
                    is_negotiable = model.IsGoodsNegotiable,
                    freeShippingName = model.FreeShippingModel.Name,
                    fullMoneyPinkage = model.FreeShippingModel.FullMoneyPinkage ?? 0,
                    fullNumPinkage = model.FreeShippingModel.FullNumPinkage ?? 0,
                    freeShippingUrl = model.FreeShippingModel.FreeShippingUrl,
                    marketingLogo = model.MarketingLogo,
                    //分类
                    cats = model.CategoryList.Select(x => new
                    {
                        x.CategoryId,
                        x.CategoryName
                    }),
                    video_type = model.VideoType,
                },
                delivery = ""
            };
            #endregion
            #endregion
        }

        /// <summary>
        /// 获取线下服务一级分类列表
        /// </summary>
        /// <returns></returns>
        public List<RB_Product_Category_Extend> GetAppletOfflineCategoryListModule(int TenantId, int MallBaseId)
        {
            var list = product_CategoryRepository.GetList(new RB_Product_Category_Extend()
            {
                TenantId = TenantId,
                MallBaseId = MallBaseId,
                Tier = 1
            });
            return list;
        }

        /// <summary>
        /// 根据分类获取所有商品列表
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="categoryIds"></param>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public object GetAppletOfflineGoodsListModule(int TenantId, int MallBaseId, string categoryIds, int storeId = 0)
        {
            List<object> list = new List<object>();
            string qCategoryIds = "";
            if (!string.IsNullOrEmpty(categoryIds))
            {
                var allCateList = product_CategoryRepository.GetCurrentAndChildCategoryListRepository(categoryIds);
                if (allCateList != null && allCateList.Count > 0)
                {
                    qCategoryIds = string.Join(",", allCateList.Select(qitem => qitem.Id));
                }
            }
            var goodsList = GetAppletGoodsPageListForZY(1, 100000, out long rowsCount, new RB_Goods_Extend()
            {
                TenantId = TenantId,
                MallBaseId = MallBaseId,
                GoodsStatus = 1,
                StoresIds = storeId.ToString(),
                CategoryIds = qCategoryIds
            }, GoodsClassify: 3);
            if (goodsList != null && goodsList.Count > 0)
            {
                foreach (var model in goodsList)
                {
                    model.CoverImage = "";
                    if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                        //封面图
                        model.CoverImage = CarouselIdList[0];
                    }
                    var obj = new
                    {
                        id = model.Id,
                        name=model.Name,
                        cover_pic = model.CoverImage,           
                    };
                    list.Add(obj);
                }
            }
            return list;
        }


        /// <summary>
        /// 获取线下服务商品预定详情
        /// </summary>
        /// <param name="goodsId">商品编号</param>
        /// <param name="UserId">用户编号</param>
        /// <param name="SmallShopsId">微店编号</param>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="storeId">门店编号</param>
        /// <returns></returns>
        public object GetAppletOfflineGoodsInfoModule(int goodsId, int UserId, int SmallShopsId, int TenantId, int MallBaseId, int storeId = 0)
        {
            var model = goodsRepository.GetEntity(goodsId).RefMapperTo<RB_Goods_Extend>();
            if (model == null || model.TenantId != TenantId || model.MallBaseId != MallBaseId)
            {
                return null;
            }
            else
            {
                model.CoverImage = "";
                if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
                {
                    List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                    //封面图
                    model.CoverImage = CarouselIdList[0];
                }
            }
            //小程序名称
            model.MallName = programRepository.GetEntity(model.MallBaseId)?.MallName ?? "";

            RB_Member_User_Extend userModel = new RB_Member_User_Extend();
            if (UserId > 0)
            {
                userModel = GetMemberUserInfo(UserId);
                if (SmallShopsId == 0)
                {
                    SmallShopsId = userModel.SmallShopId;
                }
            }

            #region 基本信息
            //查询分类
            model.CategoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });

            //2020-08-05  根据分类查找商品对应的分类包邮规则 add by :W 

            #region 微店价格
            RB_SmallShops_Info smallModel = new RB_SmallShops_Info();
            List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
            if (SmallShopsId > 0)
            {
                smallModel = smallShops_InfoRepository.GetEntity(SmallShopsId);
                smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = SmallShopsId, GoodsId = goodsId });
                if (((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.UpPrice > 0).Any()))
                {
                    var sspModel = smallPList.Where(x => x.SpecificationKey == "").FirstOrDefault();
                    if (sspModel != null)
                    {
                        //单商品设置的
                        if (sspModel.PriceType == 1)
                        {
                            model.SellingPrice = (model.SellingPrice ?? 0) + Math.Ceiling((model.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                            model.OriginalPrice = (model.OriginalPrice ?? 0) + Math.Ceiling((model.OriginalPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                        }
                        else if (sspModel.PriceType == 2)
                        {
                            model.SellingPrice = (model.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                            model.OriginalPrice = (model.OriginalPrice ?? 0) + (sspModel.UpPrice ?? 0);
                        }
                    }
                    else
                    {
                        if ((smallModel.UpPrice ?? 0) > 0)
                        {
                            if (smallModel.PriceType == 1)
                            {
                                model.SellingPrice = (model.SellingPrice ?? 0) + Math.Ceiling((model.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                model.OriginalPrice = (model.OriginalPrice ?? 0) + Math.Ceiling((model.OriginalPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                            }
                            else if (smallModel.PriceType == 2)
                            {
                                model.SellingPrice = (model.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                model.OriginalPrice = (model.OriginalPrice ?? 0) + (smallModel.UpPrice ?? 0);
                            }
                        }
                    }
                }
            }
            #endregion

            //最大售价
            decimal MaxSellMoney = model.SellingPrice ?? 0;
            model.SpecificationList = new List<RB_Goods_Specification_Extend>();
            model.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
            if (model.IsCustomSpecification == 1)
            {
                model.SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (model.SpecificationList.Any())
                {
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in svlist)
                    {
                        item.ImagePath = item.Image;
                    }
                    foreach (var item in model.SpecificationList)
                    {
                        item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                    }
                }
                model.SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (SmallShopsId > 0)
                {
                    if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.UpPrice > 0).Any())
                    {
                        foreach (var item in model.SpecificationPriceList)
                        {
                            var sspModel = smallPList.Where(x => x.SpecificationKey == item.SpecificationSort).FirstOrDefault();
                            if (sspModel != null)
                            {
                                //单商品设置的
                                if (sspModel.PriceType == 1)
                                {
                                    item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                }
                                else if (sspModel.PriceType == 2)
                                {
                                    item.SellingPrice = (item.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                }
                            }
                            else
                            {
                                if ((smallModel.UpPrice ?? 0) > 0)
                                {
                                    if (smallModel.PriceType == 1)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                    }
                                    else if (smallModel.PriceType == 2)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                    }
                                }
                            }
                        }
                    }
                }
                MaxSellMoney = model.SpecificationPriceList.Max(x => x.SellingPrice ?? 0);
                model.SellingPrice = model.SpecificationPriceList.Min(x => x.SellingPrice ?? 0);
                decimal MaxPrice = MaxSellMoney + Math.Ceiling(MaxSellMoney / 10);
                if (MaxPrice > model.OriginalPrice)
                {
                    model.OriginalPrice = MaxPrice;
                }
            }
            //区域
            model.AreaList = new List<RB_Goods_Area_Extend>();
            if (model.IsAreaBuy == 1)
            {
                model.AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //返佣
            model.DistributionCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
            if (model.SeparateDistribution == 1)
            {
                model.DistributionCommissionList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //会员价格
            model.MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
            {
                model.MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }

            #region 微店处理会员价格
            if (model.MemberPriceList.Any() && SmallShopsId > 0)
            {
                if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.UpPrice > 0).Any())
                {
                    foreach (var item in model.MemberPriceList)
                    {
                        var sspModel = smallPList.Where(x => x.SpecificationKey == item.SpecificationSort).FirstOrDefault();
                        if (sspModel != null)
                        {
                            //单商品设置的
                            if (sspModel.PriceType == 1)
                            {
                                item.MemberPrice = (item.MemberPrice ?? 0) + Math.Ceiling((item.MemberPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                            }
                            else if (sspModel.PriceType == 2)
                            {
                                item.MemberPrice = (item.MemberPrice ?? 0) + (sspModel.UpPrice ?? 0);
                            }
                        }
                        else
                        {
                            if ((smallModel.UpPrice ?? 0) > 0)
                            {
                                if (smallModel.PriceType == 1)
                                {
                                    item.MemberPrice = (item.MemberPrice ?? 0) + Math.Ceiling((item.MemberPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                }
                                else if (smallModel.PriceType == 2)
                                {
                                    item.MemberPrice = (item.MemberPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            //轮播
            model.CarouselImageList = new List<RB_ImageCommonModel>();
            if (!string.IsNullOrWhiteSpace(model.VideoAddress))
            {
                model.CarouselImageList.Add(new RB_ImageCommonModel()
                {
                    Id = 0,
                    Name = "",
                    Type = 1,
                    Path = model.VideoAddress
                });
            }
            if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
            {
                List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                //轮播图
                foreach (var item in CarouselIdList)
                {
                    model.CarouselImageList.Add(new RB_ImageCommonModel()
                    {
                        Id = 0,
                        Name = "",
                        Path = item
                    });
                }
            }

            model.CustomShareImagePath = model.CustomShareImage;

            //服务列表
            model.ServiceList = new List<RB_ImageCommonModel>();
            if (model.IsDefaultService == 2)
            {
                if (!string.IsNullOrEmpty(model.GoodsService) && model.GoodsService != "[]")
                {
                    List<int> ServiceIds = JsonConvert.DeserializeObject<List<int>>(model.GoodsService);
                    var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { ServiceIds = string.Join(",", ServiceIds), TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in slist)
                    {
                        model.ServiceList.Add(new RB_ImageCommonModel()
                        {
                            Id = item.Id,
                            Name = item.Name
                        });
                    }
                }
            }
            else if (model.IsDefaultService == 1)
            {
                var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { IsDefault = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                foreach (var item in slist)
                {
                    model.ServiceList.Add(new RB_ImageCommonModel()
                    {
                        Id = item.Id,
                        Name = item.Name
                    });
                }
            }
            //表单
            if (model.FormsId > 0)
            {
                model.FormsName = "未建表";
            }
            else
            {
                model.FormsName = "默认表单";
            }
            #endregion

            #region 是否收藏
            model.Favorite = false;
            if (UserId > 0)
            {
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                    new WhereHelper(nameof(RB_Member_Collection_Extend.UserId),UserId),
                    new WhereHelper(nameof(RB_Member_Collection_Extend.GoodsId),goodsId) ,
                    new WhereHelper(nameof(RB_Member_Collection_Extend.TenantId),TenantId),
                    new WhereHelper(nameof(RB_Member_Collection_Extend.MallBaseId),MallBaseId),
                };
                if (member_CollectionRepository.Exists(wheres))
                {
                    model.Favorite = true;
                }
            }
            #endregion

            #region 快递费用
            //运费
            Model.Entity.BaseSetUp.RB_Logistics_Rules rulesModel = new Model.Entity.BaseSetUp.RB_Logistics_Rules();
            if (model.FreightId > 0)
            {
                rulesModel = logistics_RulesRepository.GetEntity(model.FreightId);
                model.FreightName = rulesModel?.RulesName ?? "";
            }
            else
            {
                model.FreightName = "默认运费";
            }
            model.Express = 0;
            if (UserId > 0 && model.FreightId >= 0)
            {
                int FreightId = model.FreightId ?? 0;
                if (model.FreightId == 0)
                {
                    //查询默认
                    FreightId = logistics_RulesRepository.GetLogisticsRulesList(new Model.Extend.BaseSetUp.RB_Logistics_Rules_Extend() { IsDefault = 1, TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault()?.ID ?? 0;
                }
                if (FreightId > 0)
                {
                    var samodel = member_ShippingAddressRepository.GetList(new RB_Member_ShippingAddress_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, IsDefault = 1 }).FirstOrDefault();
                    List<Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend> priceList1 = logistics_RulesPriceRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesPrice_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, RulesId = FreightId });
                    if (priceList1.Any() && samodel != null)
                    {
                        string priceIds = string.Join(",", priceList1.Select(x => x.ID));
                        var regionList = logistics_RulesRegionRepository.GetListRepository(new Model.Extend.BaseSetUp.RB_Logistics_RulesRegion_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, PriceIds = priceIds });
                        List<int> disList = new List<int>();
                        disList.Add(samodel.Province ?? 0);
                        disList.Add(samodel.City ?? 0);
                        disList.Add(samodel.District ?? 0);
                        var regionModel = regionList.Where(x => disList.Contains(x.RegionId)).FirstOrDefault();
                        if (regionModel != null)
                        {
                            var pmodel = priceList1.Where(x => x.ID == regionModel.RulesPriceId).FirstOrDefault();
                            if (pmodel != null && rulesModel != null)
                            {
                                if (rulesModel.ChargeMode == Common.Enum.MallBase.ChargeModeEnum.Num)
                                {
                                    model.Express = pmodel.FirstPrice;
                                }
                                else
                                {
                                    //重量计费
                                    int TotalW = model.GoodsWeight ?? 0;
                                    if (TotalW <= pmodel.First)
                                    {
                                        model.Express = pmodel.FirstPrice;
                                    }
                                    else
                                    {
                                        if (pmodel.Second > 0)
                                        {
                                            if ((TotalW - pmodel.First) % pmodel.Second == 0)
                                            {
                                                model.Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second) * pmodel.SecondPrice;
                                            }
                                            else
                                            {
                                                model.Express = pmodel.FirstPrice + ((TotalW - pmodel.First) / pmodel.Second + 1) * pmodel.SecondPrice;
                                            }
                                        }
                                        else
                                        {
                                            model.Express = pmodel.FirstPrice;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region 最高返佣
            model.MaxShare = 0;
            decimal MyBuyCommission = 0;//自购返利
            var BasicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (UserId > 0)
            {
                //获取分销商信息
                var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                if (disModel != null)
                {
                    if ((BasicsModel?.IsEnableFXGrade ?? 2) == 1)
                    {
                        if ((model.PresentFXGrade ?? 0) == 0)
                        {
                            var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = TenantId, MallBaseId = MallBaseId });
                            if (FXList.Any() && FXList.Where(x => x.IsGuest == 1).Any())
                            {
                                var FXModel = FXList.Where(x => x.Id == disModel.FXGradeId).FirstOrDefault();
                                var PModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
                                if (FXModel != null && PModel != null)
                                {
                                    decimal CRate = 0;
                                    if (FXModel.Id == PModel.Id)
                                    {
                                        CRate = FXModel.SiblingRatio ?? 0;
                                    }
                                    else
                                    {
                                        CRate = (FXModel.CommissionRatio ?? 0) - (PModel.CommissionRatio ?? 0);
                                    }

                                    if (model.IsCustomSpecification == 1)
                                    {
                                        var dcModel = model.SpecificationPriceList.OrderByDescending(x => x.Commission).FirstOrDefault();
                                        if (dcModel.Commission > 0)
                                        {
                                            if (FXModel.DecimalType == 1)
                                            {
                                                model.MaxShare = Math.Ceiling(dcModel.Commission * CRate / 100);
                                                MyBuyCommission = Math.Ceiling(dcModel.Commission * (FXModel.CommissionRatio ?? 0) / 100);
                                            }
                                            else
                                            {
                                                model.MaxShare = Math.Ceiling(dcModel.Commission * CRate) / 100;
                                                MyBuyCommission = Math.Ceiling(dcModel.Commission * (FXModel.CommissionRatio ?? 0)) / 100;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (model.Commission > 0)
                                        {
                                            if (FXModel.DecimalType == 1)
                                            {
                                                model.MaxShare = Math.Ceiling(model.Commission * CRate / 100);
                                                MyBuyCommission = Math.Ceiling(model.Commission * (FXModel.CommissionRatio ?? 0) / 100);
                                            }
                                            else
                                            {
                                                model.MaxShare = Math.Ceiling(model.Commission * CRate) / 100;
                                                MyBuyCommission = Math.Ceiling(model.Commission * (FXModel.CommissionRatio ?? 0)) / 100;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //是否展示分享vip佣金
                            var fxcommissionList = distributor_FXCommissionRepository.GetFXCommissionList(new RB_Distributor_FXCommission_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, FXGradeId = disModel.FXGradeId ?? 0 });
                            if (fxcommissionList.Any())
                            {
                                model.MaxShare = fxcommissionList.Max(x => x.CommissionPrice ?? 0);
                            }
                        }
                    }
                    else
                    {
                        //判断是否开启和平返佣
                        List<WhereHelper> wheres = new List<WhereHelper>()
                        {
                            new WhereHelper(nameof(RB_Distributor_HPCommission.Status),0),
                            new WhereHelper(nameof(RB_Distributor_HPCommission.Enabled),1),
                            new WhereHelper(nameof(RB_Distributor_HPCommission.TenantId),TenantId),
                            new WhereHelper(nameof(RB_Distributor_HPCommission.MallBaseId),MallBaseId)
                        };
                        if (distributor_HPCommissionRepository.Exists(wheres))
                        {
                            //获取和平分销返佣
                            if (disModel.HPGradeId > 0 && model.CostPrice > 0)
                            {
                                string categoryids = string.Join(",", model.CategoryList.Select(x => x.CategoryId));
                                var hpcList = distributor_HPCommissionRepository.GetList(new RB_Distributor_HPCommission_Extend() { Enabled = 1, CategoryIdsT = categoryids, TenantId = TenantId, MallBaseId = MallBaseId });
                                if (hpcList.Any())
                                {
                                    RB_Distributor_HPCommission_Extend hpcModel;
                                    if (hpcList.Where(x => x.IsCommon != 1).Any())
                                    {
                                        //有使用非通用返佣
                                        hpcModel = hpcList.Where(x => x.IsCommon != 1).FirstOrDefault();
                                    }
                                    else
                                    {
                                        //查询通用返佣
                                        hpcModel = hpcList.Where(x => x.IsCommon == 1).FirstOrDefault();
                                    }
                                    //查询所有返佣比例
                                    var gList = distributor_HPGradeRatioRepository.GetList(new RB_Distributor_HPGradeRatio_Extend() { CommissionId = hpcModel.Id, TenantId = TenantId, MallBaseId = MallBaseId });

                                    var ratioModel = gList.Where(x => x.GradeId == disModel.HPGradeId).FirstOrDefault();
                                    decimal MPrice = (model.CostPrice ?? 0) / (1 - ((ratioModel.CommissionRatio ?? 0) / 100));
                                    model.MaxShare = MaxSellMoney - MPrice > 0 ? MaxSellMoney - MPrice : 0;
                                    if (hpcModel.DecimalType == 1)
                                    {
                                        model.MaxShare = Math.Ceiling(model.MaxShare);
                                    }
                                    else if (hpcModel.DecimalType == 2)
                                    {
                                        model.MaxShare = Math.Ceiling(model.MaxShare * 100) / 100;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (model.SeparateDistribution == 1)
                            {
                                var dcList = model.DistributionCommissionList.Where(x => x.DistributorGrade == disModel.GradeId).ToList();
                                model.MaxShare = dcList.Max(x => x.OneCommission ?? 0);
                                // 这里需注意，可能需要分销 是否提所有返佣控制
                                if (model.SeparateDistributionMoneyType == 1)
                                {
                                    model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                }
                            }
                            else
                            {
                                if (disModel.GradeId == 0)
                                {
                                    model.MaxShare = BasicsModel?.OneCommission ?? 0;
                                    if ((BasicsModel?.DistributorCommissionType ?? 2) == 1)
                                    {
                                        model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                    }
                                }
                                else if (disModel.GradeId > 0)
                                {
                                    //获取分销商等级
                                    var disgradeModel = distributor_GradeRepository.GetEntity(disModel.GradeId);
                                    if (disgradeModel != null)
                                    {
                                        model.MaxShare = disgradeModel?.OneCommission ?? 0;
                                        if ((disgradeModel?.DistributionCommissionType ?? 2) == 1)
                                        {
                                            model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region 最外层组装参数
            List<RB_Member_Grade_Extend> memeberList = new List<RB_Member_Grade_Extend>();
            if (UserId > 0)
            {
                if (userModel.MemberGrade > 0)
                {
                    memeberList = GetMemberGradeList(new RB_Member_Grade_Extend() { Enabled = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                }
            }

            #region 组装价格
            List<object> priceList = new List<object>();
            if (model.IsCustomSpecification == 1)
            {
                if (model.SpecificationPriceList.Any() && model.SpecificationList.Any())
                {
                    List<RB_Goods_Specification_Extend> SpecificationListToPrice = new List<RB_Goods_Specification_Extend>();
                    List<RB_Goods_SpecificationValue_Extend> SpecificationValueListToPrice = new List<RB_Goods_SpecificationValue_Extend>();
                    bool IsHaveSellingPriceZero = false;
                    if (model.SpecificationPriceList.Where(x => x.SellingPrice > 0).Count() != model.SpecificationPriceList.Count())
                    {
                        //有数量为0的
                        IsHaveSellingPriceZero = true;
                    }
                    foreach (var item in model.SpecificationPriceList.Where(x => x.SellingPrice > 0))
                    {
                        var ssarr = item.SpecificationSort.Split(':');
                        int Sort = Convert.ToInt32(ssarr[0]);
                        string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                        List<object> attr_list = new List<object>();
                        for (int i = 0; i < ssarr.Length; i++)
                        {
                            var smodel = model.SpecificationList[i];
                            if (IsHaveSellingPriceZero && !SpecificationListToPrice.Where(x => x.Id == smodel.Id).Any())
                            {
                                SpecificationListToPrice.Add(smodel);
                            }
                            var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                            if (IsHaveSellingPriceZero && !SpecificationValueListToPrice.Where(x => x.Id == svmodel.Id).Any())
                            {
                                SpecificationValueListToPrice.Add(svmodel);
                            }
                            attr_list.Add(new
                            {
                                attr_group_name = smodel.Name,
                                attr_group_id = smodel.Sort,
                                attr_id = svmodel.Id,
                                attr_name = svmodel.Name
                            });
                        }
                        decimal price_member = item.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                        List<object> member_price_list = new List<object>();
                        if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                        {
                            if (model.MemberPriceList.Any())
                            {
                                var mlist = model.MemberPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).ToList();
                                foreach (var qitem in mlist)
                                {
                                    member_price_list.Add(new
                                    {
                                        member_grade = qitem.MemberGrade,
                                        member_price = qitem.MemberPrice
                                    });
                                }
                                if (UserId > 0 && userModel.MemberGrade > 0)
                                {
                                    var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                                    price_member = gmodel.MemberPrice ?? 0;
                                }
                                else
                                {
                                    price_member = mlist.Max(x => x.MemberPrice ?? 0);
                                }
                            }
                        }
                        else
                        {
                            //根据会员等级查找会员价格
                            foreach (var qitem in memeberList)
                            {
                                var mprice = Math.Round((item.SellingPrice ?? 0) * (qitem.Discount ?? 0) / 10, 2, MidpointRounding.AwayFromZero);
                                member_price_list.Add(new
                                {
                                    member_grade = qitem.Grade,
                                    member_price = mprice
                                });
                            }
                            if (UserId > 0 && userModel.MemberGrade > 0 && memeberList.Any())
                            {
                                var gmodel = memeberList.Where(x => x.Grade == userModel.MemberGrade).FirstOrDefault();
                                price_member = Math.Round((model.SellingPrice ?? 0) * (gmodel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                            else if (memeberList.Any())
                            {
                                price_member = Math.Round((model.SellingPrice ?? 0) * (memeberList.Max(x => x.Discount) ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                            }
                        }
                        priceList.Add(new
                        {
                            id = item.Id,
                            goods_id = model.Id,
                            sign_id = item.SpecificationSort,
                            stock = item.InventoryNum,
                            price = item.SellingPrice,
                            no = item.GoodsNumbers,
                            weight = item.GoodsWeight,
                            pic_url,
                            is_delete = item.Status,
                            attr_list,
                            price_member,
                            member_price_list
                        });
                    }
                    //当只有一组规格项目时  
                    if (IsHaveSellingPriceZero && SpecificationListToPrice.Any() && model.SpecificationList.Count() == 1)
                    {
                        foreach (var item in SpecificationListToPrice)
                        {
                            item.SpecificationValueList = SpecificationValueListToPrice.Where(x => x.SpecificationId == item.Id).OrderBy(x => x.Sort).ToList();
                        }
                        SpecificationListToPrice = SpecificationListToPrice.Where(x => x.SpecificationValueList.Any()).ToList();
                        //有价格小于等于0的   在前端展示时   需屏蔽掉
                        model.SpecificationList = SpecificationListToPrice;
                    }
                }
            }
            else
            {
                decimal price_member = model.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                List<object> member_price_list = new List<object>();
                if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
                {
                    if (model.MemberPriceList.Any())
                    {
                        var mlist = model.MemberPriceList;
                        foreach (var qitem in mlist)
                        {
                            member_price_list.Add(new
                            {
                                member_grade = qitem.MemberGrade,
                                member_price = qitem.MemberPrice
                            });
                        }
                        if (UserId > 0 && userModel.MemberGrade > 0)
                        {
                            var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                            price_member = gmodel.MemberPrice ?? 0;
                        }
                        else
                        {
                            price_member = mlist.Max(x => x.MemberPrice ?? 0);
                        }
                    }
                }
                else
                {
                    //根据会员等级查找会员价格
                    foreach (var qitem in memeberList)
                    {
                        var mprice = Math.Round((model.SellingPrice ?? 0) * (qitem.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                        member_price_list.Add(new
                        {
                            member_grade = qitem.Grade,
                            member_price = mprice
                        });
                    }
                    if (UserId > 0 && userModel.MemberGrade > 0 && memeberList.Any())
                    {
                        var gmodel = memeberList.Where(x => x.Grade == userModel.MemberGrade).FirstOrDefault();
                        price_member = Math.Round((model.SellingPrice ?? 0) * (gmodel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                    }
                    else if (memeberList.Any())
                    {
                        price_member = Math.Round((model.SellingPrice ?? 0) * (memeberList.Max(x => x.Discount) ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                    }
                }


                priceList.Add(new
                {
                    id = 0,
                    goods_id = model.Id,
                    sign_id = "",
                    stock = model.InventoryNum,
                    price = model.SellingPrice ?? 0,
                    no = model.GoodsNumbers,
                    weight = model.GoodsWeight,
                    pic_url = "",
                    is_delete = 0,
                    attr_list = new List<object>(){ new
                    {
                        attr_group_name = "规格",
                        attr_group_id = 0,
                        attr_id = 0,
                        attr_name = model.DefaultSpecificationName
                    } },
                    price_member,
                    isChooseServicePerson = model.IsChooseServicePerson,
                    depositMoney = model.DepositMoney,
                    member_price_list
                });
            }
            #endregion

            #region 赠送积分
            int Integral = 0;
            if (model.IntegralPresent > 0)
            {
                Integral = model.IntegralPresent ?? 0;
                if (model.IntegralPresentType == 1)
                {
                    Integral = Convert.ToInt32(Math.Floor((model.SellingPrice ?? 0) * (model.IntegralPresent ?? 0) / 100));
                }
            }
            int CommentIntegral = 0;
            if (model.IntegralComment > 0)
            {
                CommentIntegral = model.IntegralComment ?? 0;
                if (model.IntegralCommentType == 1)
                {
                    CommentIntegral = Convert.ToInt32(Math.Floor((model.SellingPrice ?? 0) * (model.IntegralComment ?? 0) / 100));
                }
            }
            #endregion

            #region 赠送vip会员
            string PresentFXGradeMsg = "";
            if ((BasicsModel?.IsEnableFXGrade ?? 2) == 1)
            {
                if (model.PresentFXGrade > 0)
                {
                    var fxmodel = distributor_FXGradeRepository.GetEntity(model.PresentFXGrade);
                    if (fxmodel != null)
                    {
                        PresentFXGradeMsg = "购买后赠送" + fxmodel.GradeName + " ";
                        if (model.PresentFXMonth > 0)
                        {
                            PresentFXGradeMsg += (model.PresentFXMonth ?? 0) + "个月";
                        }
                    }
                }
            }
            #endregion

            #region 会员价格
            decimal price_member_max = 0, price_member_min = 0, price_min = 0, price_max = 0;
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1 && model.MemberPriceList.Any())
            {
                price_member_min = model.MemberPriceList.Min(x => x.MemberPrice ?? 0);
                price_member_max = model.MemberPriceList.Max(x => x.MemberPrice ?? 0);
                if (userModel.MemberGrade > 0)
                {
                    price_min = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Min(x => x.MemberPrice ?? 0);
                    price_max = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Max(x => x.MemberPrice ?? 0);
                }
            }
            else
            {

                if (model.IsCustomSpecification == 1)
                {
                    price_member_min = price_min = model.SpecificationPriceList.Where(x => x.SellingPrice > 0).Min(x => x.SellingPrice ?? 0);
                    price_member_max = price_max = model.SpecificationPriceList.Where(x => x.SellingPrice > 0).Max(x => x.SellingPrice ?? 0);
                }
                else
                {
                    price_member_min = price_member_max = price_min = price_max = model.SellingPrice ?? 0;
                }
                if (memeberList.Any())
                {
                    List<decimal> pricelist = new List<decimal>();
                    foreach (var item in memeberList)
                    {
                        pricelist.Add(price_member_min * (item.Discount ?? 10) / 10);
                        pricelist.Add(price_member_max * (item.Discount ?? 10) / 10);
                    }
                    price_member_min = pricelist.Min(x => x);
                    price_member_max = pricelist.Max(x => x);
                    if (userModel.MemberGrade > 0)
                    {
                        if (price_min > (model.SellingPrice ?? 0)) { price_min = model.SellingPrice ?? 0; }
                        if (price_max < (model.SellingPrice ?? 0)) { price_max = model.SellingPrice ?? 0; }
                        price_min = price_member_min * (memeberList.Where(x => x.Id == userModel.MemberGrade).FirstOrDefault()?.Discount ?? 10) / 10;
                        price_max = price_member_max * (memeberList.Where(x => x.Id == userModel.MemberGrade).FirstOrDefault()?.Discount ?? 10) / 10;
                    }
                }
            }
            price_member_max = Math.Round(price_member_max, 2, MidpointRounding.AwayFromZero);
            price_member_min = Math.Round(price_member_min, 2, MidpointRounding.AwayFromZero);

            price_min = price_member_min;
            price_max = price_member_max;
            #endregion

            #region 订单信息

            int payment_people = 0, payment_num = 0, payment_order = 0;//订单用户  商品数量   订单数量
            decimal payment_amount = 0;//订单总金额
            GetGoodsOrderPeopleInfo(out payment_amount, out payment_num, out payment_order, out payment_people, goodsId);
            #endregion

            #region 返回参数

            string shipping = "";
            if (model.FullNumPinkage > 0)
            {
                shipping += "单品满" + model.FullNumPinkage + "件包邮";
            }
            if (model.FullMoneyPinkage > 0)
            {
                if (model.FullNumPinkage > 0)
                {
                    shipping += "，单品满￥" + model.FullMoneyPinkage.Value.ToString("#0.00") + "包邮";
                }
                else
                {
                    shipping += "单品满￥" + model.FullMoneyPinkage.Value.ToString("#0.00") + "包邮";
                }
            }
            string limit = "";
            if (model.AreaList.Any())
            {
                limit = "仅限" + string.Join(",", model.AreaList.Select(x => x.AreaName)) + "购买";
            }
            int IsAllowShare = 1;
            if (model.CategoryList.Where(x => x.IsForeignShare == 2).Any())
            {
                IsAllowShare = 2;
            }
            if ((model.IsCustomSpecification ?? 2) != 1)
            {
                var VauleL = new List<RB_Goods_SpecificationValue_Extend>
                {
                    new RB_Goods_SpecificationValue_Extend()
                    {
                        Sort = 0,
                        Name = model.DefaultSpecificationName,
                        ImagePath = ""
                    }
                };
                model.SpecificationList = new List<RB_Goods_Specification_Extend>
                {
                    new RB_Goods_Specification_Extend()
                    {
                        Sort = 0,
                        Name = "规格",
                        SpecificationValueList = VauleL
                    }
                };
            }
            #region 门店相关
            string categoryIds = "0";
            if (model.CategoryList != null && model.CategoryList.Count > 0)
            {
                categoryIds = string.Join(",", model.CategoryList.Select(qitem => qitem.CategoryId));
            }
            var servicePersionList = reserve_ServicePersonalRepository.GetServicePersonalListExtRepository(storeId,model.Id, categoryIds)?.ToList() ?? new List<Model.Extend.Reserve.RB_Reserve_ServicePersonal_Extend>();

            var storeModel = storesRepository.GetEntity(storeId);
            List<StoreReserveDate> storeDateList = new List<StoreReserveDate>();
            DateTime currentDay = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            for (int i = 0; i <= 7; i++)
            {
                var storeDateModel = new StoreReserveDate()
                {
                    DayDate = Convert.ToDateTime(DateTime.Now.AddDays(i).ToString("yyyy-MM-dd")),
                    DayDateStr = DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"),
                    WeekDayStr = (i == 0 ? "今天" : "周" + Common.Plugin.CommonHelper.GetWeekDay(DateTime.Now.AddDays(i))),
                    TimeList = new List<string>()
                };
                for (var j = 0; j < 48; j++)
                {
                    string tempTimeStr = "";
                    if (j % 2 == 0)
                    {
                        tempTimeStr=currentDay.AddHours((j / 2)).ToString("HH:mm");
                    }
                    else
                    {
                        tempTimeStr = currentDay.AddHours((Convert.ToDouble(j) / 2.0)).ToString("HH:mm");
                    }
                    storeDateModel.TimeList.Add(tempTimeStr);
                }
                storeDateList.Add(storeDateModel);
            }

            if (storeModel != null && storeModel.Id > 0)
            {
                //全天营业
                if (storeModel.IsAllDay == 1)
                {
                    List<string> tempTimeList = new List<string>();
                    var firstModel = storeDateList[0];
                    foreach (var timeItem in firstModel.TimeList)
                    {
                        if (DateTime.Now < Convert.ToDateTime(firstModel.DayDate.ToString("yyyy-MM-dd") + " " + timeItem))
                        {
                            tempTimeList.Add(timeItem);
                        }
                    }
                    firstModel.TimeList = tempTimeList;
                }
                //有具体时间
                else
                {
                    for (var i = 0; i < storeDateList.Count; i++)
                    {
                        List<string> tempTimeList = new List<string>();
                        var firstModel = storeDateList[i];
                        DateTime startTime = Convert.ToDateTime(firstModel.DayDate.ToString("yyyy-MM-dd") + " " + storeModel.StartTime);
                        DateTime endTime = Convert.ToDateTime(firstModel.DayDate.ToString("yyyy-MM-dd") + " " + storeModel.EndTime);
                        if (i == 0)
                        {
                            foreach (var timeItem in firstModel.TimeList)
                            {
                                DateTime currentTime = Convert.ToDateTime(firstModel.DayDate.ToString("yyyy-MM-dd") + " " + timeItem);
                                if (DateTime.Now < currentTime && currentTime > startTime && currentTime < endTime)
                                {
                                    tempTimeList.Add(timeItem);
                                }
                            }
                            firstModel.TimeList = tempTimeList;
                        }
                        else
                        {
                            foreach (var timeItem in firstModel.TimeList)
                            {
                                DateTime currentTime = Convert.ToDateTime(firstModel.DayDate.ToString("yyyy-MM-dd") + " " + timeItem);
                                if (currentTime > startTime && currentTime < endTime)
                                {
                                    tempTimeList.Add(timeItem);
                                }
                            }
                            firstModel.TimeList = tempTimeList;
                        }
                    }
                }
            }

            #endregion
            return new
            {
                goods = new
                {
                    id = model.Id,
                    mall_id = model.MallBaseId,
                    mch_id = model.TenantId,//暂  商户id
                    status = model.GoodsStatus,
                    isAllowShare = IsAllowShare,//是否可以分享
                    advertising = model.Advertising,//广告词
                    price = model.SellingPrice,
                    sendArea = model.SendArea,
                    use_attr = model.IsCustomSpecification,
                    attr_groups = model.SpecificationList.Select(x => new
                    {
                        attr_group_id = x.Sort,
                        attr_group_name = x.Name,
                        attr_list = x.SpecificationValueList.Select(z => new
                        {
                            attr_id = z.Sort,
                            attr_name = z.Name,
                            pic_url = z.ImagePath
                        })
                    }),
                    goods_stock = model.InventoryNum,
                    virtual_sales = (model.SalesNum ?? 0),
                    confine_count = model.LimitBuyGoodsNum,
                    pieces = model.FullNumPinkage,//满件包邮
                    forehead = model.FullMoneyPinkage,//满额包邮
                    freight_id = model.FreightId,
                    give_integral = model.IntegralPresent,
                    give_integral_type = model.IntegralPresentType,
                    forehead_integral = model.PointsDeduction,//暂  积分抵扣
                    forehead_integral_type = model.PointsDeductionType,//暂  积分抵扣类型
                    accumulative = model.IsMultipleDeduction,//多件抵扣
                    individual_share = userModel?.IsDistributor ?? 2,// 是否分销商
                    attr_setting_type = model.SeparateDistributionType,//分销类型
                    is_level = model.EnjoyMember,//是否销售会员价格
                    is_level_alone = model.SeparateSetMember,//是否单独设置会员价
                    share_type = model.SeparateDistributionMoneyType,//分销佣金类型
                    app_share_pic = model.CustomShareImagePath,
                    app_share_title = model.CustomShareTitles,
                    is_default_services = model.IsDefaultService,
                    sort = model.Sort,
                    created_at = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    updated_at = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    is_delete = model.Status,
                    payment_people,//用户数量
                    payment_num,//商品数量
                    payment_amount,//销售总额
                    payment_order,//订单数量
                    confine_order_count = model.LimitBuyOrderNum,
                    is_area_limit = model.IsAreaBuy,
                    form_id = model.FormsId,
                    sales = (model.SalesNum ?? 0) + payment_num,//已售出数量 + 订单商品数量//
                    name = model.Name,
                    original_price = model.OriginalPrice,
                    cover_pic = model.CoverImage,
                    unit = model.Unit,
                    detail = model.GoodsDetails,
                    video_url = model.VideoAddress,
                    level_show = (userModel?.MemberGrade ?? 0) > 0 ? 1 : 2,//是否显示会员价
                    is_sales = model.GoodsStatus == 1 && model.InventoryNum > 0 ? 1 : 2,//是否可购买
                    attr = priceList,
                    goods_no = model.GoodsNumbers,
                    goods_weight = model.GoodsWeight,
                    services = model.ServiceList.Select(x => new
                    {
                        id = x.Id,
                        name = x.Name
                    }),
                    price_min,
                    price_max,
                    pic_url = model.CarouselImageList.Select(x => new
                    {
                        id = x.Id,
                        pic_url = x.Path,
                        type = x.Type
                    }),
                    share = model.MaxShare,//分销佣金
                    myBuyCommission = MyBuyCommission,//粉象模式  自购返利
                    favorite = model.Favorite,//是否收藏
                    goods_marketing = new
                    {
                        limit,
                        pickup = "",
                        shipping
                    },
                    goods_marketing_award = new
                    {
                        integral = new
                        {
                            title = Integral > 0 ? "购买可得" + Integral + "积分" : ""
                        },
                        commentIntegral = new
                        {
                            title = CommentIntegral > 0 ? "购买并评论可得" + Integral + "积分" : ""
                        },
                        PresentFXGradeMsg
                    },
                    express = model.Express,//快递费用   读取默认收货地址 如果没有为0  如果有 根据商品运费匹配 找出快递费用
                    price_member_max,
                    price_member_min,
                    extra_quick_share = new
                    {
                        share_pic = model.CarouselImageList.Select(x => new
                        {
                            id = x.Id,
                            pic_url = x.Path
                        }),
                        share_text = model.Name,
                        mall_name = model.MallName,
                        format_time = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
                    },
                    is_quick_shop = model.IsQuickBuy,
                    is_sell_well = model.IsSellWell,
                    is_negotiable = model.IsGoodsNegotiable,
                    marketingLogo = model.MarketingLogo,
                    //分类
                    cats = model.CategoryList.Select(x => new
                    {
                        x.CategoryId,
                        x.CategoryName
                    }),
                    video_type = model.VideoType,
                    isChooseServicePerson = model.IsChooseServicePerson,
                    depositMoney = model.DepositMoney,
                    persionList = servicePersionList?.Where(qitem => qitem.ServiceStatus == 1).Select(qitem => new
                    {
                        qitem.ServiceLogo,
                        qitem.Score,
                        qitem.Name,
                        qitem.Major,
                        Gender = qitem.Gender.ToInt(),
                        ReserveCount=qitem.OrderNum,
                        ServiceId=qitem.ID
                    }),
                    storeDateList= storeDateList.Select(qitem => new {qitem.DayDateStr,qitem.WeekDayStr,qitem.TimeList})
                },
                delivery = ""
            };
            #endregion
            #endregion
        }

        /// <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> GetAppletGoodsVideoPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string goodsIds = string.Join(",", list.Select(x => x.Id));
                var categoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciVList = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                List<RB_Goods_Order_Extend> orderlist = goods_OrderRepository.GetGoodsOrderNum(goodsIds: goodsIds);
                foreach (var item in list)
                {
                    item.CoverImage = "";
                    item.CarouselImageList = new List<RB_ImageCommonModel>();
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                        item.CarouselImageList = CarouselIdList.Select(x => new RB_ImageCommonModel()
                        {
                            Id = 0,
                            Name = "",
                            Path = x
                        }).ToList();
                    }

                    #region 基本信息
                    //查询分类
                    item.CategoryList = categoryList.Where(x => x.GoodsId == item.Id).ToList();

                    item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                    item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                    if (item.IsCustomSpecification == 1)
                    {
                        item.SpecificationList = speciList.Where(x => x.GoodsId == item.Id).ToList();
                        if (item.SpecificationList.Any())
                        {
                            var svlist = speciVList.Where(x => x.GoodsId == item.Id).ToList();
                            foreach (var qitem in svlist)
                            {
                                qitem.ImagePath = qitem.Image;
                            }
                            foreach (var qitem in item.SpecificationList)
                            {
                                qitem.SpecificationValueList = svlist.Where(x => x.SpecificationId == qitem.Id).ToList();
                            }
                        }
                        item.SpecificationPriceList = speciPList.Where(x => x.GoodsId == item.Id).ToList();
                    }
                    item.CustomShareImagePath = item.CustomShareImage;
                    #endregion

                    item.SalesNum += (orderlist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取商品详情 订单相关统计
        /// </summary>
        /// <param name="payment_amount"></param>
        /// <param name="payment_num"></param>
        /// <param name="payment_order"></param>
        /// <param name="payment_people"></param>
        /// <param name="goodsId"></param>
        public void GetGoodsOrderPeopleInfo(out decimal payment_amount, out int payment_num, out int payment_order, out int payment_people, int goodsId)
        {
            goods_OrderRepository.GetGoodsOrderPeopleInfo(out payment_amount, out payment_num, out payment_order, out payment_people, goodsId);
        }
        #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> GetAppletCoursePageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetAppletGoodsPageList(pageIndex, pageSize, out count, demodel, 2);
            if (list.Any())
            {
                //会员价格
                var MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
                if (list.Where(x => x.EnjoyMember == 1 && x.SeparateSetMember == 1).Any())
                {
                    string goodsIds = string.Join(",", list.Where(x => x.EnjoyMember == 1 && x.SeparateSetMember == 1).Select(x => x.Id));
                    MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                string goodsIds2 = string.Join(",", list.Select(x => x.Id));
                List<RB_Goods_Order_Extend> orderlist = goods_OrderRepository.GetGoodsOrderNum(goodsIds: goodsIds2);
                #region 微店价格
                RB_SmallShops_Info smallModel = new RB_SmallShops_Info();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                if (demodel.SmallShopsId > 0)
                {
                    smallModel = smallShops_InfoRepository.GetEntity(demodel.SmallShopsId);
                    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = demodel.SmallShopsId, GoodsIds = goodsIds2 });
                }
                #endregion
                #region 是否购买
                List<RB_Goods_Order_Extend> opaylist = new List<RB_Goods_Order_Extend>();
                if (demodel.UserId > 0)
                {
                    opaylist = goods_OrderRepository.GetCourseOrderIsPay(GoodsIds: goodsIds2, UserId: demodel.UserId ?? 0);
                }
                #endregion
                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];
                    }

                    if (demodel.SmallShopsId > 0)
                    {
                        if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                        {
                            var sspModel = smallPList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == "").FirstOrDefault();
                            if (sspModel != null)
                            {
                                //单商品设置的
                                if (sspModel.PriceType == 1)
                                {
                                    item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                }
                                else if (sspModel.PriceType == 2)
                                {
                                    item.SellingPrice = (item.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                }
                            }
                            else
                            {
                                if ((smallModel.UpPrice ?? 0) > 0)
                                {
                                    if (smallModel.PriceType == 1)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                    }
                                    else if (smallModel.PriceType == 2)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                    }
                                }
                            }
                        }
                    }

                    if (item.EnjoyMember == 1 && item.SeparateSetMember == 1)
                    {
                        item.MemberPriceList = MemberPriceList.Where(x => x.GoodsId == item.Id).ToList();
                        #region 微店处理会员价格
                        if (item.MemberPriceList.Any() && demodel.SmallShopsId > 0)
                        {
                            if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                            {
                                foreach (var mqitem in item.MemberPriceList)
                                {
                                    var sspModel = smallPList.Where(x => x.SpecificationKey == mqitem.SpecificationSort).FirstOrDefault();
                                    if (sspModel != null)
                                    {
                                        //单商品设置的
                                        if (sspModel.PriceType == 1)
                                        {
                                            mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + Math.Ceiling((mqitem.MemberPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + Math.Ceiling((mqitem.MemberPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                mqitem.MemberPrice = (mqitem.MemberPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                    }

                    item.SalesNum += (orderlist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0);

                    if (demodel.UserId > 0)
                    {
                        var omodel = opaylist.Where(x => x.GoodsId == item.Id).FirstOrDefault();
                        if (omodel != null)
                        {
                            if (omodel.PaymentTime.HasValue)
                            {
                                item.IsPay = true;
                            }
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取小程序课程详情
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="UserId"></param>
        /// <param name="SmallShopsId"></param>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public object GetAppletCourseInfo(int goodsId, int UserId, int SmallShopsId, int TenantId, int MallBaseId)
        {
            var model = goodsRepository.GetEntity(goodsId).RefMapperTo<RB_Goods_Extend>();
            if (model == null || model.TenantId != TenantId || model.MallBaseId != MallBaseId)
            {
                return null;
            }
            else
            {
                model.CoverImage = "";
                if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
                {
                    List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                    //封面图
                    model.CoverImage = CarouselIdList[0];
                }
            }

            RB_Member_User_Extend userModel = new RB_Member_User_Extend();
            if (UserId > 0)
            {
                userModel = member_UserRepository.GetEntity<RB_Member_User_Extend>(UserId);
                if (SmallShopsId == 0)
                {
                    SmallShopsId = userModel.SmallShopId;
                }
            }

            #region 基本信息
            //查询分类
            model.CategoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });

            #region 微店价格
            RB_SmallShops_Info smallModel = new RB_SmallShops_Info();
            List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
            if (SmallShopsId > 0)
            {
                smallModel = smallShops_InfoRepository.GetEntity(SmallShopsId);
                smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = SmallShopsId, GoodsId = goodsId });
                if (((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.UpPrice > 0).Any()))
                {
                    var sspModel = smallPList.Where(x => x.SpecificationKey == "").FirstOrDefault();
                    if (sspModel != null)
                    {
                        //单商品设置的
                        if (sspModel.PriceType == 1)
                        {
                            model.SellingPrice = (model.SellingPrice ?? 0) + Math.Ceiling((model.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                            model.OriginalPrice = (model.OriginalPrice ?? 0) + Math.Ceiling((model.OriginalPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                        }
                        else if (sspModel.PriceType == 2)
                        {
                            model.SellingPrice = (model.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                            model.OriginalPrice = (model.OriginalPrice ?? 0) + (sspModel.UpPrice ?? 0);
                        }
                    }
                    else
                    {
                        if ((smallModel.UpPrice ?? 0) > 0)
                        {
                            if (smallModel.PriceType == 1)
                            {
                                model.SellingPrice = (model.SellingPrice ?? 0) + Math.Ceiling((model.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                model.OriginalPrice = (model.OriginalPrice ?? 0) + Math.Ceiling((model.OriginalPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                            }
                            else if (smallModel.PriceType == 2)
                            {
                                model.SellingPrice = (model.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                model.OriginalPrice = (model.OriginalPrice ?? 0) + (smallModel.UpPrice ?? 0);
                            }
                        }
                    }
                }
            }
            #endregion

            //最大售价
            decimal MaxSellMoney = model.SellingPrice ?? 0;
            //区域
            model.AreaList = new List<RB_Goods_Area_Extend>();
            if (model.IsAreaBuy == 1)
            {
                model.AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //返佣
            model.DistributionCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
            if (model.SeparateDistribution == 1)
            {
                model.DistributionCommissionList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            //会员价格
            model.MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
            {
                model.MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }

            #region 微店处理会员价格
            if (model.MemberPriceList.Any() && SmallShopsId > 0)
            {
                if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.UpPrice > 0).Any())
                {
                    foreach (var item in model.MemberPriceList)
                    {
                        var sspModel = smallPList.Where(x => x.SpecificationKey == item.SpecificationSort).FirstOrDefault();
                        if (sspModel != null)
                        {
                            //单商品设置的
                            if (sspModel.PriceType == 1)
                            {
                                item.MemberPrice = (item.MemberPrice ?? 0) + Math.Ceiling((item.MemberPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                            }
                            else if (sspModel.PriceType == 2)
                            {
                                item.MemberPrice = (item.MemberPrice ?? 0) + (sspModel.UpPrice ?? 0);
                            }
                        }
                        else
                        {
                            if ((smallModel.UpPrice ?? 0) > 0)
                            {
                                if (smallModel.PriceType == 1)
                                {
                                    item.MemberPrice = (item.MemberPrice ?? 0) + Math.Ceiling((item.MemberPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                }
                                else if (smallModel.PriceType == 2)
                                {
                                    item.MemberPrice = (item.MemberPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            model.CustomShareImagePath = model.CustomShareImage;
            #endregion

            #region 是否收藏
            model.Favorite = false;
            if (UserId > 0)
            {
                List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.UserId),
                      FiledValue=UserId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.GoodsId),
                      FiledValue=goodsId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.TenantId),
                      FiledValue=TenantId,
                       OperatorEnum=OperatorEnum.Equal
                },
                 new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.Status),
                      FiledValue=0,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.MallBaseId),
                      FiledValue=MallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                },
            };
                if (member_CollectionRepository.Exists(wheres))
                {
                    model.Favorite = true;
                }
            }
            #endregion

            #region 最高返佣
            model.MaxShare = 0;
            decimal MyBuyCommission = 0;//自购返利
            var BasicsModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (UserId > 0)
            {
                //获取分销商信息
                var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, UserId = UserId, AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited }).FirstOrDefault();
                if (disModel != null)
                {
                    if ((BasicsModel?.IsEnableFXGrade ?? 2) == 1)
                    {
                        if ((model.PresentFXGrade ?? 0) == 0)
                        {
                            var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = TenantId, MallBaseId = MallBaseId });
                            if (FXList.Any() && FXList.Where(x => x.IsGuest == 1).Any())
                            {
                                var FXModel = FXList.Where(x => x.Id == disModel.FXGradeId).FirstOrDefault();
                                var PModel = FXList.Where(x => x.IsGuest == 1).FirstOrDefault();
                                if (FXModel != null && PModel != null)
                                {
                                    decimal CRate = 0;
                                    if (FXModel.Id == PModel.Id)
                                    {
                                        CRate = FXModel.SiblingRatio ?? 0;
                                    }
                                    else
                                    {
                                        CRate = (FXModel.CommissionRatio ?? 0) - (PModel.CommissionRatio ?? 0);
                                    }

                                    if (model.IsCustomSpecification == 1)
                                    {
                                        var dcModel = model.SpecificationPriceList.OrderByDescending(x => x.Commission).FirstOrDefault();
                                        if (dcModel.Commission > 0)
                                        {
                                            if (FXModel.DecimalType == 1)
                                            {
                                                model.MaxShare = Math.Ceiling(dcModel.Commission * CRate / 100);
                                                MyBuyCommission = Math.Ceiling(dcModel.Commission * (FXModel.CommissionRatio ?? 0) / 100);
                                            }
                                            else
                                            {
                                                model.MaxShare = Math.Ceiling(dcModel.Commission * CRate) / 100;
                                                MyBuyCommission = Math.Ceiling(dcModel.Commission * (FXModel.CommissionRatio ?? 0)) / 100;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (model.Commission > 0)
                                        {
                                            if (FXModel.DecimalType == 1)
                                            {
                                                model.MaxShare = Math.Ceiling(model.Commission * CRate / 100);
                                                MyBuyCommission = Math.Ceiling(model.Commission * (FXModel.CommissionRatio ?? 0) / 100);
                                            }
                                            else
                                            {
                                                model.MaxShare = Math.Ceiling(model.Commission * CRate) / 100;
                                                MyBuyCommission = Math.Ceiling(model.Commission * (FXModel.CommissionRatio ?? 0)) / 100;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //是否展示分享vip佣金
                            var fxcommissionList = distributor_FXCommissionRepository.GetFXCommissionList(new RB_Distributor_FXCommission_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, FXGradeId = disModel.FXGradeId ?? 0 });
                            if (fxcommissionList.Any())
                            {
                                model.MaxShare = fxcommissionList.Max(x => x.CommissionPrice ?? 0);
                            }
                        }
                    }
                    else
                    {
                        if (model.SeparateDistribution == 1)
                        {
                            var dcList = model.DistributionCommissionList.Where(x => x.DistributorGrade == disModel.GradeId).ToList();
                            //if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                            //{
                            //    model.MaxShare = dcList.Max(x => (x.OneCommission ?? 0) + (x.TwoCommission ?? 0) + (x.ThreeCommission ?? 0));
                            //}
                            //else
                            //{
                            model.MaxShare = dcList.Max(x => x.OneCommission ?? 0);
                            //}
                            // 这里需注意，可能需要分销 是否提所有返佣控制
                            if (model.SeparateDistributionMoneyType == 1)
                            {
                                model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                            }
                        }
                        else
                        {
                            if (disModel.GradeId == 0)
                            {
                                //拿分销基础配置
                                //if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                //{
                                //    model.MaxShare = (BasicsModel?.OneCommission ?? 0) + (BasicsModel?.TwoCommission ?? 0) + (BasicsModel?.ThreeCommission ?? 0);
                                //}
                                //else
                                //{
                                model.MaxShare = BasicsModel?.OneCommission ?? 0;
                                //}
                                if ((BasicsModel?.DistributorCommissionType ?? 2) == 1)
                                {
                                    model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                }
                            }
                            else if (disModel.GradeId > 0)
                            {
                                //获取分销商等级
                                var disgradeModel = distributor_GradeRepository.GetEntity(disModel.GradeId);
                                if (disgradeModel != null)
                                {
                                    //if ((BasicsModel?.IsCommissionResidue ?? 2) == 1)
                                    //{
                                    //    model.MaxShare = (disgradeModel?.OneCommission ?? 0) + (disgradeModel?.TwoCommission ?? 0) + (disgradeModel?.ThreeCommission ?? 0);
                                    //}
                                    //else
                                    //{
                                    model.MaxShare = disgradeModel?.OneCommission ?? 0;
                                    //}
                                    if ((disgradeModel?.DistributionCommissionType ?? 2) == 1)
                                    {
                                        model.MaxShare = Math.Round(model.MaxShare * MaxSellMoney / 100, 2, MidpointRounding.AwayFromZero);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            #region 最外层组装参数
            List<RB_Member_Grade_Extend> memeberList = new List<RB_Member_Grade_Extend>();
            if (UserId > 0)
            {
                if (userModel.MemberGrade > 0)
                {
                    memeberList = GetMemberGradeList(new RB_Member_Grade_Extend() { Enabled = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                }
            }

            #region 组装价格

            decimal price_member = model.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
            List<object> member_price_list = new List<object>();
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
            {
                if (model.MemberPriceList.Any())
                {
                    var mlist = model.MemberPriceList;
                    foreach (var qitem in mlist)
                    {
                        member_price_list.Add(new
                        {
                            member_grade = qitem.MemberGrade,
                            member_price = qitem.MemberPrice
                        });
                    }
                    if (UserId > 0 && userModel.MemberGrade > 0)
                    {
                        var gmodel = mlist.Where(x => x.MemberGrade == userModel.MemberGrade).FirstOrDefault();
                        price_member = gmodel.MemberPrice ?? 0;
                    }
                    else
                    {
                        price_member = mlist.Max(x => x.MemberPrice ?? 0);
                    }
                }
            }
            else
            {
                //根据会员等级查找会员价格
                foreach (var qitem in memeberList)
                {
                    var mprice = Math.Round((model.SellingPrice ?? 0) * (qitem.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                    member_price_list.Add(new
                    {
                        member_grade = qitem.Grade,
                        member_price = mprice
                    });
                }
                if (UserId > 0 && userModel.MemberGrade > 0 && memeberList.Any())
                {
                    var gmodel = memeberList.Where(x => x.Grade == userModel.MemberGrade).FirstOrDefault();
                    price_member = Math.Round((model.SellingPrice ?? 0) * (gmodel?.Discount ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                }
                else if (memeberList.Any())
                {
                    price_member = Math.Round((model.SellingPrice ?? 0) * (memeberList.Max(x => x.Discount) ?? 10) / 10, 2, MidpointRounding.AwayFromZero);
                }
            }
            #endregion

            #region 赠送积分
            int Integral = 0;
            if (model.IntegralPresent > 0)
            {
                Integral = model.IntegralPresent ?? 0;
                if (model.IntegralPresentType == 1)
                {
                    Integral = Convert.ToInt32(Math.Floor((model.SellingPrice ?? 0) * (model.IntegralPresent ?? 0) / 100));
                }
            }
            int CommentIntegral = 0;
            if (model.IntegralComment > 0)
            {
                CommentIntegral = model.IntegralComment ?? 0;
                if (model.IntegralCommentType == 1)
                {
                    CommentIntegral = Convert.ToInt32(Math.Floor((model.SellingPrice ?? 0) * (model.IntegralComment ?? 0) / 100));
                }
            }
            #endregion

            #region 会员价格
            decimal price_member_max = 0, price_member_min = 0, price_min = 0, price_max = 0;
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1 && model.MemberPriceList.Any())
            {
                price_member_min = model.MemberPriceList.Min(x => x.MemberPrice ?? 0);
                price_member_max = model.MemberPriceList.Max(x => x.MemberPrice ?? 0);
                if (userModel.MemberGrade > 0)
                {
                    price_min = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Min(x => x.MemberPrice ?? 0);
                    price_max = model.MemberPriceList.Where(x => x.MemberGrade == userModel.MemberGrade).Max(x => x.MemberPrice ?? 0);
                }
            }
            else
            {

                if (model.IsCustomSpecification == 1)
                {
                    price_member_min = price_min = model.SpecificationPriceList.Where(x => x.SellingPrice > 0).Min(x => x.SellingPrice ?? 0);
                    price_member_max = price_max = model.SpecificationPriceList.Where(x => x.SellingPrice > 0).Max(x => x.SellingPrice ?? 0);
                }
                else
                {
                    price_member_min = price_member_max = price_min = price_max = model.SellingPrice ?? 0;
                }
                if (memeberList.Any())
                {
                    List<decimal> pricelist = new List<decimal>();
                    foreach (var item in memeberList)
                    {
                        pricelist.Add(price_member_min * (item.Discount ?? 10) / 10);
                        pricelist.Add(price_member_max * (item.Discount ?? 10) / 10);
                    }
                    price_member_min = pricelist.Min(x => x);
                    price_member_max = pricelist.Max(x => x);
                    if (userModel.MemberGrade > 0)
                    {
                        if (price_min > (model.SellingPrice ?? 0)) { price_min = model.SellingPrice ?? 0; }
                        if (price_max < (model.SellingPrice ?? 0)) { price_max = model.SellingPrice ?? 0; }
                        price_min = price_member_min * (memeberList.Where(x => x.Id == userModel.MemberGrade).FirstOrDefault()?.Discount ?? 10) / 10;
                        price_max = price_member_max * (memeberList.Where(x => x.Id == userModel.MemberGrade).FirstOrDefault()?.Discount ?? 10) / 10;
                    }
                }
            }
            price_member_max = Math.Round(price_member_max, 2, MidpointRounding.AwayFromZero);
            price_member_min = Math.Round(price_member_min, 2, MidpointRounding.AwayFromZero);
            //price_min = Math.Round(price_min, 2, MidpointRounding.AwayFromZero);
            //price_max = Math.Round(price_max, 2, MidpointRounding.AwayFromZero);//先使用会员的  
            price_min = price_member_min;
            price_max = price_member_max;
            #endregion

            #region 教师列表
            model.TeacherList = goods_WK_TeacherRepository.GetList(new RB_Goods_WK_Teacher_Extend() { GoodsId = goodsId });
            #endregion

            #region 轮播图
            //轮播
            model.CarouselImageList = new List<RB_ImageCommonModel>();
            if (!string.IsNullOrWhiteSpace(model.VideoAddress))
            {
                model.CarouselImageList.Add(new RB_ImageCommonModel()
                {
                    Id = 0,
                    Name = "",
                    Type = 1,
                    Path = model.VideoAddress
                });
            }
            if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
            {
                List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                //轮播图
                foreach (var item in CarouselIdList)
                {
                    model.CarouselImageList.Add(new RB_ImageCommonModel()
                    {
                        Id = 0,
                        Name = "",
                        Path = item
                    });
                }
            }
            #endregion

            #region 课程列表  单独写个分页接口展示
            //model.CourseList = goods_WK_CourseRepository.GetList(new RB_Goods_WK_Course_Extend() { GoodsId = goodsId });
            #endregion

            #region 订单购买
            bool IsPay = false;//是否支付  1是 2否
            bool IsOrders = false;//是否下单  1是  2否
            if (UserId > 0)
            {
                var omodel = goods_OrderRepository.GetCourseOrderIsPay(GoodsIds: goodsId.ToString(), UserId: UserId).FirstOrDefault();
                if (omodel != null)
                {
                    IsOrders = true;
                    if (omodel.PaymentTime.HasValue)
                    {
                        IsPay = true;
                    }
                }
            }
            #endregion

            #region 返回参数

            int IsAllowShare = 1;
            if (model.CategoryList.Where(x => x.IsForeignShare == 2).Any())
            {
                IsAllowShare = 2;
            }
            //订单课程的销售数量
            int payment_num = goods_OrderRepository.GetGoodsOrderPaymentInfo(goodsId);

            return new
            {
                goods = new
                {
                    id = model.Id,
                    mall_id = model.MallBaseId,
                    mch_id = model.TenantId,//暂  商户id
                    status = model.GoodsStatus,
                    isAllowShare = IsAllowShare,//是否可以分享
                    advertising = model.Advertising,//广告词
                    price = model.SellingPrice,

                    give_integral = model.IntegralPresent,
                    give_integral_type = model.IntegralPresentType,
                    forehead_integral = model.PointsDeduction,//暂  积分抵扣
                    forehead_integral_type = model.PointsDeductionType,//暂  积分抵扣类型
                    accumulative = model.IsMultipleDeduction,//多件抵扣
                    individual_share = userModel?.IsDistributor ?? 2,// 是否分销商
                    attr_setting_type = model.SeparateDistributionType,//分销类型
                    is_level = model.EnjoyMember,//是否销售会员价格
                    is_level_alone = model.SeparateSetMember,//是否单独设置会员价
                    share_type = model.SeparateDistributionMoneyType,//分销佣金类型

                    app_share_pic = model.CustomShareImagePath,
                    app_share_title = model.CustomShareTitles,
                    sort = model.Sort,
                    course_score = model.CourseScore,
                    created_at = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                    updated_at = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",

                    sales = (model.SalesNum ?? 0) + payment_num,//已售出数量 + 订单商品数量//
                    name = model.Name,
                    original_price = model.OriginalPrice,
                    cover_pic = model.CoverImage,
                    unit = model.Unit,
                    detail = model.GoodsDetails,
                    video_url = model.VideoAddress,
                    level_show = (userModel?.MemberGrade ?? 0) > 0 ? 1 : 2,//是否显示会员价
                    is_pay = IsPay,
                    is_orders = IsOrders,
                    share = model.MaxShare,//分销佣金
                    myBuyCommission = MyBuyCommission,//粉象模式  自购返利
                    favorite = model.Favorite,//是否收藏
                    goods_marketing_award = new
                    {
                        integral = new
                        {
                            title = Integral > 0 ? "购买可得" + Integral + "积分" : ""
                        },
                        commentIntegral = new
                        {
                            title = CommentIntegral > 0 ? "购买并评论可得" + Integral + "积分" : ""
                        }
                    },
                    extra_quick_share = new
                    {
                        share_pic = model.CarouselImageList.Select(x => new
                        {
                            id = x.Id,
                            pic_url = x.Path
                        }),
                        share_text = model.Name,
                        mall_name = model.MallName,
                        format_time = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
                    },
                    marketingLogo = model.MarketingLogo,
                    //分类
                    cats = model.CategoryList.Select(x => new
                    {
                        x.CategoryId,
                        x.CategoryName
                    }),
                    video_type = model.VideoType,
                    teacher_list = model.TeacherList.Select(x => new
                    {
                        teacher_id = x.TeacherId,
                        teacher_logo = x.TeacherLogo,
                        teacher_name = x.Name
                    }),
                    course_lable_list = !string.IsNullOrEmpty(model?.CourseLable) && model?.CourseLable != "[]" ? JsonConvert.DeserializeObject<List<string>>(model?.CourseLable) : new List<string>()
                },
                delivery = ""
            };
            #endregion
            #endregion
        }

        /// <summary>
        /// 获取课程是否收藏
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="userId"></param>
        /// <param name="smallShopsId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetAppletCourseCollect(int goodsId, int UserId, int TenantId, int MallBaseId)
        {
            if (UserId > 0)
            {
                List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.UserId),
                      FiledValue=UserId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.GoodsId),
                      FiledValue=goodsId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.TenantId),
                      FiledValue=TenantId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.MallBaseId),
                      FiledValue=MallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                },
                 new WhereHelper(){
                     FiledName=nameof(RB_Member_Collection_Extend.Status),
                      FiledValue=0,
                       OperatorEnum=OperatorEnum.Equal
                },
            };
                if (member_CollectionRepository.Exists(wheres))
                {
                    return new
                    {
                        Favorite = true
                    };
                }
            }

            return new
            {
                Favorite = false
            };
        }

        /// <summary>
        /// 获取小程序课程章节列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="goodsId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public List<RB_Goods_WK_Course_Extend> GetAppletGoodsCourseList(int pageIndex, int pageSize, out long count, int goodsId, int userId, int tenantId, int mallBaseId)
        {
            var list = goods_WK_CourseRepository.GetPageList(pageIndex, pageSize, out count, new RB_Goods_WK_Course_Extend() { GoodsId = goodsId, TenantId = tenantId, MallBaseId = mallBaseId });
            if (userId > 0 && list.Any())
            {
                //查询用户课程章节 阅读情况
                var slist = goods_WK_CourseStudyRepository.GetList(new RB_Goods_WK_CourseStudy_Extend() { UserId = userId, CourseIds = string.Join(",", list.Select(x => x.Id)) });
                foreach (var item in list)
                {
                    item.IsRead = 2;
                    if (slist.Where(x => x.CourseId == item.Id).Any())
                    {
                        item.IsRead = 1;//已阅读
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取课程是否购买
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public int GetAppletCourseIsPay(int goodsId, int UserId)
        {
            if (UserId <= 0)
            {
                return 0;
            }
            var goodsModel = goodsRepository.GetEntity(goodsId);
            if (goodsModel == null)
            {
                return 0;
            }
            if (goodsModel.SellingPrice == 0)
            {
                return 1;
            }

            var omodel = goods_OrderRepository.GetCourseOrderIsPay(GoodsIds: goodsId.ToString(), UserId: UserId).FirstOrDefault();
            if (omodel != null)
            {
                if (omodel.PaymentTime.HasValue)
                {
                    return 1;
                }
                return 2;
            }
            return 0;
        }
        #endregion

        #region 素材管理
        /// <summary>
        /// 获取素材分组列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Material_Group_Extend> GetMaterialGroupList(RB_Material_Group_Extend dmodel)
        {
            var list = material_GroupRepository.GetList(dmodel);
            return list;
        }


        /// <summary>
        /// 获取素材分组分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Material_Info_Extend> GetMaterialInfoPageList(int pageIndex, int pageSize, out long count, RB_Material_Info_Extend dmodel)
        {
            var list = material_InfoRepository.GetPageList(pageIndex, pageSize, out count, dmodel);
            return list;
        }

        /// <summary>
        /// 新增分组
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMaterialGroupInfo(RB_Material_Group_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Material_Group.Name),demodel.Name},
                    { nameof(RB_Material_Group.Sort),demodel.Sort},
                    { nameof(RB_Material_Group.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                     FiledName=nameof(RB_Material_Group.Id),
                      FiledValue=demodel.Id,
                       OperatorEnum=OperatorEnum.Equal
                    }
                };
                return material_GroupRepository.Update(keyValues, wheres);
            }
            else
            {
                return material_GroupRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 设置素材信息
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMaterialInfo(RB_Material_Info_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Material_Info.Name),demodel.Name},
                    { nameof(RB_Material_Info.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                     FiledName=nameof(RB_Material_Group.Id),
                      FiledValue=demodel.Id,
                       OperatorEnum=OperatorEnum.Equal
                    }
                };
                return material_InfoRepository.Update(keyValues, wheres);
            }
            else
            {
                return material_InfoRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 设置分组回收
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialGroupRecycled(int groupId, string uid, int mallBaseId)
        {
            var gmodel = material_GroupRepository.GetEntity(groupId);
            if (gmodel == null)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Material_Group.Recycled),2},
                { nameof(RB_Material_Group.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.Id),
                    FiledValue=groupId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.TenantId),
                    FiledValue=Convert.ToInt32(uid),
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            bool flag = material_GroupRepository.Update(keyValues, wheres);
            if (flag)
            {
                //分组下所有素材全回收
                material_InfoRepository.SetMaterialInfoRecycled(groupId, Convert.ToInt32(uid), mallBaseId);
            }
            return flag;
        }

        /// <summary>
        /// 删除分组
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelMaterialGroupInfo(int groupId, string uid, int mallBaseId)
        {
            var gmodel = material_GroupRepository.GetEntity(groupId);
            if (gmodel == null)
            {
                return false;
            }
            if (gmodel.Recycled != 2)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Material_Group.Status),1},
                { nameof(RB_Material_Group.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.Id),
                    FiledValue=groupId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.TenantId),
                    FiledValue=Convert.ToInt32(uid),
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            bool flag = material_GroupRepository.Update(keyValues, wheres);
            if (flag)
            {
                //删除分组下所有的素材
                material_InfoRepository.DelMaterialInfo("", uid, mallBaseId, groupId);
            }
            return flag;
        }

        /// <summary>
        /// 设置分组还原
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialGroupRestore(int groupId, string uid, int mallBaseId)
        {
            var gmodel = material_GroupRepository.GetEntity(groupId);
            if (gmodel == null)
            {
                return false;
            }
            if (gmodel.Recycled != 2)
            {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Material_Group.Recycled),1},
                { nameof(RB_Material_Group.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.Id),
                    FiledValue=groupId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.TenantId),
                    FiledValue=Convert.ToInt32(uid),
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Material_Group.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            return material_GroupRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 设置素材回收
        /// </summary>
        /// <param name="materialIds"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialInfoRecycled(string materialIds, string uid, int mallBaseId)
        {
            bool flag = material_InfoRepository.SetMaterialListRecycled(materialIds, uid, mallBaseId);
            return flag;
        }

        /// <summary>
        /// 删除素材
        /// </summary>
        /// <param name="materialIds"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelMaterialInfo(string materialIds, string uid, int mallBaseId)
        {
            bool flag = material_InfoRepository.DelMaterialInfo(materialIds, uid, mallBaseId);
            return flag;
        }

        /// <summary>
        /// 设置素材还原
        /// </summary>
        /// <param name="materialIds"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialInfoRestore(string materialIds, string uid, int mallBaseId)
        {
            var trans = material_InfoRepository.DbTransaction;
            try
            {
                var list = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = materialIds, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                if (list.Any())
                {
                    //查询出所有的分组
                    var glist = material_GroupRepository.GetList(new RB_Material_Group_Extend() { GroupIds = string.Join(",", list.Select(x => x.GroupId).Distinct()), TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId });
                    if (glist.Where(x => x.Recycled == 2).Any())
                    {
                        foreach (var item in glist.Where(x => x.Recycled == 2))
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Material_Group.Recycled),1},
                                { nameof(RB_Material_Group.UpdateDate),DateTime.Now},
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                    FiledName=nameof(RB_Material_Group.Id),
                                    FiledValue=item.Id,
                                    OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                    FiledName=nameof(RB_Material_Group.TenantId),
                                    FiledValue=Convert.ToInt32(uid),
                                    OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                    FiledName=nameof(RB_Material_Group.MallBaseId),
                                    FiledValue=mallBaseId,
                                    OperatorEnum=OperatorEnum.Equal
                                },
                            };
                            material_GroupRepository.Update(keyValues, wheres, trans);
                        }
                    }
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Material_Info.Recycled),1},
                            { nameof(RB_Material_Info.UpdateDate),DateTime.Now},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                FiledName=nameof(RB_Material_Info.Id),
                                FiledValue=item.Id,
                                OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                FiledName=nameof(RB_Material_Info.TenantId),
                                FiledValue=Convert.ToInt32(uid),
                                OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                FiledName=nameof(RB_Material_Info.MallBaseId),
                                FiledValue=mallBaseId,
                                OperatorEnum=OperatorEnum.Equal
                            },
                        };
                        material_InfoRepository.Update(keyValues, wheres, trans);
                    }
                }
                material_InfoRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetMaterialInfoRestore");
                material_InfoRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 设置分组转移
        /// </summary>
        /// <param name="materialIds"></param>
        /// <param name="groupId"></param>
        /// <param name="Type"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetMaterialInfoTransfer(string materialIds, int groupId, int Type, string uid, int mallBaseId)
        {
            var gmodel = material_GroupRepository.GetEntity(groupId);
            if (gmodel == null)
            {
                return false;
            }
            if (gmodel.Status == 1 || gmodel.Recycled == 2 || gmodel.Type != Type)
            {
                return false;
            }
            return material_InfoRepository.SetMaterialInfoTransfer(materialIds, groupId, uid, mallBaseId);
        }

        #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_Product_Category_Extend> GetProductCategoryPageList(int pageIndex, int pageSize, out long count, RB_Product_Category_Extend demodel)
        {
            var list = product_CategoryRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                List<int> ImgIds = new List<int>();
                ImgIds.AddRange(list.Select(x => x.Icon ?? 0).Distinct());
                ImgIds.AddRange(list.Select(x => x.BigIcon ?? 0).Distinct());
                ImgIds.AddRange(list.Select(x => x.AdvertisingImage ?? 0).Distinct());
                List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
                if (ImgIds.Any())
                {
                    mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = string.Join(",", ImgIds), TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                foreach (var item in list)
                {
                    item.IconPath = mlist.Where(x => x.Id == item.Icon).FirstOrDefault()?.Path ?? "";
                    item.BigIconPath = mlist.Where(x => x.Id == item.BigIcon).FirstOrDefault()?.Path ?? "";
                    item.AdvertisingImagePath = mlist.Where(x => x.Id == item.AdvertisingImage).FirstOrDefault()?.Path ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelProductCategoryInfo(int categoryId, int tenantId, int mallBaseId)
        {
            var trans = product_CategoryRepository.DbTransaction;
            try
            {
                var list = GetProductCategoryForALLChlid(categoryId, tenantId, mallBaseId);
                foreach (var item in list)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Product_Category.Status),1},
                        { nameof(RB_Product_Category.UpdateDate),DateTime.Now},
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Product_Category.Id),
                              FiledValue=categoryId,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Product_Category.TenantId),
                              FiledValue=tenantId,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Product_Category.MallBaseId),
                              FiledValue=mallBaseId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    bool flag = product_CategoryRepository.Update(keyValues, wheres, trans);
                }
                product_CategoryRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "DelProductCategoryInfo");
                product_CategoryRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 获取分类样式
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_Product_CategoryStyle_Extend GetProductCategoryStyleInfo(int tenantId, int mallBaseId)
        {
            return product_CategoryStyleRepository.GetList(new RB_Product_CategoryStyle_Extend() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
        }

        /// <summary>
        /// 保存分类样式
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductCategoryStyleInfo(RB_Product_CategoryStyle_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_CategoryStyle.Type),demodel.Type},
                    { nameof(RB_Product_CategoryStyle.Style),demodel.Style},
                    { nameof(RB_Product_CategoryStyle.CategoryNum),demodel.CategoryNum},
                    { nameof(RB_Product_CategoryStyle.RowNum),demodel.RowNum},
                    { nameof(RB_Product_CategoryStyle.UpdateDate),demodel.UpdateDate},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_Product_Category.Id),
                            FiledValue=demodel.Id,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                return product_CategoryStyleRepository.Update(keyValues, wheres);
            }
            else
            {
                return product_CategoryStyleRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 保存排序
        /// </summary>
        /// <param name="delist"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetProductCategorySort(List<RB_Product_CategorySort> delist, int tenantId, int mallBaseId)
        {
            var trans = product_CategoryRepository.DbTransaction;
            try
            {
                string ids = string.Join(",", delist.Select(x => x.Id));
                var list = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { CategoryIds = ids, TenantId = tenantId, MallBaseId = mallBaseId });
                if (list.Any())
                {
                    foreach (var item in list)
                    {
                        var demodel = delist.Where(x => x.Id == item.Id).FirstOrDefault();
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Product_Category.Sort),demodel.Sort},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Product_Category.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag = product_CategoryRepository.Update(keyValues, wheres, trans);
                    }
                }
                product_CategoryRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProductCategorySort");
                product_CategoryRepository.DBSession.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 获取树形结构列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Product_CategoryTree> GetProductCategoryTreeList(RB_Product_Category_Extend demodel)
        {
            List<RB_Product_CategoryTree> treeList = new List<RB_Product_CategoryTree>();
            var list = product_CategoryRepository.GetList(demodel);
            if (list.Any())
            {
                List<int> ImgIds = new List<int>();
                ImgIds.AddRange(list.Select(x => x.Icon ?? 0).Distinct());
                ImgIds.AddRange(list.Select(x => x.BigIcon ?? 0).Distinct());
                ImgIds.AddRange(list.Select(x => x.AdvertisingImage ?? 0).Distinct());
                List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
                if (ImgIds.Any())
                {
                    mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = string.Join(",", ImgIds), TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                foreach (var item in list)
                {
                    item.IconPath = mlist.Where(x => x.Id == item.Icon).FirstOrDefault()?.Path ?? "";
                    item.BigIconPath = mlist.Where(x => x.Id == item.BigIcon).FirstOrDefault()?.Path ?? "";
                    item.AdvertisingImagePath = mlist.Where(x => x.Id == item.AdvertisingImage).FirstOrDefault()?.Path ?? "";
                    item.CategoryPageTypeStr = item.CategoryPageType.GetEnumName();
                }
                list = list.OrderBy(x => x.Sort).ThenBy(x => x.Id).ToList();
                treeList = GetProductCategoryChildTree(list, 0);
            }

            return treeList;
        }

        /// <summary>
        /// 获取子集列表
        /// </summary>
        /// <param name="list"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public List<RB_Product_CategoryTree> GetProductCategoryChildTree(List<RB_Product_Category_Extend> list, int parentId)
        {
            List<RB_Product_CategoryTree> RList = new List<RB_Product_CategoryTree>();
            var CList = list.Where(x => x.ParentId == parentId).ToList();
            foreach (var item in CList)
            {
                var cmodel = new RB_Product_CategoryTree
                {
                    Id = item.Id,
                    Name = item.Name,
                    Icon = item.Icon ?? 0,
                    IconPath = item.IconPath
                };
                cmodel.ChildList = GetProductCategoryChildTree(list, item.Id);
                RList.Add(cmodel);
            }
            return RList;
        }

        /// <summary>
        /// 保存商品分类
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductCategoryInfo(RB_Product_Category_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_Category.AdvertisingAddress),demodel.AdvertisingAddress},
                    { nameof(RB_Product_Category.AdvertisingImage),demodel.AdvertisingImage},
                    { nameof(RB_Product_Category.BigIcon),demodel.BigIcon},
                    { nameof(RB_Product_Category.Enabled),demodel.Enabled},
                    { nameof(RB_Product_Category.Icon),demodel.Icon},
                    { nameof(RB_Product_Category.IsShow),demodel.IsShow},
                    { nameof(RB_Product_Category.Name),demodel.Name},
                    { nameof(RB_Product_Category.Sort),demodel.Sort},
                    { nameof(RB_Product_Category.IsForeignShare),demodel.IsForeignShare},
                    { nameof(RB_Product_Category.UpdateDate),demodel.UpdateDate},
                    { nameof(RB_Product_Category.CategoryPageType),demodel.CategoryPageType},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Product_Category.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return product_CategoryRepository.Update(keyValues, wheres);
            }
            else
            {
                int Id = product_CategoryRepository.Insert(demodel);
                if (Id > 0)
                {
                    int RootId = Id;
                    if (demodel.ParentId > 0)
                    {
                        var pmodel = product_CategoryRepository.GetEntity(demodel.ParentId);
                        RootId = pmodel?.RootId ?? 0;
                    }
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Product_Category.RootId),RootId},
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Product_Category.Id),
                                FiledValue=Id,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    product_CategoryRepository.Update(keyValues, wheres);
                }
                return Id > 0;
            }
        }

        /// <summary>
        /// 获取商品分类
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public RB_Product_Category_Extend GetProductCategoryInfo(int categoryId)
        {
            var model = product_CategoryRepository.GetEntity(categoryId).RefMapperTo<RB_Product_Category_Extend>();
            List<int> ImgIds = new List<int>
            {
                model.Icon ?? 0,
                model.BigIcon ?? 0,
                model.AdvertisingImage ?? 0
            };
            List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
            if (ImgIds.Any())
            {
                mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = string.Join(",", ImgIds) });
            }

            model.IconPath = mlist.Where(x => x.Id == model.Icon).FirstOrDefault()?.Path ?? "";
            model.BigIconPath = mlist.Where(x => x.Id == model.BigIcon).FirstOrDefault()?.Path ?? "";
            model.AdvertisingImagePath = mlist.Where(x => x.Id == model.AdvertisingImage).FirstOrDefault()?.Path ?? "";
            var p1Model = product_CategoryRepository.GetEntity(model?.ParentId);
            if (p1Model != null)
            {
                model.Parent1Name = p1Model.Name;
                var p2Model = product_CategoryRepository.GetEntity(p1Model?.ParentId);
                if (p2Model != null)
                {
                    model.Parent1Name = p2Model.Name;
                    model.Parent2Name = p1Model.Name;//黄媛媛要求  1表示1级  2表示2级
                }
            }
            return model;
        }

        /// <summary>
        /// 获取当前分类的所有子集分类
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="tid"></param>
        /// <param name="mid"></param>
        /// <returns></returns>
        public List<RB_Product_Category_Extend> GetProductCategoryForALLChlid(int categoryId, int tid, int mid)
        {
            var model = product_CategoryRepository.GetEntity(categoryId);
            var list = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { RootId = model.RootId, TenantId = tid, MallBaseId = mid });
            List<RB_Product_Category_Extend> RList = GetProductCategoryALLChild(list, model.Id);
            RList.AddRange(list.Where(x => x.Id == model.Id).ToList());
            return RList;
        }

        /// <summary>
        /// 获取分类列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Product_Category_Extend> GetCategoryListModule(RB_Product_Category_Extend dmodel)
        {
            return product_CategoryRepository.GetList(dmodel);
        }

        /// <summary>
        /// 获取所有子集
        /// </summary>
        /// <param name="list"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private List<RB_Product_Category_Extend> GetProductCategoryALLChild(List<RB_Product_Category_Extend> list, int id)
        {
            List<RB_Product_Category_Extend> RList = new List<RB_Product_Category_Extend>();
            var list2 = list.Where(x => x.ParentId == id).ToList();
            RList.AddRange(list2);
            foreach (var item in list2)
            {
                RList.AddRange(GetProductCategoryALLChild(list, item.Id));
            }
            return RList;
        }

        /// <summary>
        /// 分类转移
        /// </summary>
        /// <param name="cmodel"></param>
        /// <param name="parentId"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public bool SetProductCategoryTransfer(RB_Product_Category_Extend cmodel, int parentId, List<RB_Product_Category_Extend> list)
        {
            var trans = product_CategoryRepository.DbTransaction;
            try
            {
                int RootId = cmodel.Id;
                int Tier = 0;
                if (parentId > 0)
                {
                    var pmodel = product_CategoryRepository.GetEntity(parentId);
                    if (pmodel == null)
                    {
                        return false;
                    }
                    RootId = pmodel.RootId ?? 0;
                    Tier = (pmodel.Tier ?? 0) + 1;
                }
                else
                {
                    Tier = 1;
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_Category.ParentId),parentId},
                    { nameof(RB_Product_Category.UpdateDate),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper()
                    {
                         FiledName=nameof(RB_Product_Category.Id),
                         FiledValue=cmodel.Id,
                         OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = product_CategoryRepository.Update(keyValues, wheres, trans);
                if (flag)
                {
                    //更新所有子集rootid=
                    foreach (var item in list)
                    {
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            { nameof(RB_Product_Category.RootId),RootId},
                            { nameof(RB_Product_Category.Tier),Tier+(item.Tier??0)-(cmodel.Tier??0) }
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_Product_Category.Id),
                                    FiledValue=item.Id,
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        product_CategoryRepository.Update(keyValues1, wheres1, trans);
                    }
                }
                product_CategoryRepository.DBSession.Commit();
                return flag;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProductCategoryTransfer");
                product_CategoryRepository.DBSession.Rollback();
                return false;
            }
        }

        #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_Product_Specification_Extend> GetProducSpecificationPageList(int pageIndex, int pageSize, out long count, RB_Product_Specification_Extend demodel)
        {
            var list = product_SpecificationRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            foreach (var item in list)
            {
                item.SpecList = new List<string>();
                if (!string.IsNullOrEmpty(item.Content))
                {
                    item.SpecList = JsonConvert.DeserializeObject<List<string>>(item.Content);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取规格列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Product_Specification_Extend> GetProducSpecificationList(RB_Product_Specification_Extend demodel)
        {
            var list = product_SpecificationRepository.GetList(demodel);
            foreach (var item in list)
            {
                item.SpecList = new List<string>();
                if (!string.IsNullOrEmpty(item.Content))
                {
                    item.SpecList = JsonConvert.DeserializeObject<List<string>>(item.Content);
                }
            }
            return list;
        }

        /// <summary>
        /// 保存修改规格
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductSpecificationInfo(RB_Product_Specification_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_Specification.Name),demodel.Name},
                    { nameof(RB_Product_Specification.Content),demodel.Content},
                    { nameof(RB_Product_Specification.UpdateDate),demodel.UpdateDate}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Product_Specification.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return product_SpecificationRepository.Update(keyValues, wheres);
            }
            else
            {
                return product_SpecificationRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 删除商品规格
        /// </summary>
        /// <param name="specificationId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelProductSpecificationInfo(int specificationId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Product_Specification.Status),1},
                { nameof(RB_Product_Specification.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Product_Specification.Id),
                        FiledValue=specificationId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Product_Specification.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Product_Specification.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return product_SpecificationRepository.Update(keyValues, wheres);
        }
        #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_Product_QuickBuy_Extend> GetProductQuickBuyPageList(int pageIndex, int pageSize, out long count, RB_Product_QuickBuy_Extend demodel)
        {
            var list = product_QuickBuyRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string imgids = string.Join(",", list.Where(x => x.Icon > 0).Select(x => x.Icon));
                List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
                if (!string.IsNullOrEmpty(imgids))
                {
                    mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = imgids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    item.IconPath = mlist.Where(x => x.Id == item.Icon).FirstOrDefault()?.Path ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 获取快速购买列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Product_QuickBuy_Extend> GetProductQuickBuyList(RB_Product_QuickBuy_Extend demodel)
        {
            var list = product_QuickBuyRepository.GetAllList(demodel);
            if (list.Any())
            {
                string imgids = string.Join(",", list.Where(x => x.Icon > 0).Select(x => x.Icon));
                List<RB_Material_Info_Extend> mlist = new List<RB_Material_Info_Extend>();
                if (!string.IsNullOrEmpty(imgids))
                {
                    mlist = material_InfoRepository.GetList(new RB_Material_Info_Extend() { MaterialIds = imgids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                foreach (var item in list)
                {
                    item.IconPath = mlist.Where(x => x.Id == item.Icon).FirstOrDefault()?.Path ?? "";
                }
            }
            return list;
        }

        /// <summary>
        /// 验证快速购买分类
        /// </summary>
        /// <param name="id"></param>
        /// <param name="categoryId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool ValidateQuickBuyCategory(int id, int? categoryId, int tenantId, int mallBaseId)
        {
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.CategoryId),
                        FiledValue=categoryId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.Status),
                        FiledValue=0,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            if (id > 0)
            {
                wheres.Add(new WhereHelper()
                {
                    FiledName = nameof(RB_Product_QuickBuy.Id),
                    FiledValue = id,
                    OperatorEnum = OperatorEnum.NotEqual
                });
            }
            return product_QuickBuyRepository.Exists(wheres);
        }

        /// <summary>
        /// 新增修改快速购买
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductQuickBuyInfo(RB_Product_QuickBuy_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_QuickBuy.CategoryId),demodel.CategoryId},
                    { nameof(RB_Product_QuickBuy.Sort),demodel.Sort},
                    { nameof(RB_Product_QuickBuy.UpdateDate),DateTime.Now}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_Product_QuickBuy.Id),
                            FiledValue=demodel.Id,
                            OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.TenantId),
                        FiledValue=demodel.TenantId,
                        OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                        FiledName=nameof(RB_Product_QuickBuy.MallBaseId),
                        FiledValue=demodel.MallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                    },
                };
                return product_QuickBuyRepository.Update(keyValues, wheres);
            }
            else
            {
                return product_QuickBuyRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 删除快速购买
        /// </summary>
        /// <param name="quickBuyId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelProductQuickBuyInfo(int quickBuyId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Product_QuickBuy.Status),1},
                { nameof(RB_Product_QuickBuy.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Product_QuickBuy.Id),
                    FiledValue=quickBuyId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Product_QuickBuy.TenantId),
                    FiledValue=tenantId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Product_QuickBuy.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            return product_QuickBuyRepository.Update(keyValues, wheres);
        }

        #endregion

        #region 推荐设置
        /// <summary>
        /// 获取推荐设置详情
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_Product_Recommend_Extend GetProductRecommendSetInfo(int tenantId, int mallBaseId)
        {
            var model = product_RecommendRepository.GetList(new RB_Product_Recommend_Extend() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (model == null)
            {
                return new RB_Product_Recommend_Extend();
            }
            model.OrderProductList = new List<RB_ProductRecommendModel>();
            if (model.IsOrderRecommend == 1 && !string.IsNullOrEmpty(model.OrderProductIds))
            {
                //查询商品
                var glist = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = model.OrderProductIds, TenantId = tenantId, MallBaseId = mallBaseId });
                foreach (var item in glist)
                {
                    //轮播图
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<int> CarouselIdList = JsonConvert.DeserializeObject<List<int>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = material_InfoRepository.GetEntity(CarouselIdList[0])?.Path ?? "";
                    }
                }
                foreach (var item in glist)
                {
                    model.OrderProductList.Add(new RB_ProductRecommendModel()
                    {
                        Id = item.Id,
                        Image = item.CoverImage,
                        Name = item.Name
                    });
                }
            }
            model.CommentProductList = new List<RB_ProductRecommendModel>();
            if (model.IsCommentRecommend == 1 && !string.IsNullOrEmpty(model.CommentProductIds))
            {
                var glist = goodsRepository.GetList(new RB_Goods_Extend() { GoodsIds = model.CommentProductIds, TenantId = tenantId, MallBaseId = mallBaseId });
                foreach (var item in glist)
                {
                    //轮播图
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                }
                foreach (var item in glist)
                {
                    model.CommentProductList.Add(new RB_ProductRecommendModel()
                    {
                        Id = item.Id,
                        Image = item.CoverImage,
                        Name = item.Name
                    });
                }
            }
            return model;
        }

        /// <summary>
        /// 保存推荐设置
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductRecommendSetInfo(RB_Product_Recommend_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_Recommend.CommentProductIds),demodel.CommentProductIds},
                    { nameof(RB_Product_Recommend.CommentRecommentStatus),demodel.CommentRecommentStatus},
                    { nameof(RB_Product_Recommend.DetailRecommendNum),demodel.DetailRecommendNum},
                    { nameof(RB_Product_Recommend.DetailRecommendStatus),demodel.DetailRecommendStatus},
                    { nameof(RB_Product_Recommend.DetailRecommendSame),demodel.DetailRecommendSame},
                    { nameof(RB_Product_Recommend.IsCommentRecommend),demodel.IsCommentRecommend},
                    { nameof(RB_Product_Recommend.IsOrderRecommend),demodel.IsOrderRecommend},
                    { nameof(RB_Product_Recommend.OrderCompleteStatus),demodel.OrderCompleteStatus},
                    { nameof(RB_Product_Recommend.OrderProductIds),demodel.OrderProductIds},
                    { nameof(RB_Product_Recommend.UpdateDate),demodel.UpdateDate}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Product_Recommend.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return product_RecommendRepository.Update(keyValues, wheres);
            }
            else
            {
                return product_RecommendRepository.Insert(demodel) > 0;
            }
        }

        #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_Product_Service_Extend> GetProductServicePageList(int pageIndex, int pageSize, out long count, RB_Product_Service_Extend demodel)
        {
            return product_ServiceRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取商品服务列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Product_Service_Extend> GetProductServiceList(RB_Product_Service_Extend demodel)
        {
            return product_ServiceRepository.GetList(demodel);
        }


        /// <summary>
        /// 新增修改商品服务
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetProductServiceInfo(RB_Product_Service_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Product_Service.Name),demodel.Name},
                    { nameof(RB_Product_Service.Sort),demodel.Sort},
                    { nameof(RB_Product_Service.Remark),demodel.Remark},
                    { nameof(RB_Product_Service.IsDefault),demodel.IsDefault},
                    { nameof(RB_Product_Service.UpdateDate),demodel.UpdateDate}
                };
                if (demodel.UpdateType == 1)
                { //只更新默认状态
                    var model = product_ServiceRepository.GetEntity(demodel.Id);
                    if (model == null)
                    {
                        return false;
                    }
                    keyValues = new Dictionary<string, object>()
                    {
                        { nameof(RB_Product_Service.IsDefault),model.IsDefault==1?2:1},
                        { nameof(RB_Product_Service.UpdateDate),demodel.UpdateDate}
                    };
                }
                else if (demodel.UpdateType == 2)
                { //只更新排序
                    keyValues = new Dictionary<string, object>()
                    {
                        { nameof(RB_Product_Service.Sort),demodel.Sort},
                        { nameof(RB_Product_Service.UpdateDate),demodel.UpdateDate}
                    };
                }
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Product_Service.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return product_ServiceRepository.Update(keyValues, wheres);
            }
            else
            {
                return product_ServiceRepository.Insert(demodel) > 0;
            }
        }

        /// <summary>
        /// 获取服务详情
        /// </summary>
        /// <param name="serviceId"></param>
        /// <returns></returns>
        public RB_Product_Service_Extend GetProductServiceInfo(int serviceId)
        {
            return product_ServiceRepository.GetEntity(serviceId).RefMapperTo<RB_Product_Service_Extend>();
        }

        /// <summary>
        /// 删除商品服务
        /// </summary>
        /// <param name="serviceId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelProductServiceInfo(int serviceId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Product_Service.Status),1},
                { nameof(RB_Product_Service.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                    FiledName=nameof(RB_Product_Service.Id),
                    FiledValue=serviceId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Product_Service.TenantId),
                    FiledValue=tenantId,
                    OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                    FiledName=nameof(RB_Product_Service.MallBaseId),
                    FiledValue=mallBaseId,
                    OperatorEnum=OperatorEnum.Equal
                },
            };
            return product_ServiceRepository.Update(keyValues, wheres);
        }
        #endregion

        #region 商品管理

        /// <summary>
        /// 获取后台商品分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <param name="IsGetSpec">是否获取规格</param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetProductGoodsPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel, int IsGetSpec = 0)
        {
            var list = goodsRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询分类
                string ids = string.Join(",", list.Select(x => x.Id));
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var olist = goods_OrderRepository.GetGoodsOrderNum(ids);
                //规格列表
                List<RB_Goods_Specification_Extend> SpecificationList = new List<RB_Goods_Specification_Extend>();
                //规格值
                List<RB_Goods_SpecificationValue_Extend> svlist = new List<RB_Goods_SpecificationValue_Extend>();
                //规格值列表
                List<RB_Goods_SpecificationPrice_Extend> SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                if (IsGetSpec == 1)
                {
                    SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }

                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    item.CarouselImageList = new List<RB_ImageCommonModel>();
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                        //轮播图
                        //轮播图
                        foreach (var qitem in CarouselIdList)
                        {
                            item.CarouselImageList.Add(new RB_ImageCommonModel()
                            {
                                Id = 0,
                                Name = "",
                                Path = qitem
                            });
                        }
                    }

                    item.GoodsBuyNum = olist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0;
                    if (IsGetSpec == 1)
                    {
                        item.SpecificationList = SpecificationList?.Where(qitem => qitem.GoodsId == item.Id)?.ToList() ?? new List<RB_Goods_Specification_Extend>();
                        if (item.SpecificationList != null && item.SpecificationList.Count > 0)
                        {
                            foreach (var subItem in item.SpecificationList)
                            {
                                subItem.SpecificationValueList = svlist.Where(x => x.SpecificationId == subItem.Id).ToList();
                            }
                        }
                        var tempPriceList = SpecificationPriceList?.Where(qitem => qitem.GoodsId == item.Id)?.ToList() ?? new List<RB_Goods_SpecificationPrice_Extend>();
                        int SortNum = 1;
                        foreach (var childItem in tempPriceList)
                        {
                            if (!string.IsNullOrEmpty(childItem.SpecificationSort))
                            {
                                var ssarr = childItem.SpecificationSort.Split(':');
                                int Sort = Convert.ToInt32(ssarr[0]);
                                string pic_url = item.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                List<object> AttrList = new List<object>();
                                for (int i = 0; i < ssarr.Length; i++)
                                {
                                    var smodel = item.SpecificationList[i];
                                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                    AttrList.Add(new
                                    {
                                        SName = smodel.Name,
                                        SId = smodel.Id,
                                        SVId = svmodel.Sort,
                                        SVName = svmodel.Name
                                    });
                                }
                                childItem.AttrList = AttrList;
                            }
                            childItem.SortNum = SortNum;
                            SortNum++;
                        }
                        item.SpecificationPriceList = tempPriceList.OrderByDescending(x => x.SortNum).ToList();
                    }
                }
            }
            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_Goods_Extend> GetProductGoodsDialogList_V2(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetProductGoodsDialogList_V2(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询分类
                string ids = string.Join(",", list.Select(x => x.Id));
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    item.CarouselImageList = new List<RB_ImageCommonModel>();
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                        //轮播图
                        //轮播图
                        foreach (var qitem in CarouselIdList)
                        {
                            item.CarouselImageList.Add(new RB_ImageCommonModel()
                            {
                                Id = 0,
                                Name = "",
                                Path = qitem
                            });
                        }
                    }
                }
            }
            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_Goods_Extend> GetProductGoodsDialogList_V3(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetProductGoodsDialogList_V3(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询分类
                string ids = string.Join(",", list.Select(x => x.Id));
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    item.CarouselImageList = new List<RB_ImageCommonModel>();
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                        //轮播图
                        //轮播图
                        foreach (var qitem in CarouselIdList)
                        {
                            item.CarouselImageList.Add(new RB_ImageCommonModel()
                            {
                                Id = 0,
                                Name = "",
                                Path = qitem
                            });
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取后台商品分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <param name="IsGetSpec">是否获取规格</param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetListByGoodsClassify(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel, int IsGetSpec = 0)
        {
            var list = goodsRepository.GetPageList_V2(pageIndex, pageSize, out count, demodel);
            //if (list.Any())
            //{
            //    //查询分类
            //    string ids = string.Join(",", list.Select(x => x.Id));
            //    var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
            //    var olist = goods_OrderRepository.GetGoodsOrderNum(ids);
            //    //规格列表
            //    List<RB_Goods_Specification_Extend> SpecificationList = new List<RB_Goods_Specification_Extend>();
            //    //规格值
            //    List<RB_Goods_SpecificationValue_Extend> svlist = new List<RB_Goods_SpecificationValue_Extend>();
            //    //规格值列表
            //    List<RB_Goods_SpecificationPrice_Extend> SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
            //    if (IsGetSpec == 1)
            //    {
            //        SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
            //        svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
            //        SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
            //    }

            //    foreach (var item in list)
            //    {
            //        item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
            //        //轮播图
            //        item.CoverImage = "";
            //        item.CarouselImageList = new List<RB_ImageCommonModel>();
            //        if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
            //        {
            //            List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
            //            //封面图
            //            item.CoverImage = CarouselIdList[0];
            //            //轮播图
            //            //轮播图
            //            foreach (var qitem in CarouselIdList)
            //            {
            //                item.CarouselImageList.Add(new RB_ImageCommonModel()
            //                {
            //                    Id = 0,
            //                    Name = "",
            //                    Path = qitem
            //                });
            //            }
            //        }

            //        item.GoodsBuyNum = olist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0;
            //        if (IsGetSpec == 1)
            //        {
            //            item.SpecificationList = SpecificationList?.Where(qitem => qitem.GoodsId == item.Id)?.ToList() ?? new List<RB_Goods_Specification_Extend>();
            //            if (item.SpecificationList != null && item.SpecificationList.Count > 0)
            //            {
            //                foreach (var subItem in item.SpecificationList)
            //                {
            //                    subItem.SpecificationValueList = svlist.Where(x => x.SpecificationId == subItem.Id).ToList();
            //                }
            //            }
            //            var tempPriceList = SpecificationPriceList?.Where(qitem => qitem.GoodsId == item.Id)?.ToList() ?? new List<RB_Goods_SpecificationPrice_Extend>();
            //            int SortNum = 1;
            //            foreach (var childItem in tempPriceList)
            //            {
            //                if (!string.IsNullOrEmpty(childItem.SpecificationSort))
            //                {
            //                    var ssarr = childItem.SpecificationSort.Split(':');
            //                    int Sort = Convert.ToInt32(ssarr[0]);
            //                    string pic_url = item.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
            //                    List<object> AttrList = new List<object>();
            //                    for (int i = 0; i < ssarr.Length; i++)
            //                    {
            //                        var smodel = item.SpecificationList[i];
            //                        var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
            //                        AttrList.Add(new
            //                        {
            //                            SName = smodel.Name,
            //                            SId = smodel.Id,
            //                            SVId = svmodel.Sort,
            //                            SVName = svmodel.Name
            //                        });
            //                    }
            //                    childItem.AttrList = AttrList;
            //                }
            //                childItem.SortNum = SortNum;
            //                SortNum++;
            //            }
            //            item.SpecificationPriceList = tempPriceList.OrderByDescending(x => x.SortNum).ToList();
            //        }
            //    }
            //}
            return list;
        }


        /// <summary>
        /// 获取分类=>商品列表
        /// </summary>
        /// <param name="demodel">查询条件</param>
        /// <returns></returns>
        public List<object> GetGoodsListModule(RB_Goods_Extend demodel)
        {
            List<object> resultList = new List<object>();
            List<RB_Product_Category_Extend> categoryList = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId });

            var goodsList = goodsRepository.GetList(demodel);
            if (categoryList != null && categoryList.Count > 0)
            {
                var firstCategoryList = categoryList.Where(qitem => qitem.Tier == 1).ToList();
                foreach (var firstItem in firstCategoryList)
                {
                    var rootGoodsList = goodsList.Where(qitem => qitem.CategoryId == firstItem.Id).ToList();
                    var secondCategoryList = categoryList.Where(qitem => qitem.Tier == 2 && qitem.ParentId == firstItem.Id).ToList();
                    List<object> secondResultList = new List<object>();
                    foreach (var secondItem in secondCategoryList)
                    {
                        var secondGoodList = goodsList.Where(qitem => qitem.CategoryId == secondItem.Id).ToList();
                        List<object> thirdResultList = new List<object>();
                        var thirdCategoryList = categoryList.Where(qitem => qitem.Tier == 3 && qitem.ParentId == secondItem.Id).ToList();
                        foreach (var thirdItem in thirdCategoryList)
                        {
                            var thirdGoodList = goodsList.Where(qitem => qitem.CategoryId == thirdItem.Id).ToList();
                            thirdResultList.Add(new
                            {
                                PageId = thirdItem.Id + 100000,
                                PageName = thirdItem.Name,
                                PageUrl = "/pages/goods/list?CategoryIds=" + thirdItem.Id,
                                PageType = Common.Enum.MallBase.PageTypeEnum.DiyPage,
                                IsParameter = 0,
                                TipText = "",
                                SelfPageName = thirdItem.Name,
                                ParameterValue = "",
                                SubMenuList = thirdGoodList.Select(qitem => new
                                {
                                    PageId = qitem.Id + 100000,
                                    PageName = qitem.Name,
                                    PageUrl = "/pages/goods/goods?id=" + qitem.Id,
                                    PageType = Common.Enum.MallBase.PageTypeEnum.DiyPage,
                                    IsParameter = 0,
                                    TipText = "",
                                    SelfPageName = qitem.Name,
                                    ParameterValue = "",
                                })
                            });
                        }
                        if (secondGoodList != null && secondGoodList.Count > 0)
                        {
                            thirdResultList.AddRange(secondGoodList.Select(qitem => new
                            {
                                PageId = qitem.Id + 100000,
                                PageName = qitem.Name,
                                PageUrl = "/pages/goods/goods?id=" + qitem.Id,
                                PageType = Common.Enum.MallBase.PageTypeEnum.DiyPage,
                                IsParameter = 0,
                                TipText = "",
                                SelfPageName = qitem.Name,
                                ParameterValue = "",
                            }));
                        }
                        secondResultList.Add(new
                        {
                            PageId = secondItem.Id + 100000,
                            PageName = secondItem.Name,
                            PageUrl = "/pages/goods/list?CategoryIds=" + secondItem.Id,
                            PageType = Common.Enum.MallBase.PageTypeEnum.DiyPage,
                            IsParameter = 0,
                            TipText = "",
                            SelfPageName = secondItem.Name,
                            ParameterValue = "",
                            SubMenuList = thirdResultList,
                        });
                    }

                    if (rootGoodsList != null && rootGoodsList.Count > 0)
                    {
                        secondResultList.AddRange(rootGoodsList.Select(qitem => new
                        {
                            PageId = qitem.Id + 100000,
                            PageName = qitem.Name,
                            PageUrl = "/pages/goods/goods?id=" + qitem.Id,
                            PageType = Common.Enum.MallBase.PageTypeEnum.DiyPage,
                            IsParameter = 0,
                            TipText = "",
                            SelfPageName = qitem.Name,
                            ParameterValue = "",
                        }));
                    }
                    resultList.Add(new
                    {
                        PageId = firstItem.Id + 100000,
                        PageName = firstItem.Name,
                        PageUrl = "/pages/cats/cats?cat_type=1&cat_id=" + firstItem.Id,
                        PageType = Common.Enum.MallBase.PageTypeEnum.DiyPage,
                        IsParameter = 0,
                        TipText = "",
                        SelfPageName = firstItem.Name,
                        ParameterValue = "",
                        SubMenuList = secondResultList,
                    });
                }
            }
            return resultList;
        }


        /// <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> GetProductGoodsPageList_V2(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel, int SmallShopsId = 0)
        {
            if (!string.IsNullOrEmpty(demodel.CategoryIds) && !demodel.CategoryIds.Contains(','))
            {
                //获取该分类下所有子集分类
                var cmodel = product_CategoryRepository.GetEntity(demodel.CategoryIds);
                if (cmodel != null)
                {
                    List<int> AllClist = new List<int>();
                    AllClist.Add(cmodel.Id);
                    var clist = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId, RootId = cmodel.RootId });
                    var OneList = clist.Where(x => x.ParentId == cmodel.Id).ToList();
                    foreach (var item in OneList)
                    {
                        AllClist.Add(item.Id);
                        var TwoList = clist.Where(x => x.ParentId == item.Id).ToList();
                        if (TwoList.Any())
                        {
                            AllClist.AddRange(TwoList.Select(x => x.Id).Distinct().ToList());
                        }
                    }
                    if (AllClist.Any())
                    {
                        demodel.CategoryIds = string.Join(",", AllClist);
                    }
                }
            }
            var list = goodsRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                RB_SmallShops_Info_Extend smallModel = new RB_SmallShops_Info_Extend();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                List<RB_Goods_SpecificationPrice_Extend> spriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                //商品Id
                string ids = string.Join(",", list.Select(x => x.Id));
                if (SmallShopsId > 0)
                {
                    smallModel = smallShops_InfoRepository.GetEntity<RB_SmallShops_Info_Extend>(SmallShopsId);
                    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = SmallShopsId, GoodsIds = ids });
                    spriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = ids });
                }
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var olist = goods_OrderRepository.GetGoodsOrderNum(ids);
                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                        //轮播图
                    }

                    item.GoodsBuyNum = olist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0;
                    #region 微店价格
                    if (SmallShopsId > 0)
                    {
                        if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                        {
                            var spList = spriceList.Where(x => x.GoodsId == item.Id).ToList();
                            if (spList.Any())
                            {
                                foreach (var qitem in spList)
                                {
                                    var sspModel = smallPList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == qitem.SpecificationSort).FirstOrDefault();
                                    if (sspModel != null)
                                    {
                                        //单商品设置的
                                        if (sspModel.PriceType == 1)
                                        {
                                            qitem.SellingPrice = (qitem.SellingPrice ?? 0) + Math.Ceiling((qitem.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            qitem.SellingPrice = (qitem.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                qitem.SellingPrice = (qitem.SellingPrice ?? 0) + Math.Ceiling((qitem.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                qitem.SellingPrice = (qitem.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                                item.SellingPrice = spList.Min(x => x.SellingPrice ?? 0);
                                decimal MaxPrice = spList.Max(x => x.SellingPrice ?? 0);
                                MaxPrice += Math.Ceiling(MaxPrice / 10);
                                if (MaxPrice > item.OriginalPrice)
                                {
                                    item.OriginalPrice = MaxPrice;
                                }
                            }
                            else
                            {
                                var sspModel = smallPList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == "").FirstOrDefault();
                                if (sspModel != null)
                                {
                                    //单商品设置的
                                    if (sspModel.PriceType == 1)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                        item.OriginalPrice = (item.OriginalPrice ?? 0) + Math.Ceiling((item.OriginalPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                    }
                                    else if (sspModel.PriceType == 2)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                        item.OriginalPrice = (item.OriginalPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                    }
                                }
                                else
                                {
                                    if ((smallModel.UpPrice ?? 0) > 0)
                                    {
                                        if (smallModel.PriceType == 1)
                                        {
                                            item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                            item.OriginalPrice = (item.OriginalPrice ?? 0) + Math.Ceiling((item.OriginalPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (smallModel.PriceType == 2)
                                        {
                                            item.SellingPrice = (item.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                            item.OriginalPrice = (item.OriginalPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
            }
            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_Goods_Extend> GetProductGoodsProxyPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询分类
                string ids = string.Join(",", list.Select(x => x.Id));
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var olist = goods_OrderRepository.GetGoodsOrderNum(ids);
                //查询商品是否已代理
                var ProxyList = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { GoodsIds = ids, ProxyTenantId = demodel.TenantId, ProxyMallBaseId = demodel.MallBaseId });
                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }

                    item.GoodsBuyNum = olist.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.OrderNum ?? 0;
                    item.IsProcurement = 2;
                    item.ProcurementGoodsId = 0;
                    if (ProxyList.Where(x => x.GoodsId == item.Id).Any())
                    {
                        item.IsProcurement = 1;
                        item.ProcurementGoodsId = ProxyList.Where(x => x.GoodsId == item.Id).FirstOrDefault()?.GoodsId ?? 0;
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取后台商品列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetProductGoodsList(RB_Goods_Extend demodel, int SmallShopsId = 0)
        {
            var list = goodsRepository.GetList(demodel);
            if (list.Any())
            {
                //查询分类
                string ids = string.Join(",", list.Select(x => x.Id));
                RB_SmallShops_Info_Extend smallModel = new RB_SmallShops_Info_Extend();
                List<RB_SmallShops_Price_Extend> smallPList = new List<RB_SmallShops_Price_Extend>();
                List<RB_Goods_SpecificationPrice_Extend> spriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                if (SmallShopsId > 0)
                {
                    smallModel = smallShops_InfoRepository.GetEntity<RB_SmallShops_Info_Extend>(SmallShopsId);
                    smallPList = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = SmallShopsId, GoodsIds = ids });
                    spriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = ids });
                }
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in list)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                        //轮播图
                    }

                    #region 微店价格
                    if (SmallShopsId > 0)
                    {
                        if ((smallModel.UpPrice ?? 0) > 0 || smallPList.Where(x => x.GoodsId == item.Id && x.UpPrice > 0).Any())
                        {
                            var spList = spriceList.Where(x => x.GoodsId == item.Id).ToList();
                            if (spList.Any())
                            {
                                foreach (var qitem in spList)
                                {
                                    var sspModel = smallPList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == qitem.SpecificationSort).FirstOrDefault();
                                    if (sspModel != null)
                                    {
                                        //单商品设置的
                                        if (sspModel.PriceType == 1)
                                        {
                                            qitem.SellingPrice = (qitem.SellingPrice ?? 0) + Math.Ceiling((qitem.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (sspModel.PriceType == 2)
                                        {
                                            qitem.SellingPrice = (qitem.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                        }
                                    }
                                    else
                                    {
                                        if ((smallModel.UpPrice ?? 0) > 0)
                                        {
                                            if (smallModel.PriceType == 1)
                                            {
                                                qitem.SellingPrice = (qitem.SellingPrice ?? 0) + Math.Ceiling((qitem.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                            }
                                            else if (smallModel.PriceType == 2)
                                            {
                                                qitem.SellingPrice = (qitem.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                            }
                                        }
                                    }
                                }
                                item.SellingPrice = spList.Min(x => x.SellingPrice ?? 0);
                                decimal MaxPrice = spList.Max(x => x.SellingPrice ?? 0);
                                MaxPrice += Math.Ceiling(MaxPrice / 10);
                                if (MaxPrice > item.OriginalPrice)
                                {
                                    item.OriginalPrice = MaxPrice;
                                }
                            }
                            else
                            {
                                var sspModel = smallPList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == "").FirstOrDefault();
                                if (sspModel != null)
                                {
                                    //单商品设置的
                                    if (sspModel.PriceType == 1)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                        item.OriginalPrice = (item.OriginalPrice ?? 0) + Math.Ceiling((item.OriginalPrice ?? 0) * (sspModel.UpPrice ?? 0) / 100);
                                    }
                                    else if (sspModel.PriceType == 2)
                                    {
                                        item.SellingPrice = (item.SellingPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                        item.OriginalPrice = (item.OriginalPrice ?? 0) + (sspModel.UpPrice ?? 0);
                                    }
                                }
                                else
                                {
                                    if ((smallModel.UpPrice ?? 0) > 0)
                                    {
                                        if (smallModel.PriceType == 1)
                                        {
                                            item.SellingPrice = (item.SellingPrice ?? 0) + Math.Ceiling((item.SellingPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                            item.OriginalPrice = (item.OriginalPrice ?? 0) + Math.Ceiling((item.OriginalPrice ?? 0) * (smallModel.UpPrice ?? 0) / 100);
                                        }
                                        else if (smallModel.PriceType == 2)
                                        {
                                            item.SellingPrice = (item.SellingPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                            item.OriginalPrice = (item.OriginalPrice ?? 0) + (smallModel.UpPrice ?? 0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
            }
            return list;
        }

        /// <summary>
        /// 获取后台商品列表(导出专用)
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Extend> GetProductGoodsListForExcel(RB_Goods_Extend demodel)
        {
            var list = goodsRepository.GetList(demodel);
            if (list.Any())
            {
                var SpecificationList = new List<RB_Goods_Specification_Extend>();
                var SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                if (list.Where(x => x.IsCustomSpecification == 1).Any())
                {
                    string goodsIds = string.Join(",", list.Where(x => x.IsCustomSpecification == 1).Select(x => x.Id));
                    SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    if (SpecificationList.Any())
                    {
                        var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        foreach (var item in svlist)
                        {
                            item.ImagePath = item.Image;
                        }
                        foreach (var item in SpecificationList)
                        {
                            item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                        }
                    }
                    SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                //区域
                var AreaList = new List<RB_Goods_Area_Extend>();
                if (list.Where(x => x.IsAreaBuy == 1).Any())
                {
                    string goodssid = string.Join(",", list.Where(x => x.IsAreaBuy == 1).Select(x => x.Id));
                    AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsIds = goodssid, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                }
                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];
                    }

                    item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                    item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                    if (item.IsCustomSpecification == 1)
                    {
                        item.SpecificationList = SpecificationList.Where(x => x.GoodsId == item.Id).ToList();
                        item.SpecificationPriceList = SpecificationPriceList.Where(x => x.GoodsId == item.Id).ToList();
                    }
                    item.AreaList = new List<RB_Goods_Area_Extend>();
                    if (item.IsAreaBuy == 1)
                    {
                        item.AreaList = AreaList.Where(x => x.GoodsId == item.Id).ToList();
                    }

                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改商品信息
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetProductGoodsInfo(RB_Goods_Extend demodel)
        {
            var goodsModel = new RB_Goods();
            if (demodel.Id > 0)
            {
                goodsModel = goodsRepository.GetEntity(demodel.Id);
                if (goodsModel == null)
                {
                    return false;
                }
                if (goodsModel.IsProcurement == 1)
                {
                    //是采购的商品
                    if (demodel.CostPrice != goodsModel.CostPrice)
                    {
                        return false;
                    }
                    //验证 规格
                    if (demodel.IsCustomSpecification != goodsModel.IsCustomSpecification)
                    {
                        return false;
                    }
                    if (goodsModel.IsCustomSpecification == 1)
                    {
                        var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        if (splist.Count() != demodel.SpecificationPriceList.Count() || splist.Count() != demodel.SpecificationPriceList.Where(x => splist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count())
                        {
                            return false;
                        }
                    }
                }
            }
            try
            {
                if (demodel.Id > 0)
                {
                    //修改
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Goods.Name),demodel.Name},
                        { nameof(RB_Goods.CarouselImage),demodel.CarouselImage},
                        { nameof(RB_Goods.VideoAddress),demodel.VideoAddress},
                        { nameof(RB_Goods.CustomShareTitles),demodel.CustomShareTitles},
                        { nameof(RB_Goods.CustomShareImage),demodel.CustomShareImage},
                        { nameof(RB_Goods.GoodsStatus),demodel.GoodsStatus},
                        { nameof(RB_Goods.InventoryNum),demodel.InventoryNum},
                        { nameof(RB_Goods.DefaultSpecificationName),demodel.DefaultSpecificationName},
                        { nameof(RB_Goods.IsCustomSpecification),demodel.IsCustomSpecification},
                        { nameof(RB_Goods.Sort),demodel.Sort},
                        { nameof(RB_Goods.SellingPrice),demodel.SellingPrice},
                        { nameof(RB_Goods.OriginalPrice),demodel.OriginalPrice},
                        { nameof(RB_Goods.Unit),demodel.Unit},
                        { nameof(RB_Goods.CostPrice),demodel.CostPrice},
                        { nameof(RB_Goods.IsGoodsNegotiable),demodel.IsGoodsNegotiable},
                        { nameof(RB_Goods.SalesNum),demodel.SalesNum},
                        { nameof(RB_Goods.GoodsNumbers),demodel.GoodsNumbers},
                        { nameof(RB_Goods.GoodsWeight),demodel.GoodsWeight},
                        { nameof(RB_Goods.IsDefaultService),demodel.IsDefaultService},
                        { nameof(RB_Goods.GoodsService),demodel.GoodsService},
                        { nameof(RB_Goods.FreightId),demodel.FreightId},
                        { nameof(RB_Goods.FormsId),demodel.FormsId},
                        { nameof(RB_Goods.LimitBuyGoodsNum),demodel.LimitBuyGoodsNum},
                        { nameof(RB_Goods.LimitBuyOrderNum),demodel.LimitBuyOrderNum},
                        { nameof(RB_Goods.FullNumPinkage),demodel.FullNumPinkage},
                        { nameof(RB_Goods.FullMoneyPinkage),demodel.FullMoneyPinkage},
                        { nameof(RB_Goods.IsAreaBuy),demodel.IsAreaBuy},
                        { nameof(RB_Goods.IntegralPresent),demodel.IntegralPresent},
                        { nameof(RB_Goods.IntegralPresentType),demodel.IntegralPresentType},
                        { nameof(RB_Goods.PointsDeduction),demodel.PointsDeduction},
                        { nameof(RB_Goods.PointsDeductionType),demodel.PointsDeductionType},
                        { nameof(RB_Goods.IsMultipleDeduction),demodel.IsMultipleDeduction},
                        { nameof(RB_Goods.GoodsDetails),demodel.GoodsDetails},
                        { nameof(RB_Goods.UpdateDate),demodel.UpdateDate},
                        { nameof(RB_Goods.SeparateDistribution),demodel.SeparateDistribution},
                        { nameof(RB_Goods.SeparateDistributionType),demodel.SeparateDistributionType},
                        { nameof(RB_Goods.SeparateDistributionMoneyType),demodel.SeparateDistributionMoneyType},
                        { nameof(RB_Goods.EnjoyMember),demodel.EnjoyMember},
                        { nameof(RB_Goods.SeparateSetMember),demodel.SeparateSetMember},
                        { nameof(RB_Goods.IsQuickBuy),demodel.IsQuickBuy},
                        { nameof(RB_Goods.SupplierId),demodel.SupplierId},
                        { nameof(RB_Goods.IsProxy),demodel.IsProxy},
                        { nameof(RB_Goods.ProxyType),demodel.ProxyType},
                        { nameof(RB_Goods.ProxyRises),demodel.ProxyRises},
                        { nameof(RB_Goods.ProxyMoney),demodel.ProxyMoney},
                        { nameof(RB_Goods.Commission),demodel.Commission},
                        { nameof(RB_Goods.PresentFXGrade),demodel.PresentFXGrade},
                        { nameof(RB_Goods.PresentFXMonth),demodel.PresentFXMonth},
                        { nameof(RB_Goods.Advertising),demodel.Advertising},
                        { nameof(RB_Goods.SubName),demodel.SubName},
                        { nameof(RB_Goods.MarketingLogo),demodel.MarketingLogo},
                        { nameof(RB_Goods.IsLiveGoods),demodel.IsLiveGoods},
                        { nameof(RB_Goods.ShelvesDate),demodel.ShelvesDate },
                        { nameof(RB_Goods.DownDate),demodel.DownDate },
                        { nameof(RB_Goods.SendArea),demodel.SendArea },
                        { nameof(RB_Goods.VideoType),demodel.VideoType },
                        { nameof(RB_Goods.IntegralComment),demodel.IntegralComment },
                        { nameof(RB_Goods.IntegralCommentType),demodel.IntegralCommentType },
                        { nameof(RB_Goods.Remark),demodel.Remark },
                        { nameof(RB_Goods.GoodsPageType),demodel.GoodsPageType },
                    };
                    if (goodsModel.IsProcurement == 1)
                    {
                        //采购商品可修改
                        keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Goods.Name),demodel.Name},
                        { nameof(RB_Goods.CarouselImage),demodel.CarouselImage},
                        { nameof(RB_Goods.VideoAddress),demodel.VideoAddress},
                        { nameof(RB_Goods.CustomShareTitles),demodel.CustomShareTitles},
                        { nameof(RB_Goods.CustomShareImage),demodel.CustomShareImage},
                        { nameof(RB_Goods.Sort),demodel.Sort},
                        { nameof(RB_Goods.SellingPrice),demodel.SellingPrice},
                        { nameof(RB_Goods.OriginalPrice),demodel.OriginalPrice},
                        { nameof(RB_Goods.Unit),demodel.Unit},
                        { nameof(RB_Goods.SalesNum),demodel.SalesNum},
                        { nameof(RB_Goods.IsDefaultService),demodel.IsDefaultService},
                        { nameof(RB_Goods.GoodsService),demodel.GoodsService},
                        { nameof(RB_Goods.FreightId),demodel.FreightId},
                        { nameof(RB_Goods.FormsId),demodel.FormsId},
                        { nameof(RB_Goods.LimitBuyGoodsNum),demodel.LimitBuyGoodsNum},
                        { nameof(RB_Goods.LimitBuyOrderNum),demodel.LimitBuyOrderNum},
                        { nameof(RB_Goods.FullNumPinkage),demodel.FullNumPinkage},
                        { nameof(RB_Goods.FullMoneyPinkage),demodel.FullMoneyPinkage},
                        { nameof(RB_Goods.IsAreaBuy),demodel.IsAreaBuy},
                        { nameof(RB_Goods.IntegralPresent),demodel.IntegralPresent},
                        { nameof(RB_Goods.IntegralPresentType),demodel.IntegralPresentType},
                        { nameof(RB_Goods.PointsDeduction),demodel.PointsDeduction},
                        { nameof(RB_Goods.PointsDeductionType),demodel.PointsDeductionType},
                        { nameof(RB_Goods.IsMultipleDeduction),demodel.IsMultipleDeduction},
                        { nameof(RB_Goods.GoodsDetails),demodel.GoodsDetails},
                        { nameof(RB_Goods.UpdateDate),demodel.UpdateDate},
                        { nameof(RB_Goods.SeparateDistribution),demodel.SeparateDistribution},
                        { nameof(RB_Goods.SeparateDistributionType),demodel.SeparateDistributionType},
                        { nameof(RB_Goods.SeparateDistributionMoneyType),demodel.SeparateDistributionMoneyType},
                        { nameof(RB_Goods.EnjoyMember),demodel.EnjoyMember},
                        { nameof(RB_Goods.SeparateSetMember),demodel.SeparateSetMember},
                        { nameof(RB_Goods.IsQuickBuy),demodel.IsQuickBuy},

                    };
                    }
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods.Id),
                              FiledValue=demodel.Id,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods.TenantId),
                              FiledValue=demodel.TenantId,
                               OperatorEnum=OperatorEnum.Equal
                        },
                        new WhereHelper(){
                             FiledName=nameof(RB_Goods.MallBaseId),
                              FiledValue=demodel.MallBaseId,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    bool flag = goodsRepository.Update(keyValues, wheres);
                    if (flag)
                    {
                        #region 修改分类
                        var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        var insertList = demodel.CategoryList.Where(x => !clist.Select(y => y.CategoryId).Contains(x.CategoryId)).ToList();
                        //var updateList = clist.Where(x => demodel.CategoryList.Select(y => y.CategoryId).Contains(x.CategoryId)).ToList();
                        var deleteList = clist.Where(x => !demodel.CategoryList.Select(y => y.CategoryId).Contains(x.CategoryId)).ToList();
                        foreach (var item in insertList)
                        {
                            goods_CategoryRepository.Insert(new RB_Goods_Category()
                            {
                                CategoryId = item.CategoryId,
                                CreateDate = demodel.CreateDate,
                                GoodsId = demodel.Id,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                Status = 0,
                                TenantId = demodel.TenantId
                            });
                        }
                        foreach (var item in deleteList)
                        {
                            goods_CategoryRepository.Delete(item.Id);
                        }
                        #endregion
                        #region 修改规格
                        if (demodel.IsCustomSpecification == 1)
                        {
                            if (goodsModel.IsProcurement != 1)
                            {
                                var slist = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                if (slist.Count() != demodel.SpecificationList.Count() || slist.Count() != demodel.SpecificationList.Where(x => x.Id > 0).Count())
                                {
                                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                    var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                    //删除后新增
                                    goods_SpecificationRepository.DeleteBatch(slist);
                                    goods_SpecificationValueRepository.DeleteBatch(svlist);
                                    goods_SpecificationPriceRepository.DeleteBatch(splist);
                                    foreach (var item in demodel.SpecificationList)
                                    {
                                        int sid = goods_SpecificationRepository.Insert(new RB_Goods_Specification()
                                        {
                                            CreateDate = demodel.CreateDate,
                                            EnabledImage = item.EnabledImage,
                                            GoodsId = demodel.Id,
                                            Id = 0,
                                            MallBaseId = demodel.MallBaseId,
                                            Name = item.Name,
                                            Sort = item.Sort,
                                            Status = 0,
                                            TenantId = demodel.TenantId
                                        });
                                        if (sid > 0)
                                        {
                                            foreach (var qitem in item.SpecificationValueList)
                                            {
                                                goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                                                {
                                                    CreateDate = demodel.CreateDate,
                                                    GoodsId = demodel.Id,
                                                    Id = 0,
                                                    Image = qitem.Image,
                                                    MallBaseId = demodel.MallBaseId,
                                                    Name = qitem.Name,
                                                    Sort = qitem.Sort,
                                                    Status = 0,
                                                    TenantId = demodel.TenantId,
                                                    SpecificationId = sid
                                                });
                                            }
                                        }
                                    }
                                    foreach (var item in demodel.SpecificationPriceList)
                                    {
                                        goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                                        {
                                            CreateDate = demodel.CreateDate,
                                            GoodsId = demodel.Id,
                                            Id = 0,
                                            GoodsNumbers = item.GoodsNumbers,
                                            GoodsWeight = item.GoodsWeight,
                                            InventoryNum = item.InventoryNum,
                                            MallBaseId = demodel.MallBaseId,
                                            SellingPrice = item.SellingPrice,
                                            SpecificationSort = item.SpecificationSort,
                                            Status = 0,
                                            TenantId = demodel.TenantId,
                                            UpdateDate = demodel.UpdateDate,
                                            Commission = item.Commission,
                                            CostMoney = item.CostMoney
                                        });
                                    }
                                }
                                else
                                {
                                    //更新
                                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                    var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                    foreach (var item in slist)
                                    {
                                        var supmodel = demodel.SpecificationList.Where(x => x.Id == item.Id).FirstOrDefault();
                                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>()
                                        {
                                            { nameof(RB_Goods_Specification.EnabledImage),supmodel.EnabledImage},
                                            { nameof(RB_Goods_Specification.Name),supmodel.Name},
                                            { nameof(RB_Goods_Specification.Sort),supmodel.Sort}
                                        };
                                        List<WhereHelper> wheres1 = new List<WhereHelper>()
                                        {
                                            new WhereHelper()
                                            {
                                                 FiledName=nameof(RB_Goods_Specification.Id),
                                                 FiledValue=item.Id,
                                                 OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        bool flag1 = goods_SpecificationRepository.Update(keyValues1, wheres1);
                                        if (flag1)
                                        {
                                            var sv2list = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                                            if (sv2list.Count() != supmodel.SpecificationValueList.Count() || sv2list.Count() != supmodel.SpecificationValueList.Where(x => x.Id > 0).Count())
                                            {
                                                goods_SpecificationValueRepository.DeleteBatch(sv2list);
                                                foreach (var qitem in supmodel.SpecificationValueList)
                                                {
                                                    goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                                                    {
                                                        CreateDate = demodel.CreateDate,
                                                        GoodsId = demodel.Id,
                                                        Id = 0,
                                                        Image = qitem.Image,
                                                        MallBaseId = demodel.MallBaseId,
                                                        Name = qitem.Name,
                                                        Sort = qitem.Sort,
                                                        Status = 0,
                                                        TenantId = demodel.TenantId,
                                                        SpecificationId = item.Id
                                                    });
                                                }
                                            }
                                            else
                                            {
                                                foreach (var qitem in sv2list)
                                                {
                                                    var supModel1 = supmodel.SpecificationValueList.Where(x => x.Id == qitem.Id).FirstOrDefault();
                                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                    { nameof(RB_Goods_SpecificationValue.Image),supModel1.Image},
                                                    { nameof(RB_Goods_SpecificationValue.Name),supModel1.Name},
                                                    { nameof(RB_Goods_SpecificationValue.Sort),supModel1.Sort}
                                                };
                                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                         FiledName=nameof(RB_Goods_Specification.Id),
                                                          FiledValue=qitem.Id,
                                                           OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                                    goods_SpecificationValueRepository.Update(keyValues2, wheres2);
                                                }
                                            }
                                        }
                                    }
                                    //价格新增/更新
                                    if (splist.Count() != demodel.SpecificationPriceList.Count() || splist.Count() != demodel.SpecificationPriceList.Where(x => splist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count())
                                    {
                                        goods_SpecificationPriceRepository.DeleteBatch(splist);
                                        foreach (var item in demodel.SpecificationPriceList)
                                        {
                                            goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                                            {
                                                CreateDate = demodel.CreateDate,
                                                GoodsId = demodel.Id,
                                                Id = 0,
                                                GoodsNumbers = item.GoodsNumbers,
                                                GoodsWeight = item.GoodsWeight,
                                                InventoryNum = item.InventoryNum,
                                                MallBaseId = demodel.MallBaseId,
                                                SellingPrice = item.SellingPrice,
                                                SpecificationSort = item.SpecificationSort,
                                                Status = 0,
                                                TenantId = demodel.TenantId,
                                                UpdateDate = demodel.UpdateDate,
                                                Commission = item.Commission,
                                                CostMoney = item.CostMoney
                                            });
                                        }
                                    }
                                    else
                                    {
                                        foreach (var item in splist)
                                        {
                                            var pupmodel = demodel.SpecificationPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                                            if (item.Commission != pupmodel.Commission || item.CostMoney != pupmodel.CostMoney || item.SellingPrice != pupmodel.SellingPrice || item.InventoryNum != pupmodel.InventoryNum || item.GoodsNumbers != pupmodel.GoodsNumbers || item.GoodsWeight != pupmodel.GoodsWeight)
                                            {
                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                { nameof(RB_Goods_SpecificationPrice.SellingPrice),pupmodel.SellingPrice},
                                                { nameof(RB_Goods_SpecificationPrice.InventoryNum),pupmodel.InventoryNum},
                                                { nameof(RB_Goods_SpecificationPrice.GoodsWeight),pupmodel.GoodsWeight},
                                                { nameof(RB_Goods_SpecificationPrice.GoodsNumbers),pupmodel.GoodsNumbers},
                                                { nameof(RB_Goods_SpecificationPrice.Commission),pupmodel.Commission},
                                                { nameof(RB_Goods_SpecificationPrice.CostMoney),pupmodel.CostMoney},
                                            };
                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                new WhereHelper(){
                                                     FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                                      FiledValue=item.Id,
                                                       OperatorEnum=OperatorEnum.Equal
                                                }
                                            };
                                                goods_SpecificationPriceRepository.Update(keyValues1, wheres1);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //只更新规格价格
                                var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                                //价格新增/更新
                                if (splist.Count() != demodel.SpecificationPriceList.Count() || splist.Count() != demodel.SpecificationPriceList.Where(x => splist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count())
                                {
                                    goods_SpecificationPriceRepository.DeleteBatch(splist);
                                    foreach (var item in demodel.SpecificationPriceList)
                                    {
                                        goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                                        {
                                            CreateDate = demodel.CreateDate,
                                            GoodsId = demodel.Id,
                                            Id = 0,
                                            GoodsNumbers = item.GoodsNumbers,
                                            GoodsWeight = item.GoodsWeight,
                                            InventoryNum = item.InventoryNum,
                                            MallBaseId = demodel.MallBaseId,
                                            SellingPrice = item.SellingPrice,
                                            SpecificationSort = item.SpecificationSort,
                                            Status = 0,
                                            TenantId = demodel.TenantId,
                                            UpdateDate = demodel.UpdateDate,
                                            Commission = item.Commission,
                                            CostMoney = item.CostMoney
                                        });
                                    }
                                }
                                else
                                {
                                    foreach (var item in splist)
                                    {
                                        var pupmodel = demodel.SpecificationPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                                        if (item.Commission != pupmodel.Commission || item.CostMoney != pupmodel.CostMoney || item.SellingPrice != pupmodel.SellingPrice || item.InventoryNum != pupmodel.InventoryNum || item.GoodsNumbers != pupmodel.GoodsNumbers || item.GoodsWeight != pupmodel.GoodsWeight)
                                        {
                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                { nameof(RB_Goods_SpecificationPrice.SellingPrice),pupmodel.SellingPrice},
                                                { nameof(RB_Goods_SpecificationPrice.InventoryNum),pupmodel.InventoryNum},
                                                { nameof(RB_Goods_SpecificationPrice.GoodsWeight),pupmodel.GoodsWeight},
                                                { nameof(RB_Goods_SpecificationPrice.GoodsNumbers),pupmodel.GoodsNumbers},
                                                 { nameof(RB_Goods_SpecificationPrice.Commission),pupmodel.Commission},
                                                { nameof(RB_Goods_SpecificationPrice.CostMoney),pupmodel.CostMoney},
                                            };
                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                new WhereHelper(){
                                                     FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                                      FiledValue=item.Id,
                                                       OperatorEnum=OperatorEnum.Equal
                                                }
                                            };
                                            goods_SpecificationPriceRepository.Update(keyValues1, wheres1);
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                        #region 修改区域
                        var alist = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                        var insertList1 = demodel.AreaList.Where(x => !alist.Select(y => y.AreaId).Contains(x.AreaId)).ToList();
                        var deleteList1 = alist.Where(x => !demodel.AreaList.Select(y => y.AreaId).Contains(x.AreaId)).ToList();
                        foreach (var item in insertList1)
                        {
                            goods_AreaRepository.Insert(new RB_Goods_Area()
                            {
                                AreaId = item.AreaId,
                                AreaType = item.AreaType,
                                CreateDate = demodel.CreateDate,
                                GoodsId = demodel.Id,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                Status = 0,
                                TenantId = demodel.TenantId
                            });
                        }
                        foreach (var item in deleteList1)
                        {
                            goods_AreaRepository.Delete(item.Id);
                        }


                        #endregion
                        //修改卡卷
                        #region 修改分销佣金
                        if (demodel.SeparateDistribution == 1)
                        {
                            //价格新增/更新
                            var dclist = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                            if (dclist.Count() != demodel.DistributionCommissionList.Count()
                                || dclist.Count() != demodel.DistributionCommissionList.Where(x => dclist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count()
                                || dclist.Select(x => x.DistributorGrade).Distinct().Count() != demodel.DistributionCommissionList.Select(x => x.DistributorGrade).Distinct().Count()
                                || dclist.Select(x => x.DistributorGrade).Distinct().Count() != dclist.Select(x => x.DistributorGrade).Distinct().Where(x => demodel.DistributionCommissionList.Select(y => y.DistributorGrade).Distinct().Contains(x)).Count())
                            {
                                goods_DistributionCommissionRepository.DeleteBatch(dclist);
                                foreach (var item in demodel.DistributionCommissionList)
                                {
                                    goods_DistributionCommissionRepository.Insert(new RB_Goods_DistributionCommission()
                                    {
                                        CreateDate = demodel.CreateDate,
                                        GoodsId = demodel.Id,
                                        Id = 0,
                                        DistributorGrade = item.DistributorGrade,
                                        OneCommission = item.OneCommission,
                                        ThreeCommission = item.ThreeCommission,
                                        TwoCommission = item.TwoCommission,
                                        MallBaseId = demodel.MallBaseId,
                                        SpecificationSort = item.SpecificationSort,
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        UpdateDate = demodel.UpdateDate
                                    });
                                }
                            }
                            else
                            {

                                foreach (var item in dclist)
                                {
                                    var pupmodel = demodel.DistributionCommissionList.Where(x => x.SpecificationSort == item.SpecificationSort && x.DistributorGrade == item.DistributorGrade).FirstOrDefault();
                                    if (item.OneCommission != pupmodel.OneCommission || item.TwoCommission != pupmodel.TwoCommission || item.ThreeCommission != pupmodel.ThreeCommission)
                                    {
                                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_DistributionCommission.OneCommission),pupmodel.OneCommission},
                                            { nameof(RB_Goods_DistributionCommission.TwoCommission),pupmodel.TwoCommission},
                                            { nameof(RB_Goods_DistributionCommission.ThreeCommission),pupmodel.ThreeCommission}
                                        };
                                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_Goods_DistributionCommission.Id),
                                                    FiledValue=item.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        goods_DistributionCommissionRepository.Update(keyValues1, wheres1);
                                    }
                                }
                            }
                        }
                        #endregion
                        #region 修改会员价格
                        if (demodel.EnjoyMember == 1 && demodel.SeparateSetMember == 1)
                        {
                            var mplist = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsId = demodel.Id, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                            if (mplist.Count() != demodel.MemberPriceList.Count()
                                || mplist.Count() != demodel.MemberPriceList.Where(x => mplist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count()
                                || mplist.Select(x => x.MemberGrade).Distinct().Count() != demodel.MemberPriceList.Select(x => x.MemberGrade).Distinct().Count()
                                || mplist.Select(x => x.MemberGrade).Distinct().Count() != mplist.Select(x => x.MemberGrade).Distinct().Where(x => demodel.MemberPriceList.Select(y => y.MemberGrade).Distinct().Contains(x)).Count())
                            {
                                goods_MemberPriceRepository.DeleteBatch(mplist);
                                foreach (var item in demodel.MemberPriceList)
                                {
                                    goods_MemberPriceRepository.Insert(new RB_Goods_MemberPrice()
                                    {
                                        CreateDate = demodel.CreateDate,
                                        GoodsId = demodel.Id,
                                        Id = 0,
                                        MemberGrade = item.MemberGrade,
                                        MemberPrice = item.MemberPrice,
                                        MallBaseId = demodel.MallBaseId,
                                        SpecificationSort = item.SpecificationSort,
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        UpdateDate = demodel.UpdateDate
                                    });
                                }
                            }
                            else
                            {

                                foreach (var item in mplist)
                                {
                                    var pupmodel = demodel.MemberPriceList.Where(x => x.SpecificationSort == item.SpecificationSort && x.MemberGrade == item.MemberGrade).FirstOrDefault();
                                    if (item.MemberPrice != pupmodel.MemberPrice)
                                    {
                                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_MemberPrice.MemberPrice),pupmodel.MemberPrice}
                                        };
                                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_Goods_MemberPrice.Id),
                                                    FiledValue=item.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        goods_MemberPriceRepository.Update(keyValues1, wheres1);
                                    }
                                }
                            }
                        }
                        #endregion

                        #region 商品代理
                        //由代理  变成  非代理
                        if (goodsModel.IsProxy == 1 && demodel.IsProxy == 2)
                        {
                            //设置所有采购商品  下架  状态代理下架
                            var plist = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { GoodsId = demodel.Id, MallBaseId = goodsModel.MallBaseId, TenantId = goodsModel.TenantId });
                            string goodsIds = string.Join(",", plist.Select(x => x.ProxyGoodsId ?? 0));
                            var glist = goodsRepository.GetSingleListForGoodsId(new RB_Goods_Extend() { GoodsIds = goodsIds });
                            foreach (var item in glist)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_Goods.GoodsStatus),2},
                                    { nameof(RB_Goods.ProcurementStatus),2},
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods.Id),
                                          FiledValue=item.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                goodsRepository.Update(keyValues1, wheres1);
                            }
                        }
                        else if ((goodsModel.IsProxy == 2 || goodsModel.IsProxy == 1) && demodel.IsProxy == 1 && demodel.GoodsStatus == 1)
                        {
                            //启用代理  检测是否有已代理的  同步数据  并采购商品状态
                            var plist = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { GoodsId = demodel.Id, MallBaseId = goodsModel.MallBaseId, TenantId = goodsModel.TenantId });
                            string goodsIds = string.Join(",", plist.Select(x => x.ProxyGoodsId ?? 0));
                            var glist = goodsRepository.GetSingleListForGoodsId(new RB_Goods_Extend() { GoodsIds = goodsIds });
                            //同步数据
                            foreach (var item in glist)
                            {
                                Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                    { nameof(RB_Goods.GoodsStatus),demodel.GoodsStatus},
                                    { nameof(RB_Goods.InventoryNum),demodel.InventoryNum},
                                    { nameof(RB_Goods.DefaultSpecificationName),demodel.DefaultSpecificationName},
                                    { nameof(RB_Goods.IsCustomSpecification),demodel.IsCustomSpecification},
                                    { nameof(RB_Goods.CostPrice),demodel.CostPrice},
                                    { nameof(RB_Goods.IsGoodsNegotiable),demodel.IsGoodsNegotiable},
                                    { nameof(RB_Goods.GoodsNumbers),demodel.GoodsNumbers},
                                    { nameof(RB_Goods.GoodsWeight),demodel.GoodsWeight},
                                    { nameof(RB_Goods.ProcurementStatus),1},
                                    { nameof(RB_Goods.UpdateDate),demodel.UpdateDate}
                                };
                                List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_Goods.Id),
                                          FiledValue=item.Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                bool flag2 = goodsRepository.Update(keyValues2, wheres2);
                                if (flag2)
                                {
                                    //检测规格更新
                                    if (demodel.IsCustomSpecification == 1)
                                    {

                                    }
                                    else
                                    {
                                        //删除规格
                                        var slist = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = item.Id, TenantId = item.TenantId, MallBaseId = item.MallBaseId });
                                        var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = item.Id, TenantId = item.TenantId, MallBaseId = item.MallBaseId });
                                        var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = item.Id, TenantId = item.TenantId, MallBaseId = item.MallBaseId });
                                        //删除
                                        goods_SpecificationRepository.DeleteBatch(slist);
                                        goods_SpecificationValueRepository.DeleteBatch(svlist);
                                        goods_SpecificationPriceRepository.DeleteBatch(splist);
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
                else
                {
                    int Id = goodsRepository.Insert(demodel);
                    bool flag = Id > 0;
                    if (flag)
                    {
                        //插入分类
                        foreach (var item in demodel.CategoryList)
                        {
                            goods_CategoryRepository.Insert(new RB_Goods_Category()
                            {
                                CategoryId = item.CategoryId,
                                CreateDate = demodel.CreateDate,
                                GoodsId = Id,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                Status = 0,
                                TenantId = demodel.TenantId
                            });
                        }
                        //插入规格
                        if (demodel.IsCustomSpecification == 1)
                        {
                            foreach (var item in demodel.SpecificationList)
                            {
                                int sid = goods_SpecificationRepository.Insert(new RB_Goods_Specification()
                                {
                                    CreateDate = demodel.CreateDate,
                                    EnabledImage = item.EnabledImage,
                                    GoodsId = Id,
                                    Id = 0,
                                    MallBaseId = demodel.MallBaseId,
                                    Name = item.Name,
                                    Sort = item.Sort,
                                    Status = 0,
                                    TenantId = demodel.TenantId
                                });
                                if (sid > 0)
                                {
                                    foreach (var qitem in item.SpecificationValueList)
                                    {
                                        goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                                        {
                                            CreateDate = demodel.CreateDate,
                                            GoodsId = Id,
                                            Id = 0,
                                            Image = qitem.Image,
                                            MallBaseId = demodel.MallBaseId,
                                            Name = qitem.Name,
                                            Sort = qitem.Sort,
                                            Status = 0,
                                            TenantId = demodel.TenantId,
                                            SpecificationId = sid
                                        });
                                    }
                                }
                            }
                            foreach (var item in demodel.SpecificationPriceList)
                            {
                                goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                                {
                                    CreateDate = demodel.CreateDate,
                                    GoodsId = Id,
                                    Id = 0,
                                    GoodsNumbers = item.GoodsNumbers,
                                    GoodsWeight = item.GoodsWeight,
                                    InventoryNum = item.InventoryNum,
                                    MallBaseId = demodel.MallBaseId,
                                    SellingPrice = item.SellingPrice,
                                    SpecificationSort = item.SpecificationSort,
                                    Status = 0,
                                    TenantId = demodel.TenantId,
                                    UpdateDate = demodel.UpdateDate,
                                    Commission = item.Commission,
                                    CostMoney = item.CostMoney
                                });
                            }
                        }
                        //插入区域
                        foreach (var item in demodel.AreaList)
                        {
                            goods_AreaRepository.Insert(new RB_Goods_Area()
                            {
                                AreaId = item.AreaId,
                                AreaType = item.AreaType,
                                CreateDate = demodel.CreateDate,
                                GoodsId = Id,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                Status = 0,
                                TenantId = demodel.TenantId
                            });
                        }
                        //插入卡卷
                        //插入分销佣金
                        if (demodel.SeparateDistribution == 1)
                        {
                            foreach (var item in demodel.DistributionCommissionList)
                            {
                                goods_DistributionCommissionRepository.Insert(new RB_Goods_DistributionCommission()
                                {
                                    CreateDate = demodel.CreateDate,
                                    GoodsId = Id,
                                    Id = 0,
                                    DistributorGrade = item.DistributorGrade,
                                    OneCommission = item.OneCommission,
                                    ThreeCommission = item.ThreeCommission,
                                    TwoCommission = item.TwoCommission,
                                    MallBaseId = demodel.MallBaseId,
                                    SpecificationSort = item.SpecificationSort,
                                    Status = 0,
                                    TenantId = demodel.TenantId,
                                    UpdateDate = demodel.UpdateDate
                                });
                            }
                        }
                        //插入会员价格
                        if (demodel.EnjoyMember == 1 && demodel.SeparateSetMember == 1)
                        {
                            foreach (var item in demodel.MemberPriceList)
                            {
                                goods_MemberPriceRepository.Insert(new RB_Goods_MemberPrice()
                                {
                                    CreateDate = demodel.CreateDate,
                                    GoodsId = Id,
                                    Id = 0,
                                    MemberGrade = item.MemberGrade,
                                    MemberPrice = item.MemberPrice,
                                    MallBaseId = demodel.MallBaseId,
                                    SpecificationSort = item.SpecificationSort,
                                    Status = 0,
                                    TenantId = demodel.TenantId,
                                    UpdateDate = demodel.UpdateDate
                                });
                            }
                        }
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProductGoodsInfo:" + Common.Plugin.JsonHelper.Serialize(demodel));
                return false;
            }
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        public RB_Goods_Extend GetProductGoodsInfo(int goodsId, int TenantId, int MallBaseId)
        {
            var model = goodsRepository.GetEntity(goodsId).RefMapperTo<RB_Goods_Extend>();
            if (model == null || model.TenantId != TenantId || model.MallBaseId != MallBaseId)
            {
                return null;
            }
            model.CategoryList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            model.SpecificationList = new List<RB_Goods_Specification_Extend>();
            model.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
            if (model.IsCustomSpecification == 1)
            {
                model.SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (model.SpecificationList.Any())
                {
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in svlist)
                    {
                        item.ImagePath = item.Image;
                    }
                    foreach (var item in model.SpecificationList)
                    {
                        item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                    }
                }
                int SortNum = 1;
                model.SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                foreach (var item in model.SpecificationPriceList)
                {
                    if (!string.IsNullOrEmpty(item.SpecificationSort))
                    {
                        var ssarr = item.SpecificationSort.Split(':');
                        int Sort = Convert.ToInt32(ssarr[0]);
                        string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                        List<object> AttrList = new List<object>();
                        for (int i = 0; i < ssarr.Length; i++)
                        {
                            var smodel = model.SpecificationList[i];
                            var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                            AttrList.Add(new
                            {
                                SName = smodel.Name,
                                SId = smodel.Id,
                                SVId = svmodel.Sort,
                                SVName = svmodel.Name
                            });
                        }
                        item.AttrList = AttrList;
                    }
                    item.SortNum = SortNum;
                    SortNum++;
                }
                model.SpecificationPriceList = model.SpecificationPriceList.OrderByDescending(x => x.SortNum).ToList();
            }
            model.AreaList = new List<RB_Goods_Area_Extend>();
            if (model.IsAreaBuy == 1)
            {
                model.AreaList = goods_AreaRepository.GetList(new RB_Goods_Area_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
            }
            model.DistributionCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
            model.DistributionCommissionTreeList = new List<RB_Goods_DistributionCommission_Extend>();
            if (model.SeparateDistribution == 1)
            {
                model.DistributionCommissionList = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });

                if (model.DistributionCommissionList.Any())
                {
                    int SortNum = 1;
                    //获取分销商启用等级
                    var dgradeList = distributor_GradeRepository.GetList(new RB_Distributor_Grade_Extend() { Enabled = 1, TenantId = TenantId, MallBaseId = MallBaseId });
                    dgradeList.Add(new RB_Distributor_Grade_Extend()
                    {
                        Grade = 0,
                        Name = "默认等级",
                        Id = 0
                    });
                    string zdgradeStr = string.Join(",", dgradeList.Select(x => x.Id).OrderBy(x => x));
                    string ndgradeStr = string.Join(",", model.DistributionCommissionList.Select(x => x.DistributorGrade).Distinct().OrderBy(x => x));
                    var KeyList = model.DistributionCommissionList.Select(x => x.SpecificationSort ?? "").Distinct().ToList();
                    if (zdgradeStr == ndgradeStr)
                    {
                        foreach (var qitem in KeyList)
                        {
                            var treemodel = model.DistributionCommissionList.Where(x => (x.SpecificationSort ?? "") == qitem).FirstOrDefault();
                            treemodel.GradeCommissionList = model.DistributionCommissionList.Where(x => (x.SpecificationSort ?? "") == qitem).ToList();
                            if (model.SeparateDistributionType == 2)
                            {
                                if (!string.IsNullOrEmpty(qitem))
                                {
                                    var ssarr = qitem.Split(':');
                                    int Sort = Convert.ToInt32(ssarr[0]);
                                    string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                    List<object> AttrList = new List<object>();
                                    for (int i = 0; i < ssarr.Length; i++)
                                    {
                                        var smodel = model.SpecificationList[i];
                                        var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                        AttrList.Add(new
                                        {
                                            SName = smodel.Name,
                                            SId = smodel.Id,
                                            SVId = svmodel.Sort,
                                            SVName = svmodel.Name
                                        });
                                    }
                                    treemodel.AttrList = AttrList;
                                }
                            }
                            treemodel.Sort = SortNum;
                            treemodel.GradeCommissionList = treemodel.GradeCommissionList.OrderBy(x => x.DistributorGrade).ToList();
                            model.DistributionCommissionTreeList.Add(treemodel);
                        }
                    }
                    else
                    {//分销商等级有变更
                        foreach (var qitem in KeyList)
                        {
                            var treemodel = model.DistributionCommissionList.Where(x => (x.SpecificationSort ?? "") == qitem).FirstOrDefault();
                            treemodel.GradeCommissionList = new List<RB_Goods_DistributionCommission_Extend>();
                            var gradeCommList = model.DistributionCommissionList.Where(x => (x.SpecificationSort ?? "") == qitem).ToList();
                            dgradeList = dgradeList.OrderByDescending(x => x.Grade).ToList();
                            foreach (var grade in dgradeList)
                            {
                                var gradeMList = gradeCommList.Where(x => x.DistributorGrade == grade.Id && x.SpecificationSort == qitem);
                                if (gradeMList.Any())
                                {
                                    treemodel.GradeCommissionList.AddRange(gradeMList);
                                }
                                else
                                {
                                    //表示新的
                                    treemodel.GradeCommissionList.Add(new RB_Goods_DistributionCommission_Extend()
                                    {
                                        DistributorGrade = grade.Id,
                                        OneCommission = 0,
                                        TwoCommission = 0,
                                        ThreeCommission = 0
                                    });
                                }
                            }
                            if (model.SeparateDistributionType == 2)
                            {
                                if (!string.IsNullOrEmpty(qitem))
                                {
                                    var ssarr = qitem.Split(':');
                                    int Sort = Convert.ToInt32(ssarr[0]);
                                    string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                    List<object> AttrList = new List<object>();
                                    for (int i = 0; i < ssarr.Length; i++)
                                    {
                                        var smodel = model.SpecificationList[i];
                                        var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                        AttrList.Add(new
                                        {
                                            SName = smodel.Name,
                                            SId = smodel.Id,
                                            SVId = svmodel.Sort,
                                            SVName = svmodel.Name
                                        });
                                    }
                                    treemodel.AttrList = AttrList;
                                }
                            }
                            treemodel.Sort = SortNum;
                            treemodel.GradeCommissionList = treemodel.GradeCommissionList.OrderBy(x => x.DistributorGrade).ToList();
                            model.DistributionCommissionTreeList.Add(treemodel);
                        }
                    }
                    SortNum++;
                    if (model.DistributionCommissionTreeList.Any())
                    {
                        //倒序排一次
                        model.DistributionCommissionTreeList = model.DistributionCommissionTreeList.OrderByDescending(x => x.Sort).ToList();
                    }
                }
            }
            model.MemberPriceList = new List<RB_Goods_MemberPrice_Extend>();
            model.MemberPriceTreeList = new List<RB_Goods_MemberPrice_Extend>();
            if (model.EnjoyMember == 1 && model.SeparateSetMember == 1)
            {
                model.MemberPriceList = goods_MemberPriceRepository.GetList(new RB_Goods_MemberPrice_Extend() { GoodsId = goodsId, TenantId = TenantId, MallBaseId = MallBaseId });
                if (model.MemberPriceList.Any())
                {
                    int SortNum = 1;
                    var mgradeList = member_GradeRepository.GetList(new RB_Member_Grade_Extend() { Enabled = 1, TenantId = 1, MallBaseId = 1 });

                    string zdgradeStr = string.Join(",", mgradeList.Select(x => x.Id).OrderBy(x => x));
                    string ndgradeStr = string.Join(",", model.MemberPriceList.Select(x => x.MemberGrade).Distinct().OrderBy(x => x));
                    if (zdgradeStr == ndgradeStr)
                    {
                        var KeyList = model.MemberPriceList.Select(x => x.SpecificationSort ?? "").Distinct().ToList();
                        foreach (var qitem in KeyList)
                        {
                            var treemodel = model.MemberPriceList.Where(x => (x.SpecificationSort ?? "") == qitem).FirstOrDefault();
                            treemodel.GradePriceList = model.MemberPriceList.Where(x => (x.SpecificationSort ?? "") == qitem).ToList();
                            if (!string.IsNullOrEmpty(qitem))
                            {
                                var ssarr = qitem.Split(':');
                                int Sort = Convert.ToInt32(ssarr[0]);
                                string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                List<object> AttrList = new List<object>();
                                for (int i = 0; i < ssarr.Length; i++)
                                {
                                    var smodel = model.SpecificationList[i];
                                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                    AttrList.Add(new
                                    {
                                        SName = smodel.Name,
                                        SId = smodel.Id,
                                        SVId = svmodel.Sort,
                                        SVName = svmodel.Name
                                    });
                                }
                                treemodel.AttrList = AttrList;
                            }
                            treemodel.Sort = SortNum;
                            treemodel.GradePriceList = treemodel.GradePriceList.OrderBy(x => x.MemberGrade).ToList();
                            model.MemberPriceTreeList.Add(treemodel);
                        }
                    }
                    else
                    {//会员等级有变更
                        var KeyList = model.MemberPriceList.Select(x => x.SpecificationSort ?? "").Distinct().ToList();
                        foreach (var qitem in KeyList)
                        {
                            var treemodel = model.MemberPriceList.Where(x => (x.SpecificationSort ?? "") == qitem).FirstOrDefault();
                            //treemodel.GradePriceList = model.MemberPriceList.Where(x => (x.SpecificationSort ?? "") == qitem).ToList();
                            treemodel.GradePriceList = new List<RB_Goods_MemberPrice_Extend>() { };
                            var gradePrice = model.MemberPriceList.Where(x => (x.SpecificationSort ?? "") == qitem).ToList();
                            mgradeList = mgradeList.OrderByDescending(x => x.Grade).ToList();
                            foreach (var grade in mgradeList)
                            {
                                var gradeMList = gradePrice.Where(x => x.MemberGrade == grade.Id && x.SpecificationSort == qitem);
                                if (gradeMList.Any())
                                {
                                    treemodel.GradePriceList.AddRange(gradeMList);
                                }
                                else
                                {
                                    //表示新的
                                    treemodel.GradePriceList.Add(new RB_Goods_MemberPrice_Extend()
                                    {
                                        MemberGrade = grade.Id,
                                        MemberPrice = 0,
                                    });
                                }
                            }
                            if (!string.IsNullOrEmpty(qitem))
                            {
                                var ssarr = qitem.Split(':');
                                int Sort = Convert.ToInt32(ssarr[0]);
                                string pic_url = model.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                List<object> AttrList = new List<object>();
                                for (int i = 0; i < ssarr.Length; i++)
                                {
                                    var smodel = model.SpecificationList[i];
                                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                    AttrList.Add(new
                                    {
                                        SName = smodel.Name,
                                        SId = smodel.Id,
                                        SVId = svmodel.Sort,
                                        SVName = svmodel.Name
                                    });
                                }
                                treemodel.AttrList = AttrList;
                            }
                            treemodel.Sort = SortNum;
                            treemodel.GradePriceList = treemodel.GradePriceList.OrderBy(x => x.MemberGrade).ToList();
                            model.MemberPriceTreeList.Add(treemodel);
                        }
                    }

                    SortNum++;
                    if (model.MemberPriceTreeList.Any())
                    {
                        //倒序排一次
                        model.MemberPriceTreeList = model.MemberPriceTreeList.OrderByDescending(x => x.Sort).ToList();
                    }
                }
            }
            model.CarouselImageList = new List<RB_ImageCommonModel>();
            if (!string.IsNullOrEmpty(model.CarouselImage) && model.CarouselImage != "[]")
            {
                List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(model.CarouselImage);
                //轮播图
                foreach (var item in CarouselIdList)
                {
                    model.CarouselImageList.Add(new RB_ImageCommonModel()
                    {
                        Id = 0,
                        Name = "",
                        Path = item
                    });
                }
            }
            model.CustomShareImagePath = model.CustomShareImage;
            //服务列表
            model.ServiceList = new List<RB_ImageCommonModel>();
            if (model.IsDefaultService == 2)
            {
                if (!string.IsNullOrEmpty(model.GoodsService) && model.GoodsService != "[]")
                {
                    List<int> ServiceIds = JsonConvert.DeserializeObject<List<int>>(model.GoodsService);
                    var slist = product_ServiceRepository.GetList(new RB_Product_Service_Extend() { ServiceIds = string.Join(",", ServiceIds), TenantId = TenantId, MallBaseId = MallBaseId });
                    foreach (var item in slist)
                    {
                        model.ServiceList.Add(new RB_ImageCommonModel()
                        {
                            Id = item.Id,
                            Name = item.Name
                        });
                    }
                }
            }
            //运费
            if (model.FreightId > 0)
            {
                model.FreightName = logistics_RulesRepository.GetEntity(model.FreightId)?.RulesName ?? "";
            }
            else
            {
                model.FreightName = "默认运费";
            }
            //表单
            if (model.FormsId > 0)
            {
                model.FormsName = "未建表";
            }
            else
            {
                model.FormsName = "默认表单";
            }

            return model;
        }

        /// <summary>
        /// 快速修改
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="type"></param>
        /// <param name="sort"></param>
        /// <param name="goodsName"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetProductGoodsQuickUpdate(int goodsId, int type, int sort, string goodsName, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues;
            if (type == 1)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Sort),sort}
                };
            }
            else if (type == 2)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Name),goodsName}
                };
            }
            else if (type == 3)
            {
                var model = goodsRepository.GetEntity(goodsId);
                if (model == null)
                {
                    return false;
                }
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.IsQuickBuy),model.IsQuickBuy==1?2:1}
                };
            }

            else
            {
                return false;
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.Id),
                        FiledValue=goodsId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goodsRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 快速修改
        /// </summary>
        /// <param name="goodsIds"></param>
        /// <param name="type"></param>
        /// <param name="sort"></param>
        /// <param name="goodsName"></param>
        /// <param name="freightId"></param>
        /// <param name="limitBuyGoodsNum"></param>
        /// <param name="limitBuyOrderNum"></param>
        /// <param name="integralPresent"></param>
        /// <param name="integralPresentType"></param>
        /// <param name="pointsDeduction"></param>
        /// <param name="pointsDeductionType"></param>
        /// <param name="isMultipleDeduction"></param>
        /// <param name="isQuickBuy"></param>
        /// <param name="isGoodsNegotiable"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetProductGoodsQuickUpdate(string goodsIds, int type, int sort, string goodsName, int freightId, int limitBuyGoodsNum, int limitBuyOrderNum, int integralPresent, int integralPresentType, decimal pointsDeduction, int pointsDeductionType, int isMultipleDeduction, int isQuickBuy, int isGoodsNegotiable, int SupplierId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues;
            if (type == 1)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Sort),sort}
                };
            }//排序
            else if (type == 2)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Name),goodsName}
                };
            }//商品名称
            else if (type == 3)
            {
                var model = goodsRepository.GetEntity(Convert.ToInt32(goodsIds));
                if (model == null)
                {
                    return false;
                }
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.IsQuickBuy),model.IsQuickBuy==1?2:1}
                };
            }//单个快速购买
            else if (type == 4)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.GoodsStatus),1}
                };
            }//上架
            else if (type == 5)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.GoodsStatus),2}
                };
            }//下架
            else if (type == 6)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Status),1}
                };
            }//删除
            else if (type == 7)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.FreightId),freightId}
                };
            }//运费
            else if (type == 8)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.LimitBuyGoodsNum),limitBuyGoodsNum},
                    { nameof(RB_Goods.LimitBuyOrderNum),limitBuyOrderNum},
                };
            }//限购
            else if (type == 9)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.IntegralPresent),integralPresent},
                    { nameof(RB_Goods.IntegralPresentType),integralPresentType},
                    { nameof(RB_Goods.PointsDeduction),pointsDeduction},
                    { nameof(RB_Goods.PointsDeductionType),pointsDeductionType},
                    { nameof(RB_Goods.IsMultipleDeduction),isMultipleDeduction},
                };
            }//积分
            else if (type == 10)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.IsQuickBuy),isQuickBuy}
                };
            }//批量快速购买
            else if (type == 11)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.IsGoodsNegotiable),isGoodsNegotiable}
                };
            }//面议
            else if (type == 12)
            {
                keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods.SupplierId),SupplierId}
                };
            }//面议
            else
            {
                return false;
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.Id),
                        FiledValue=goodsIds,
                        OperatorEnum=OperatorEnum.IN
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goodsRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool DelProcudtGoodsInfo(int goodsId, int tenantId, int mallBaseId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods.Status),1},
                { nameof(RB_Goods.UpdateDate),DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.Id),
                        FiledValue=goodsId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.TenantId),
                        FiledValue=tenantId,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Goods.MallBaseId),
                        FiledValue=mallBaseId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return goodsRepository.Update(keyValues, 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);
            return list;
        }

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



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

        /// <summary>
        /// 根据商品id获取商品规格
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<RB_Goods_Specification_Extend> GetSpecificationList(RB_Goods_Specification_Extend model)
        {
            return goods_SpecificationRepository.GetList(model);
        }
        /// <summary>
        /// 根据商品id获取商品规格价格
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<RB_Goods_SpecificationPrice_Extend> GetSpecificationPriceList(RB_Goods_SpecificationPrice_Extend model)
        {
            return goods_SpecificationPriceRepository.GetList(model);
        }
        /// <summary>
        /// 根据商品id获取商品规格值
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<RB_Goods_SpecificationValue_Extend> GetSpecificationValueList(RB_Goods_SpecificationValue_Extend model)
        {
            return goods_SpecificationValueRepository.GetList(model);
        }

        /// <summary>
        /// 商品分类修改
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="newCategoryId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string SetGoodsCategoryTransfer(int categoryId, int newCategoryId, int tenantId, int mallBaseId, int empId)
        {
            var newModel = product_CategoryRepository.GetEntity(newCategoryId);
            if (newModel == null) { return "新分类不存在"; }
            if (newModel.Enabled != 1) { return "新分类未启用"; }

            var list = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { CategoryId = categoryId, TenantId = tenantId, MallBaseId = mallBaseId });
            if (list.Any())
            {
                foreach (var item in list)
                {
                    //修改分类
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Goods_Category.CategoryId),newCategoryId}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                              FiledName= nameof(RB_Goods_Category.Id),
                               FiledValue=item.Id,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    bool flag = goods_CategoryRepository.Update(keyValues, wheres);
                    if (flag)
                    {
                        //记录该商品日志
                        goods_LogRepository.Insert(new RB_Goods_Log()
                        {
                            Id = 0,
                            Type = 2,
                            TenantId = tenantId,
                            MallBaseId = mallBaseId,
                            SourceId = item.GoodsId,
                            CreateDate = DateTime.Now,
                            Content = "商品分类转移,empId:" + empId + "，由" + categoryId + "转移至" + newCategoryId
                        });
                    }
                }
                return "转移成功，总计：" + list.Count() + "商品";
            }
            else
            {
                return "该分类下未找到相关商品";
            }
        }

        #endregion

        #region 商品代理

        /// <summary>
        /// 新增代理商品
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="categoryList"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public ApiResult SetProductGoodsProxy(int goodsId, List<int> categoryList, int tenantId, int mallBaseId)
        {
            var plist = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { GoodsId = goodsId, ProxyMallBaseId = mallBaseId, ProxyTenantId = tenantId });
            if (plist.Any())
            {
                return ApiResult.Failed("该商品已存在采购");
            }
            var goodsModel = goodsRepository.GetEntity(goodsId);
            if (goodsModel == null)
            {
                return ApiResult.Failed("采购商品不存在");
            }
            if (goodsModel.GoodsStatus != 1)
            {
                return ApiResult.Failed("该商品未上架，无法采购");
            }
            if (goodsModel.IsProxy != 1)
            {
                return ApiResult.Failed("采购商品不可代理");
            }
            if (goodsModel.IsProcurement == 1)
            {
                return ApiResult.Failed("采购商品不可代理");
            }
            if (goodsModel.TenantId == tenantId)
            {
                return ApiResult.Failed("不可采购同商户商品");
            }
            if ((goodsModel.ProxyMoney ?? 0) <= 0)
            {
                return ApiResult.Failed("采购商品有误");
            }

            var trans = goodsRepository.DbTransaction;
            try
            {
                //复制商品信息
                int Id = goodsRepository.Insert(new RB_Goods()
                {
                    Name = goodsModel.Name,
                    CarouselImage = goodsModel.CarouselImage,
                    VideoAddress = goodsModel.VideoAddress,
                    CustomShareTitles = goodsModel.CustomShareTitles,
                    CustomShareImage = goodsModel.CustomShareImage,
                    GoodsStatus = goodsModel.GoodsStatus,
                    InventoryNum = goodsModel.InventoryNum,
                    DefaultSpecificationName = goodsModel.DefaultSpecificationName,
                    IsCustomSpecification = goodsModel.IsCustomSpecification,
                    Sort = goodsModel.Sort,
                    SellingPrice = goodsModel.SellingPrice,
                    OriginalPrice = goodsModel.OriginalPrice,
                    Unit = goodsModel.Unit,
                    CostPrice = goodsModel.ProxyMoney,
                    IsGoodsNegotiable = goodsModel.IsGoodsNegotiable,
                    SalesNum = goodsModel.SalesNum,
                    GoodsNumbers = goodsModel.GoodsNumbers,
                    GoodsWeight = goodsModel.GoodsWeight,
                    IsDefaultService = 1,
                    GoodsService = "[]",
                    FreightId = 0,
                    FormsId = 0,
                    LimitBuyGoodsNum = goodsModel.LimitBuyGoodsNum,
                    LimitBuyOrderNum = goodsModel.LimitBuyOrderNum,
                    FullNumPinkage = goodsModel.FullNumPinkage,
                    FullMoneyPinkage = goodsModel.FullMoneyPinkage,
                    IsAreaBuy = 2,
                    IntegralPresent = goodsModel.IntegralPresent,
                    IntegralPresentType = goodsModel.IntegralPresentType,
                    PointsDeduction = goodsModel.PointsDeduction,
                    PointsDeductionType = goodsModel.PointsDeductionType,
                    IsMultipleDeduction = goodsModel.IsMultipleDeduction,
                    GoodsDetails = goodsModel.GoodsDetails,
                    Status = 0,
                    TenantId = tenantId,
                    MallBaseId = mallBaseId,
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    SeparateDistribution = 2,
                    SeparateDistributionType = 1,
                    SeparateDistributionMoneyType = 1,
                    EnjoyMember = 2,
                    SeparateSetMember = 2,
                    IsQuickBuy = 2,
                    IsSellWell = 2,
                    GoodsType = goodsModel.GoodsType,
                    SupplierId = 0,
                    IsProxy = 2,
                    ProxyType = 1,
                    ProxyRises = 0,
                    ProxyMoney = 0,
                    IsProcurement = 1,
                    ProcurementStatus = 1
                }, trans);
                if (Id > 0)
                {
                    goods_ProxyRepository.Insert(new RB_Goods_Proxy()
                    {
                        CreateDate = DateTime.Now,
                        GoodsId = goodsId,
                        Id = 0,
                        MallBaseId = goodsModel.MallBaseId,
                        TenantId = goodsModel.TenantId,
                        ProxyGoodsId = Id,
                        ProxyMallBaseId = mallBaseId,
                        ProxyTenantId = tenantId,
                        Remark = "新增采购",
                        Status = 0
                    }, trans);
                    //商品分类
                    foreach (var item in categoryList)
                    {
                        goods_CategoryRepository.Insert(new RB_Goods_Category()
                        {
                            CategoryId = item,
                            CreateDate = DateTime.Now,
                            GoodsId = Id,
                            Id = 0,
                            MallBaseId = mallBaseId,
                            Status = 0,
                            TenantId = tenantId
                        }, trans);
                    }
                    //复制规格
                    var slist = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsId = goodsId });
                    var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsId = goodsId });
                    foreach (var item in slist)
                    {
                        goods_SpecificationRepository.Insert(new RB_Goods_Specification()
                        {
                            EnabledImage = item.EnabledImage,
                            CreateDate = DateTime.Now,
                            GoodsId = Id,
                            Id = 0,
                            MallBaseId = mallBaseId,
                            Name = item.Name,
                            Sort = item.Sort,
                            Status = 0,
                            TenantId = tenantId
                        }, trans);
                    }
                    foreach (var item in svlist)
                    {
                        goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                        {
                            TenantId = tenantId,
                            Status = 0,
                            Sort = item.Sort,
                            CreateDate = DateTime.Now,
                            GoodsId = Id,
                            Id = 0,
                            Image = item.Image,
                            MallBaseId = mallBaseId,
                            Name = item.Name,
                            SpecificationId = item.SpecificationId
                        }, trans);
                    }
                }
                goodsRepository.DBSession.Commit();
                if (Id > 0)
                    return ApiResult.Success();
                else
                    return ApiResult.Failed();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProductGoodsProxy");
                goodsRepository.DBSession.Rollback("SetProductGoodsProxy");
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 取消商品代理
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="type"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool CancelGoodsProxy(int goodsId, int type, int tenantId, int mallBaseId)
        {
            var plist = new List<RB_Goods_Proxy_Extend>();
            if (type == 1)
            {
                plist = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { GoodsId = goodsId, ProxyMallBaseId = mallBaseId, ProxyTenantId = tenantId });
            }
            else
            {
                plist = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { ProxyGoodsId = goodsId, ProxyMallBaseId = mallBaseId, ProxyTenantId = tenantId });
            }
            if (!plist.Any())
            {
                return false;
            }
            var pModel = plist.FirstOrDefault();
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Goods_Proxy.Status),1},
                { nameof(RB_Goods_Proxy.Remark),DateTime.Now.ToString("yyyy-MM-dd")+ " 取消代理"}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Proxy.Id),
                      FiledValue=pModel.Id,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_ProxyRepository.Update(keyValues, wheres);
            if (flag)
            {
                //删除商品
                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                    { nameof(RB_Goods.Status),1},
                    { nameof(RB_Goods.UpdateDate),DateTime.Now}
                };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods.Id),
                          FiledValue=pModel.ProxyGoodsId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                goodsRepository.Update(keyValues1, wheres1);
            }
            return flag;
        }

        /// <summary>
        /// 设置采购商品上下架
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="type">类型  1上架   2下架</param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetGoodsProxyStatus(int goodsId, int type, int tenantId, int mallBaseId)
        {
            var goodsModel = goodsRepository.GetEntity(goodsId);
            if (goodsModel == null)
            {
                return false;
            }
            if (goodsModel.IsProcurement != 1)
            {
                return false;
            }
            if (goodsModel.ProcurementStatus != 1)
            {
                return false;
            }
            int GoodsStatus = 1;
            if (type == 1)
            {
                if (goodsModel.GoodsStatus != 2)
                {
                    return false;
                }
            }
            else
            {
                if (goodsModel.GoodsStatus != 1)
                {
                    return false;
                }
                GoodsStatus = 2;
            }

            var pModel = goods_ProxyRepository.GetList(new RB_Goods_Proxy_Extend() { ProxyGoodsId = goodsId, ProxyMallBaseId = mallBaseId, ProxyTenantId = tenantId }).FirstOrDefault();
            if (pModel == null) { return false; }
            var gModel = goodsRepository.GetEntity(pModel.GoodsId);
            if (gModel == null) { return false; }
            if (gModel.GoodsStatus == 1 && gModel.IsProxy == 1)
            {
                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                    { nameof(RB_Goods.GoodsStatus),GoodsStatus},
                    { nameof(RB_Goods.UpdateDate),DateTime.Now}
                };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_Goods.Id),
                            FiledValue=goodsModel.Id,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                return goodsRepository.Update(keyValues1, wheres1);
            }
            return false;
        }

        #endregion

        #region 商品导入

        /// <summary>
        /// 赞羊商品导入
        /// </summary>
        /// <param name="path_server"></param>
        /// <param name="goodsStatus"></param>
        /// <param name="categoryIdList"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public string SetGoodsBatchImport(string path_server, int goodsStatus, List<int> categoryIdList, int tenantId, int mallBaseId)
        {
            if (!System.IO.File.Exists(path_server))
            {
                return "导入文件已删除，请刷新后重新导入再试";
            }
            int FileType = path_server.Contains(".csv") ? 1 : 2;//1 赞羊导入   2 和平导入
            //处理文件内容读取
            List<RB_Goods_Extend> list = DataHelper.GoodsBetchDataHelper.ImportClaimData(path_server);
            list = list.Where(x => !string.IsNullOrWhiteSpace(x.Name)).ToList();
            if (list.Any())
            {
                List<string> AreaName = new List<string>();
                foreach (var item in list)
                {
                    #region 导入验证
                    if (string.IsNullOrEmpty(item.Name))
                    {
                        return "有商品名称为空，无法导入";
                    }
                    if ((item.OriginalPrice ?? 0) < 0)
                    {
                        return "商品原价为空：" + item.Name;
                    }
                    if ((item.SellingPrice ?? 0) < 0)
                    {
                        return "商品售价为空：" + item.Name;
                    }
                    if (string.IsNullOrEmpty(item.CoverImage))
                    {
                        return "封面图为空：" + item.Name;
                    }
                    if (string.IsNullOrEmpty(item.CarouselImage))
                    {
                        return "轮播图为空：" + item.Name;
                    }
                    if (item.IsCustomSpecification == 1)
                    {
                        if (string.IsNullOrEmpty(item.SpecificationImport))
                        {
                            return "规格组为空：" + item.Name;
                        }
                        if (string.IsNullOrEmpty(item.SpecificationPriceImport))
                        {
                            return "规格详情为空：" + item.Name;
                        }
                    }
                    if (item.IsAreaBuy == 1)
                    {
                        if (string.IsNullOrEmpty(item.AreaImport))
                        {
                            return "区域购买为空：" + item.Name;
                        }
                    }

                    if (FileType == 1)
                    {
                        try
                        {
                            //转化轮播图
                            List<GoodsCarouselImport> CarouseList = JsonConvert.DeserializeObject<List<GoodsCarouselImport>>(item.CarouselImage);
                            item.CarouselImage = JsonConvert.SerializeObject(CarouseList.Select(x => x.pic_url));//转化为系统格式
                        }
                        catch (Exception)
                        {
                            return "轮播图格式有误";
                        }
                        item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                        item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                        item.AreaList = new List<RB_Goods_Area_Extend>();
                        try
                        {
                            List<GoodsSpecificationImport> SpecificationList = JsonConvert.DeserializeObject<List<GoodsSpecificationImport>>(item.SpecificationImport);
                            List<GoodsSpecificationPriceImport> SpecificationPriceList = JsonConvert.DeserializeObject<List<GoodsSpecificationPriceImport>>(item.SpecificationPriceImport);
                            //转化规格组
                            if (item.IsCustomSpecification == 1)
                            {
                                //规格组转化
                                int Num = 1;
                                foreach (var qitem in SpecificationList)
                                {
                                    List<RB_Goods_SpecificationValue_Extend> SpecificationValueList = new List<RB_Goods_SpecificationValue_Extend>();
                                    int EnabledImage = 2;
                                    foreach (var qqitem in qitem.attr_list)
                                    {
                                        if (!string.IsNullOrEmpty(qqitem.pic_url))
                                        {
                                            EnabledImage = 1;
                                        }
                                        SpecificationValueList.Add(new RB_Goods_SpecificationValue_Extend()
                                        {
                                            Sort = qqitem.attr_id,
                                            Name = FromUnicodeString(qqitem.attr_name),
                                            Image = qqitem.pic_url
                                        });
                                    }
                                    if (Num > 1) { EnabledImage = 2; }
                                    item.SpecificationList.Add(new RB_Goods_Specification_Extend()
                                    {
                                        Sort = qitem.attr_group_id,
                                        Name = FromUnicodeString(qitem.attr_group_name),
                                        EnabledImage = EnabledImage,
                                        SpecificationValueList = SpecificationValueList
                                    });
                                    Num++;
                                }
                                //规格详情转化
                                foreach (var qitem in SpecificationPriceList)
                                {
                                    item.SpecificationPriceList.Add(new RB_Goods_SpecificationPrice_Extend()
                                    {
                                        SpecificationSort = qitem.sign_id,
                                        GoodsNumbers = FromUnicodeString(qitem.no),
                                        GoodsWeight = qitem.weight,
                                        InventoryNum = qitem.stock,
                                        SellingPrice = qitem.price
                                    });
                                }
                            }
                            else
                            {
                                item.DefaultSpecificationName = SpecificationList.FirstOrDefault()?.attr_list?.FirstOrDefault()?.attr_name ?? "";
                                item.GoodsNumbers = SpecificationPriceList.FirstOrDefault()?.no ?? "";
                                item.GoodsWeight = SpecificationPriceList.FirstOrDefault()?.weight ?? 0;
                            }
                            item.GoodsId = SpecificationPriceList.FirstOrDefault()?.goods_id ?? 0;
                        }
                        catch (Exception)
                        {
                            return "规格组/规格详情有误";
                        }
                        try
                        {
                            //转化区域
                            if (item.IsAreaBuy == 1)
                            {
                                List<GoodsAreaListImport> GoodsAreaList = JsonConvert.DeserializeObject<List<GoodsAreaListImport>>(item.AreaImport);
                                foreach (var qitem in GoodsAreaList)
                                {
                                    foreach (var qqitem in qitem.list)
                                    {
                                        item.AreaList.Add(new RB_Goods_Area_Extend()
                                        {
                                            AreaName = qqitem.name//拿到name  查询根据系统区域表再次查询所有的区域拿到id
                                        });
                                        AreaName.Add("'" + (qqitem.name ?? "") + "'");
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            return "区域格式有误";
                        }

                        try
                        {
                            if (item.GoodsId <= 0)
                            {
                                return "商品id不存在：" + item.Name;
                            }
                            var goodsModel = goodsRepository.GetEntity(item.GoodsId);
                            if (goodsModel != null)
                            {
                                return "商品id已存在：" + item.Name + " ,id:" + item.GoodsId;
                            }
                        }
                        catch (Exception)
                        {
                            return "商品id获取出错了";
                        }
                    }
                    else
                    {
                        try
                        {
                            //转化轮播图
                            List<string> CarouseList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        }
                        catch (Exception)
                        {
                            return "轮播图格式有误";
                        }
                        item.SpecificationList = new List<RB_Goods_Specification_Extend>();
                        item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                        item.AreaList = new List<RB_Goods_Area_Extend>();
                        try
                        {
                            item.SpecificationList = JsonConvert.DeserializeObject<List<RB_Goods_Specification_Extend>>(item.SpecificationImport);
                            item.SpecificationPriceList = JsonConvert.DeserializeObject<List<RB_Goods_SpecificationPrice_Extend>>(item.SpecificationPriceImport);
                            //转化规格组
                            if (item.IsCustomSpecification != 1)
                            {
                                item.DefaultSpecificationName = item.SpecificationList.FirstOrDefault()?.SpecificationValueList?.FirstOrDefault()?.Name ?? "";
                                item.GoodsNumbers = item.SpecificationPriceList.FirstOrDefault()?.GoodsNumbers ?? "";
                                item.GoodsWeight = item.SpecificationPriceList.FirstOrDefault()?.GoodsWeight ?? 0;
                            }

                            //item.Id = item.SpecificationPriceList.FirstOrDefault()?.GoodsId ?? 0;
                        }
                        catch (Exception)
                        {
                            return "规格组/规格详情有误";
                        }
                        try
                        {
                            //转化区域
                            if (item.IsAreaBuy == 1)
                            {
                                item.AreaList = JsonConvert.DeserializeObject<List<RB_Goods_Area_Extend>>(item.AreaImport);
                            }
                        }
                        catch (Exception)
                        {
                            return "区域格式有误";
                        }
                    }
                    #endregion

                    #region 规格验证

                    if (item.IsCustomSpecification == 1)
                    {

                        if (item.SpecificationList.Count() != item.SpecificationList.Select(x => x.Sort).Distinct().Count())
                        {
                            return "商品规格组排序有误：" + item.Name;
                        }
                        int TotalNum = 1;
                        foreach (var qitem in item.SpecificationList)
                        {
                            if (qitem.SpecificationValueList.Count() != qitem.SpecificationValueList.Select(x => x.Sort).Distinct().Count())
                            {
                                return "商品规格组排序有误：" + item.Name;
                            }
                            TotalNum *= qitem.SpecificationValueList.Count();
                            if (qitem.EnabledImage != 1)
                            {
                                foreach (var qqitem in qitem.SpecificationValueList)
                                {
                                    qqitem.Image = "";
                                }
                            }
                        }
                        //验证总keys数量
                        if (item.SpecificationPriceList.Count() != TotalNum)
                        {
                            return "商品规格明细数量有误：" + item.Name;
                        }
                        //初始化所有keys
                        List<string> KeyList = new List<string>();
                        for (var i = 1; i <= TotalNum; i++)
                        {
                            KeyList.Add("");
                        }
                        int MGBJNum = 1;
                        //组装所有keys
                        foreach (var qitem in item.SpecificationList)
                        {
                            int LBBJNum = TotalNum / qitem.SpecificationValueList.Count() / MGBJNum;
                            int KeyIndex = 0;
                            for (var i = 1; i <= LBBJNum; i++)
                            {
                                foreach (var qqitem in qitem.SpecificationValueList)
                                {
                                    for (var j = 1; j <= MGBJNum; j++)
                                    {
                                        KeyList[KeyIndex] = KeyList[KeyIndex] + ":" + qqitem.Sort;
                                        KeyIndex++;
                                    }
                                }
                            }
                        }
                        //验证所有keys
                        foreach (var qitem in KeyList)
                        {
                            string keys = qitem[1..];
                            var pricemodel = item.SpecificationPriceList.Where(x => x.SpecificationSort == keys).FirstOrDefault();
                            if (pricemodel == null)
                            {
                                return "商品规格价格Key有误：" + item.Name;
                            }
                            pricemodel.InventoryNum ??= 0;
                            pricemodel.SellingPrice ??= 0;
                            pricemodel.GoodsNumbers ??= "";
                            pricemodel.GoodsWeight ??= 0;
                            item.InventoryNum += (pricemodel.InventoryNum ?? 0);
                        }
                        //主表价格  如果有自定义规格，直接取最小值
                        item.SellingPrice = item.SpecificationPriceList.Min(x => x.SellingPrice ?? 0);
                    }

                    #endregion

                    #region 商品分类
                    item.CategoryList = new List<RB_Goods_Category_Extend>();
                    foreach (var qitem in categoryIdList)
                    {
                        item.CategoryList.Add(new RB_Goods_Category_Extend()
                        {
                            CategoryId = qitem
                        });
                    }
                    #endregion

                    #region 赋默认值

                    item.GoodsStatus = goodsStatus;
                    item.DefaultSpecificationName ??= "";
                    item.GoodsNumbers ??= "";
                    item.GoodsWeight ??= 0;
                    item.IsDefaultService ??= 1;
                    item.GoodsService = "[]";
                    item.FreightId ??= 0;
                    item.FormsId ??= 0;
                    item.SeparateDistribution ??= 2;
                    item.SeparateDistributionType ??= 1;
                    item.SeparateDistributionMoneyType ??= 1;
                    item.EnjoyMember ??= 2;
                    item.SeparateSetMember ??= 2;
                    item.GoodsType ??= Common.Enum.Goods.OrderTypeEnum.Mall;

                    item.IsProxy ??= 2;
                    item.ProxyType ??= 0;
                    item.ProxyRises ??= 0;
                    item.ProxyMoney ??= 0;
                    item.IsProcurement = 2;

                    item.Status = 0;
                    item.TenantId = tenantId;
                    item.MallBaseId = mallBaseId;
                    item.CreateDate = DateTime.Now;
                    item.UpdateDate = DateTime.Now;

                    #endregion

                    #region 修正默认
                    item.Name = item.Name.Replace("\t", "");
                    item.IsSellWell = item.IsSellWell == 1 ? 1 : 2;
                    item.IsQuickBuy = item.IsQuickBuy == 1 ? 1 : 2;
                    item.IsGoodsNegotiable = item.IsGoodsNegotiable == 1 ? 1 : 2;
                    item.IsAreaBuy = item.IsAreaBuy == 1 ? 1 : 2;
                    item.IsMultipleDeduction = item.IsMultipleDeduction == 1 ? 1 : 2;
                    item.IsCustomSpecification = item.IsCustomSpecification == 1 ? 1 : 2;
                    #endregion
                }
                //根据区域名称  查找所有区域id
                List<Model.Extend.BaseSetUp.RB_Destination_Extend> destList = new List<Model.Extend.BaseSetUp.RB_Destination_Extend>();
                if (FileType == 1)
                {
                    destList = destinationRepository.GetListExt(new Model.Extend.BaseSetUp.RB_Destination_Extend() { NameStr = string.Join(",", AreaName.Distinct()) });
                }
                var trans = goodsRepository.DbTransaction;
                DateTime dt = DateTime.Now;
                try
                {
                    foreach (var item in list)
                    {
                        if (item.IsAreaBuy == 1 && FileType == 1)
                        {
                            foreach (var qitem in item.AreaList)
                            {
                                qitem.AreaId = destList.Where(x => x.Name == qitem.AreaName).FirstOrDefault()?.ID;
                                qitem.AreaType = (int)(destList.Where(x => x.Name == qitem.AreaName).FirstOrDefault()?.CodeLevel ?? Common.Enum.AreaRegionEnum.CountryEnum);
                            }
                        }
                        bool flag = SetGoodsImportInfo(item, trans);
                        if (flag == false)
                        {
                            goodsRepository.DBSession.Rollback();
                            return "请联系管理员，商品导入失败：" + item.Name;
                        }
                    }
                    goodsRepository.DBSession.Commit();
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetGoodsBatchImport");
                    goodsRepository.DBSession.Rollback();
                    System.IO.File.Delete(path_server);
                    return "出错啦，请联系管理员";
                }
            }
            System.IO.File.Delete(path_server);
            return "";
        }

        /// <summary>
        /// 新增商品导入
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetGoodsImportInfo(RB_Goods_Extend demodel, System.Data.IDbTransaction trans)
        {
            try
            {
                int Id = goodsRepository.Insert(demodel, trans);
                bool flag = Id > 0;
                if (flag)
                {
                    if (demodel.GoodsId > 0)
                    {
                        goodsRepository.SetGoodsNewId(demodel.GoodsId ?? 0, Id, trans);
                        Id = demodel.GoodsId ?? 0;
                    }
                    //插入分类
                    foreach (var item in demodel.CategoryList)
                    {
                        goods_CategoryRepository.Insert(new RB_Goods_Category()
                        {
                            CategoryId = item.CategoryId,
                            CreateDate = demodel.CreateDate,
                            GoodsId = Id,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            Status = 0,
                            TenantId = demodel.TenantId
                        }, trans);
                    }
                    //插入规格
                    if (demodel.IsCustomSpecification == 1)
                    {
                        foreach (var item in demodel.SpecificationList)
                        {
                            int sid = goods_SpecificationRepository.Insert(new RB_Goods_Specification()
                            {
                                CreateDate = demodel.CreateDate,
                                EnabledImage = item.EnabledImage,
                                GoodsId = Id,
                                Id = 0,
                                MallBaseId = demodel.MallBaseId,
                                Name = item.Name,
                                Sort = item.Sort,
                                Status = 0,
                                TenantId = demodel.TenantId
                            }, trans);
                            if (sid > 0)
                            {
                                foreach (var qitem in item.SpecificationValueList)
                                {
                                    goods_SpecificationValueRepository.Insert(new RB_Goods_SpecificationValue()
                                    {
                                        CreateDate = demodel.CreateDate,
                                        GoodsId = Id,
                                        Id = 0,
                                        Image = qitem.Image,
                                        MallBaseId = demodel.MallBaseId,
                                        Name = qitem.Name,
                                        Sort = qitem.Sort,
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        SpecificationId = sid
                                    }, trans);
                                }
                            }
                        }
                        foreach (var item in demodel.SpecificationPriceList)
                        {
                            goods_SpecificationPriceRepository.Insert(new RB_Goods_SpecificationPrice()
                            {
                                CreateDate = demodel.CreateDate,
                                GoodsId = Id,
                                Id = 0,
                                GoodsNumbers = item.GoodsNumbers,
                                GoodsWeight = item.GoodsWeight,
                                InventoryNum = item.InventoryNum,
                                MallBaseId = demodel.MallBaseId,
                                SellingPrice = item.SellingPrice,
                                SpecificationSort = item.SpecificationSort,
                                Status = 0,
                                TenantId = demodel.TenantId,
                                UpdateDate = demodel.UpdateDate
                            }, trans);
                        }
                    }
                    //插入区域
                    foreach (var item in demodel.AreaList)
                    {
                        goods_AreaRepository.Insert(new RB_Goods_Area()
                        {
                            AreaId = item.AreaId,
                            AreaType = item.AreaType,
                            CreateDate = demodel.CreateDate,
                            GoodsId = Id,
                            Id = 0,
                            MallBaseId = demodel.MallBaseId,
                            Status = 0,
                            TenantId = demodel.TenantId
                        }, trans);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetGoodsImportInfo");
                return false;
            }
        }

        /// <summary>
        /// unicode 解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string FromUnicodeString(string str)
        {
            //最直接的方法Regex.Unescape(str);
            StringBuilder strResult = new StringBuilder();
            if (!string.IsNullOrEmpty(str) && str.Contains("\\u"))
            {
                string[] strlist = str.Replace("\\", "").Split('u');
                try
                {
                    for (int i = 1; i < strlist.Length; i++)
                    {
                        int charCode = Convert.ToInt32(strlist[i], 16);
                        strResult.Append((char)charCode);
                    }
                }
                catch (FormatException)
                {
                    return Regex.Unescape(str);
                }
                return strResult.ToString();
            }
            return str;
        }

        #endregion

        #region 同步粉象商品规格佣金
        /// <summary>
        /// 同步粉象佣金
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SyncGoodsSpecificationCommission(int tenantId, int mallBaseId)
        {
            var goodsList = goodsRepository.GetSingleList(new RB_Goods_Extend() { TenantId = tenantId, MallBaseId = mallBaseId });
            if (goodsList.Any())
            {
                //查询所有的分销价格
                string goodsIds = string.Join(",", goodsList.Select(x => x.Id));
                var dclist = goods_DistributionCommissionRepository.GetList(new RB_Goods_DistributionCommission_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                //查询所有的规格价格
                var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });

                foreach (var item in goodsList)
                {
                    if (item.SeparateDistribution == 1 && item.SeparateDistributionMoneyType == 2)
                    {
                        var dc1list = dclist.Where(x => x.GoodsId == item.Id).ToList();
                        if (item.IsCustomSpecification == 1)
                        {
                            var sp1list = splist.Where(x => x.GoodsId == item.Id).ToList();
                            if (item.SeparateDistributionType == 1)
                            {
                                //普通设置  直接查 分销商等级的 返佣和
                                var dcmodel = dc1list.Where(x => x.DistributorGrade == 74).FirstOrDefault();
                                decimal TotalMoney = (dcmodel.OneCommission ?? 0) + (dcmodel.TwoCommission ?? 0) + (dcmodel.ThreeCommission ?? 0);
                                foreach (var qitem in sp1list)
                                {
                                    //每个规格都设置为这么多fanyong 
                                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_SpecificationPrice.Commission),TotalMoney}
                                    };
                                    if (qitem.CostMoney <= 0)
                                    {
                                        keyValues.Add(nameof(RB_Goods_SpecificationPrice.CostMoney), item.CostPrice ?? 0);
                                    }
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                              FiledValue=qitem.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    goods_SpecificationPriceRepository.Update(keyValues, wheres);
                                }
                            }
                            else
                            {
                                //详细设置咯  对比规格更新
                                foreach (var qitem in dc1list.Where(x => x.DistributorGrade == 74))
                                {
                                    decimal TotalMoney = (qitem.OneCommission ?? 0) + (qitem.TwoCommission ?? 0) + (qitem.ThreeCommission ?? 0);

                                    var spmodel = sp1list.Where(x => x.SpecificationSort == qitem.SpecificationSort).FirstOrDefault();
                                    if (spmodel != null)
                                    {
                                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_SpecificationPrice.Commission),TotalMoney}
                                        };
                                        if (spmodel.CostMoney <= 0)
                                        {
                                            keyValues.Add(nameof(RB_Goods_SpecificationPrice.CostMoney), item.CostPrice ?? 0);
                                        }
                                        List<WhereHelper> wheres = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                                  FiledValue=spmodel.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        goods_SpecificationPriceRepository.Update(keyValues, wheres);
                                    }
                                }
                            }
                        }
                        else
                        {
                            //没有自定义规格  直接弄主表返佣金额
                            var dcmodel = dc1list.Where(x => x.DistributorGrade == 74).FirstOrDefault();
                            decimal TotalMoney = (dcmodel.OneCommission ?? 0) + (dcmodel.TwoCommission ?? 0) + (dcmodel.ThreeCommission ?? 0);
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Goods.Commission),TotalMoney}
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                        FiledName=nameof(RB_Goods.Id),
                                        FiledValue=item.Id,
                                        OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goodsRepository.Update(keyValues, wheres);
                        }
                    }
                    else
                    {
                        //只更新成本
                        if (item.IsCustomSpecification == 1)
                        {
                            var sp1list = splist.Where(x => x.GoodsId == item.Id).ToList();
                            foreach (var qitem in sp1list)
                            {
                                if (qitem.CostMoney <= 0)
                                {
                                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_SpecificationPrice.CostMoney), item.CostPrice ?? 0}
                                    };
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                              FiledValue=qitem.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    goods_SpecificationPriceRepository.Update(keyValues, wheres);
                                }
                            }
                        }
                    }
                }
            }

            return true;
        }
        #endregion

        #region 分销商


        /// <summary>
        /// 获取公司列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Member_User_Extend> GetCompanyUserList(RB_Member_User_Extend dmodel)
        {
            return member_UserRepository.GetCompanyUserList(dmodel);
        }



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

        /// <summary>
        /// 获取VIP等级信息
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetAppletVipGradeInfo(int tenantId, int mallBaseId)
        {
            var disModel = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, IsGuest = 3 }).FirstOrDefault();
            if (disModel != null)
            {
                return new
                {
                    Status = 1,
                    VIPModel = new
                    {
                        disModel.Id,
                        disModel.Grade,
                        disModel.GradeName
                    }
                };
            }
            else
            {
                return new
                {
                    Status = 2,
                    VIPModel = new { }
                };
            }
        }
        #endregion

        #region 分类包邮规则信息
        /// <summary>
        /// 物流规则列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_FreeShipping_Extend> GetFreeShippingListByCategoryIds(RB_FreeShipping_Extend query)
        {
            return freeShippingRepository.GetFreeShippingListByCategoryIds(query);
        }
        #endregion

        #region 根据订单状态获取订单信息
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Order_Extend> GetOrderListByOrderStatus(RB_Goods_Order_Extend dmodel)
        {
            return goods_OrderRepository.GetOrderListByOrderStatus(dmodel);
        }
        #endregion
    }
}
