/// <summary>
        /// 商品搜索
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public SearchProductResult SearchProduct(SearchProductQuery query)
        {
            //string selComments = "s.Comments";
            //以前评论条数是搜索表里的 统计的所有评论条数
            string selComments = "(SELECT COUNT(*) FROM Mall_productcomment pc WHERE pc.productid=s.productid AND pc.Ishidden=0) as Comments";//搜索这里评论数获取排除隐藏的条数

            SearchProductResult result = new SearchProductResult();
            string countsql            = "select count(1) from Mall_searchproduct s  ";
            string sql = "select (p.SaleCounts+ IFNULL(p.VirtualSaleCounts,0)) as  SaleCount, s.ProductId,s.ProductName,s.SalePrice,s.ImagePath,s.ShopId,s.ShopName,s.ThirdCateId,p.DisplaySequence,p.ShopDisplaySequence,p.ProductType,IFNULL(p.VirtualSaleCounts,0) as  VirtualSaleCounts,p.MinSalePrice," + selComments + "   from Mall_searchproduct s ";

            var where = new Sql();
            GetSearchWhere(query, where);
            var order = new Sql();

            GetSearchOrder(query, order);
            string index = GetForceIndex(query);
            string page  = GetSearchPage(query);

            index       += string.Format(" left join Mall_Product p on p.Id=s.ProductId  ");//FORCE INDEX要放在join之前
            countsql    += string.Format(" left join Mall_Product p on p.Id=s.ProductId  ");
            result.Data  = DbFactory.Default.Query <ProductView>(string.Concat(sql, index, where.SQL, order.SQL, page), where.Arguments).ToList();
            result.Total = DbFactory.Default.ExecuteScalar <int>(string.Concat(countsql, where.SQL), where.Arguments);

            return(result);
        }
Beispiel #2
0
        public static SearchProductResultLiquidViewModel MapToLiquidView(this SearchProductResult res)
        {
            var products = Mapper.Map <List <ProductLiquidAdapter> >(res.Products);

            return(new SearchProductResultLiquidViewModel()
            {
                Count = res.Count,
                Products = products,
                SearchText = res.SearchText
            });
        }
        /// <summary>
        /// 诊疗项目搜索
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public SearchProductResult SearchAppletProduct(SearchProductQuery query)
        {
            SearchProductResult result = new SearchProductResult();
            DynamicParameters   parms  = new DynamicParameters();
            string countsql            = "select count(1) from himall_searchproducts ps ";
            string sql = "select ps.ProductId,ps.ProductName,ps.SalePrice,ps.ImagePath,ps.ShopId,ps.ShopName,ps.SaleCount,ps.ThirdCateId,ps.Comments,pt.HasSKU,pt.MinSalePrice,(select id from Himall_SKUs where ProductId=ps.ProductId order by id desc limit 1) as SkuId,IFNULL((select Sum(Quantity) from Himall_ShoppingCarts cs where cs.ProductId=ps.ProductId),0) as cartquantity  from himall_searchproducts ps left join Himall_Products pt on ps.ProductId=pt.Id ";

            string where = GetAppletSearchWhere(query, parms);
            string order = GetAppletSearchOrder(query);
            string index = GetForceIndex(query);
            string page  = GetSearchPage(query);

            using (MySqlConnection conn = new MySqlConnection(Connection.ConnectionString))
            {
                result.Data  = conn.Query <ProductView>(string.Concat(sql, index, where, order, page), parms).ToList();
                result.Total = int.Parse(conn.ExecuteScalar(string.Concat(countsql, where), parms).ToString());
            }

            return(result);
        }
        /// <summary>
        /// 诊疗项目搜索
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public SearchProductResult SearchProduct(SearchProductQuery query)
        {
            SearchProductResult result = new SearchProductResult();
            DynamicParameters   parms  = new DynamicParameters();
            string countsql            = "select count(1) from himall_searchproducts ";
            string sql = "select ProductId,ProductName,SalePrice,ImagePath,ShopId,ShopName,SaleCount,ThirdCateId,Comments from himall_searchproducts ";

            string where = GetSearchWhere(query, parms);
            string order = GetSearchOrder(query);
            string index = GetForceIndex(query);
            string page  = GetSearchPage(query);

            using (MySqlConnection conn = new MySqlConnection(Connection.ConnectionString))
            {
                result.Data  = conn.Query <ProductView>(string.Concat(sql, index, where, order, page), parms).ToList();
                result.Total = int.Parse(conn.ExecuteScalar(string.Concat(countsql, where), parms).ToString());
            }

            return(result);
        }
Beispiel #5
0
        public async Task <SearchProductResult> Search(string searchText)
        {
            if (string.IsNullOrEmpty(searchText))
            {
                return(new SearchProductResult());
            }

            var products = _accessManager.Filter(_productDataService.Query.Include(x => x.Pictures).Where(x =>
                                                                                                          x.Title.Contains(searchText) ||
                                                                                                          x.Tags.Any(t => t.Title.Contains(searchText)) ||
                                                                                                          x.PrimaryCategory.Title.Contains(searchText))).OrderByDescending(x => x.PublishDateTime);

            var retVal = new SearchProductResult
            {
                Count      = await products.LongCountAsync(),
                Products   = await products.ToListAsync(),
                SearchText = searchText
            };

            retVal.Products.ForEach(
                FetchAvalailbleDiscounts);

            return(retVal);
        }
        public ActionResult SearchAd(string sid, long cid = 0, string keywords = "", int pageNo = 1, decimal startPrice = 0, decimal endPrice = decimal.MaxValue)
        {
            int      pageSize = 40;
            long     shopId   = 0;
            ShopInfo shopObj  = null;

            endPrice   = endPrice <= 0 || endPrice < startPrice ? decimal.MaxValue : endPrice;
            startPrice = startPrice < 0 ? 0 : startPrice;

            //shopId 不是数字
            if (!long.TryParse(sid, out shopId))
            {
                return(RedirectToAction("Error404", "Error", new { area = "Web" }));
                //404 页面
            }

            //店铺Id不存在
            shopObj = _iShopService.GetShop(shopId);
            if (null == shopObj)
            {
                return(RedirectToAction("Error404", "Error", new { area = "Web" }));
                //404 页面
            }
            #region 初始化Model

            ShopHomeModel model = new ShopHomeModel
            {
                HotAttentionProducts = new List <HotProductInfo>(),
                HotSaleProducts      = new List <HotProductInfo>(),
                Floors       = new List <ShopHomeFloor>(),
                Navignations = new List <BannerInfo>(),
                Shop         = new ShopInfoModel(),
                ShopCategory = new List <CategoryJsonModel>(),
                Slides       = new List <SlideAdInfo>(),
                Logo         = ""
            };

            #endregion

            #region 导航和3个推荐商品

            //导航
            model.Navignations = _iNavigationService.GetSellerNavigations(shopObj.Id).ToList();

            //banner和3个推荐商品
            model.ImageAds = _iSlideAdsService.GetImageAds(shopObj.Id).OrderBy(item => item.Id).ToList();

            model.Slides = _iSlideAdsService.GetSlidAds(shopObj.Id, SlideAdInfo.SlideAdType.ShopHome).ToList();

            #endregion

            #region 店铺分类

            var categories = _iShopCategoryService.GetShopCategory(shopObj.Id).ToArray();
            foreach (var main in categories.Where(s => s.ParentCategoryId == 0))
            {
                var topC = new CategoryJsonModel()
                {
                    Name        = main.Name,
                    Id          = main.Id.ToString(),
                    SubCategory = new List <SecondLevelCategory>()
                };
                foreach (var secondItem in categories.Where(s => s.ParentCategoryId == main.Id))
                {
                    var secondC = new SecondLevelCategory()
                    {
                        Name = secondItem.Name,
                        Id   = secondItem.Id.ToString(),
                    };

                    topC.SubCategory.Add(secondC);
                }
                model.ShopCategory.Add(topC);
            }

            #endregion

            #region 店铺信息

            var mark = ShopServiceMark.GetShopComprehensiveMark(shopObj.Id);
            model.Shop.Name              = shopObj.ShopName;
            model.Shop.CompanyName       = shopObj.CompanyName;
            model.Shop.Id                = shopObj.Id;
            model.Shop.PackMark          = mark.PackMark;
            model.Shop.ServiceMark       = mark.ServiceMark;
            model.Shop.ComprehensiveMark = mark.ComprehensiveMark;
            model.Shop.Phone             = shopObj.CompanyPhone;
            model.Shop.Address           = _iRegionService.GetFullName(shopObj.CompanyRegionId);
            model.Logo = shopObj.Logo;
            #endregion

            SearchProductQuery query = new SearchProductQuery()
            {
                ShopId         = long.Parse(sid),
                ShopCategoryId = cid,
                Keyword        = keywords,
                StartPrice     = startPrice,
                EndPrice       = endPrice,
                PageNumber     = pageNo,
                PageSize       = pageSize
            };

            SearchProductResult result = _iSearchProductService.SearchProduct(query);

            model.Products = result.Data;

            //#endregion

            #region 热门销售

            var sale = _iProductService.GetHotSaleProduct(shopObj.Id, 5);
            if (sale != null)
            {
                foreach (var item in sale)
                {
                    model.HotSaleProducts.Add(new HotProductInfo
                    {
                        ImgPath   = item.ImagePath,
                        Name      = item.ProductName,
                        Price     = item.MinSalePrice,
                        Id        = item.Id,
                        SaleCount = (int)item.SaleCounts
                    });
                }
            }

            #endregion


            #region 热门关注

            var hot = _iProductService.GetHotConcernedProduct(shopObj.Id, 5).ToList();
            if (hot != null)
            {
                foreach (var item in hot)
                {
                    model.HotAttentionProducts.Add(new HotProductInfo
                    {
                        ImgPath   = item.ImagePath,
                        Name      = item.ProductName,
                        Price     = item.MinSalePrice,
                        Id        = item.Id,
                        SaleCount = (int)item.ConcernedCount
                    });
                }
            }
            #endregion

            #region 获取店铺的评价统计
            var shopStatisticOrderComments = _iShopService.GetShopStatisticOrderComments(shopId);

            var productAndDescription = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.ProductAndDescription).FirstOrDefault();
            var sellerServiceAttitude = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerServiceAttitude).FirstOrDefault();
            var sellerDeliverySpeed   = shopStatisticOrderComments.Where(c => c.CommentKey ==
                                                                         StatisticOrderCommentsInfo.EnumCommentKey.SellerDeliverySpeed).FirstOrDefault();

            var productAndDescriptionPeer = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.ProductAndDescriptionPeer).FirstOrDefault();
            var sellerServiceAttitudePeer = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerServiceAttitudePeer).FirstOrDefault();
            var sellerDeliverySpeedPeer   = shopStatisticOrderComments.Where(c => c.CommentKey ==
                                                                             StatisticOrderCommentsInfo.EnumCommentKey.SellerDeliverySpeedPeer).FirstOrDefault();

            var productAndDescriptionMax = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.ProductAndDescriptionMax).FirstOrDefault();
            var productAndDescriptionMin = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.ProductAndDescriptionMin).FirstOrDefault();

            var sellerServiceAttitudeMax = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerServiceAttitudeMax).FirstOrDefault();
            var sellerServiceAttitudeMin = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerServiceAttitudeMin).FirstOrDefault();

            var sellerDeliverySpeedMax = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerDeliverySpeedMax).FirstOrDefault();
            var sellerDeliverySpeedMin = shopStatisticOrderComments.Where(c => c.CommentKey == StatisticOrderCommentsInfo.EnumCommentKey.SellerDeliverySpeedMin).FirstOrDefault();

            decimal defaultValue = 5;
            //宝贝与描述
            if (productAndDescription != null && productAndDescriptionPeer != null)
            {
                ViewBag.ProductAndDescription     = productAndDescription.CommentValue;
                ViewBag.ProductAndDescriptionPeer = productAndDescriptionPeer.CommentValue;
                ViewBag.ProductAndDescriptionMin  = productAndDescriptionMin.CommentValue;
                ViewBag.ProductAndDescriptionMax  = productAndDescriptionMax.CommentValue;
            }
            else
            {
                ViewBag.ProductAndDescription     = defaultValue;
                ViewBag.ProductAndDescriptionPeer = defaultValue;
                ViewBag.ProductAndDescriptionMin  = defaultValue;
                ViewBag.ProductAndDescriptionMax  = defaultValue;
            }
            //卖家服务态度
            if (sellerServiceAttitude != null && sellerServiceAttitudePeer != null)
            {
                ViewBag.SellerServiceAttitude     = sellerServiceAttitude.CommentValue;
                ViewBag.SellerServiceAttitudePeer = sellerServiceAttitudePeer.CommentValue;
                ViewBag.SellerServiceAttitudeMax  = sellerServiceAttitudeMax.CommentValue;
                ViewBag.SellerServiceAttitudeMin  = sellerServiceAttitudeMin.CommentValue;
            }
            else
            {
                ViewBag.SellerServiceAttitude     = defaultValue;
                ViewBag.SellerServiceAttitudePeer = defaultValue;
                ViewBag.SellerServiceAttitudeMax  = defaultValue;
                ViewBag.SellerServiceAttitudeMin  = defaultValue;
            }
            //卖家发货速度
            if (sellerDeliverySpeedPeer != null && sellerDeliverySpeed != null)
            {
                ViewBag.SellerDeliverySpeed     = sellerDeliverySpeed.CommentValue;
                ViewBag.SellerDeliverySpeedPeer = sellerDeliverySpeedPeer.CommentValue;
                ViewBag.SellerDeliverySpeedMax  = sellerDeliverySpeedMax.CommentValue;
                ViewBag.sellerDeliverySpeedMin  = sellerDeliverySpeedMin.CommentValue;
            }
            else
            {
                ViewBag.SellerDeliverySpeed     = defaultValue;
                ViewBag.SellerDeliverySpeedPeer = defaultValue;
                ViewBag.SellerDeliverySpeedMax  = defaultValue;
                ViewBag.sellerDeliverySpeedMin  = defaultValue;
            }
            #endregion

            #region 分页控制
            PagingInfo info = new PagingInfo
            {
                CurrentPage  = pageNo,
                ItemsPerPage = pageSize,
                TotalItems   = result.Total
            };
            ViewBag.pageInfo = info;
            #endregion
            var categoryName = string.Empty;
            if (keywords == string.Empty)
            {
                if (cid != 0)
                {
                    var category = _iShopCategoryService.GetCategory(cid) ?? new ShopCategoryInfo()
                    {
                    };
                    categoryName = category.Name;
                }
            }
            ViewBag.CategoryName   = categoryName;
            ViewBag.Keyword        = keywords;
            ViewBag.cid            = cid;
            ViewBag.BrowsedHistory = BrowseHistrory.GetBrowsingProducts(13, CurrentUser == null ? 0 : CurrentUser.Id);

            //补充当前店铺红包功能
            ViewBag.isShopPage     = true;
            ViewBag.CurShopId      = shopId;
            TempData["isShopPage"] = true;
            TempData["CurShopId"]  = shopId;
            //统计店铺访问人数
            StatisticApplication.StatisticShopVisitUserCount(shopId);
            return(View(model));
        }
        // GET: Web/Search/SearchAd
        /// <summary>
        ///  商品搜索页面
        /// </summary>
        /// <param name="keywords">搜索关键字</param>
        /// <param name="cid">分类ID</param>
        /// <param name="b_id">品牌ID</param>
        /// <param name="a_id">属性ID, 表现形式:attrId_attrValueId</param>
        /// <param name="orderKey">序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间)</param>
        /// <param name="orderType">排序方式(1:升序,2:降序)</param>
        /// <param name="pageNo">页码</param>
        /// <param name="pageSize">每页显示数据量</param>
        /// <returns></returns>
        public ActionResult SearchAd(
            string keywords = "", /* 搜索关键字 */
            long cid        = 0,  /* 分类ID */
            long b_id       = 0,  /* 品牌ID */
            string a_id     = "", /* 属性值ID, 表现形式:valueid,valueid */
            int orderKey    = 1,  /* 排序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间) */
            int orderType   = 1,  /* 排序方式(1:升序,2:降序) */
            int pageNo      = 1,  /*页码*/
            int pageSize    = 60  /*每页显示数据量*/
            )
        {
            try
            {
                if (string.IsNullOrEmpty(keywords) && cid <= 0 && b_id <= 0 && a_id == "")
                {
                    keywords = Application.SiteSettingApplication.GetSiteSettings().Keyword;
                }

                #region 初始化查询Model
                SearchProductQuery model = new SearchProductQuery();
                model.ShopId  = 0;
                model.BrandId = b_id;
                if (cid != 0)
                {
                    var catelist = _iCategoryService.GetCategories();
                    var cate     = catelist.FirstOrDefault(r => r.Id == cid);
                    if (cate.Depth == 1)
                    {
                        model.FirstCateId = cid;
                    }
                    else if (cate.Depth == 2)
                    {
                        model.SecondCateId = cid;
                    }
                    else if (cate.Depth == 3)
                    {
                        model.ThirdCateId = cid;
                    }
                }
                model.AttrValIds = a_id.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                model.Keyword    = keywords;
                model.OrderKey   = orderKey;
                model.OrderType  = orderType == 1;
                model.PageNumber = pageNo;
                model.PageSize   = pageSize;
                #endregion
                SearchProductResult result = _iSearchProductService.SearchProduct(model);
                int total = result.Total;

                //当查询的结果少于一页时用like进行补偿
                if (result.Total < pageSize)
                {
                    model.IsLikeSearch = true;
                    SearchProductResult result2 = _iSearchProductService.SearchProduct(model);
                    var idList1 = result.Data.Select(a => a.ProductId).ToList();
                    var nresult = result2.Data.Where(a => !idList1.Contains(a.ProductId)).ToList();
                    if (nresult.Count > 0)
                    {
                        result.Total += nresult.Count;
                        result.Data.AddRange(nresult);
                    }
                }
                if (result.Total == 0)
                {
                    ViewBag.BrowsedHistory = BrowseHistrory.GetBrowsingProducts(13, CurrentUser == null ? 0 : CurrentUser.Id);
                    var    category     = _iCategoryService.GetCategory(model.ThirdCateId);
                    string categoryName = category == null ? string.Empty : category.Name;
                    var    brand        = _iBrandService.GetBrand(b_id) ?? new BrandInfo();
                    string bname        = brand == null ? "" : brand.Name;
                    ViewBag.categoryName = categoryName;
                    ViewBag.bName        = bname;
                }
                total = result.Total;

                if (Core.HimallIO.GetHimallIO().GetType().FullName.Equals("Himall.Strategy.OSS"))
                {
                    ViewBag.IsOss = true;
                }
                else
                {
                    ViewBag.IsOss = false;
                }

                ViewBag.keywords  = model.Keyword;
                ViewBag.cid       = cid;
                ViewBag.b_id      = b_id;
                ViewBag.a_id      = a_id;
                ViewBag.orderKey  = orderKey;
                ViewBag.orderType = orderType;

                #region 分页控制
                PagingInfo info = new PagingInfo
                {
                    CurrentPage  = model.PageNumber,
                    ItemsPerPage = pageSize,
                    TotalItems   = total
                };
                ViewBag.pageInfo = info;
                #endregion


                return(View(result.Data));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Beispiel #8
0
        // GET: Web/Search/SearchAd
        /// <summary>
        ///  商品搜索页面
        /// </summary>
        /// <param name="keywords">搜索关键字</param>
        /// <param name="cid">分类ID</param>
        /// <param name="b_id">品牌ID</param>
        /// <param name="a_id">属性ID, 表现形式:attrId_attrValueId</param>
        /// <param name="orderKey">序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间)</param>
        /// <param name="orderType">排序方式(1:升序,2:降序)</param>
        /// <param name="pageNo">页码</param>
        /// <param name="pageSize">每页显示数据量</param>
        /// <returns></returns>
        public ActionResult SearchAd(
            string keywords = "", /* 搜索关键字 */
            long cid        = 0,  /* 分类ID */
            long b_id       = 0,  /* 品牌ID */
            string a_id     = "", /* 属性值ID, 表现形式:valueid,valueid */
            int orderKey    = 1,  /* 排序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间) */
            int orderType   = 1,  /* 排序方式(1:升序,2:降序) */
            int pageNo      = 1,  /*页码*/
            int pageSize    = 60  /*每页显示数据量*/
            )
        {
            try
            {
                var  siteSetingInfo = SiteSettingApplication.SiteSettings;
                bool isShow         = siteSetingInfo.ProductSaleCountOnOff == 1;
                if (string.IsNullOrEmpty(keywords) && cid <= 0 && b_id <= 0 && a_id == "")
                {
                    keywords = siteSetingInfo.Keyword;
                }

                #region 初始化查询Model
                SearchProductQuery model = new SearchProductQuery();
                model.ShopId  = 0;
                model.BrandId = b_id;
                if (cid != 0)
                {
                    var catelist = _iCategoryService.GetCategories();
                    var cate     = catelist.FirstOrDefault(r => r.Id == cid);
                    if (cate != null)
                    {
                        if (cate.Depth == 1)
                        {
                            model.FirstCateId = cid;
                        }
                        else if (cate.Depth == 2)
                        {
                            model.SecondCateId = cid;
                        }
                        else if (cate.Depth == 3)
                        {
                            model.ThirdCateId = cid;
                        }
                        ViewBag.pageTitle = cate.Name;
                    }
                }
                model.AttrValIds = a_id.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                model.Keyword    = keywords;
                model.OrderKey   = orderKey;
                model.OrderType  = orderType == 1;
                model.PageNumber = pageNo;
                model.PageSize   = pageSize;
                #endregion
                SearchProductResult result = _iSearchProductService.SearchProduct(model);
                int total = result.Total;

                //当查询的结果少于一页时用like进行补偿
                if (result.Total < pageSize)
                {
                    model.IsLikeSearch = true;
                    SearchProductResult result2 = _iSearchProductService.SearchProduct(model);
                    var idList1 = result.Data.Select(a => a.ProductId).ToList();
                    var nresult = result2.Data.Where(a => !idList1.Contains(a.ProductId)).ToList();
                    if (nresult.Count > 0)
                    {
                        result.Total += nresult.Count;
                        result.Data.AddRange(nresult);
                    }
                    //补充数据后,重新排序
                    Func <IEnumerable <ProductView>, IOrderedEnumerable <ProductView> > orderby     = null;
                    Func <IEnumerable <ProductView>, IOrderedEnumerable <ProductView> > orderByDesc = null;
                    switch (model.OrderKey)
                    {
                    case 2:
                        //order.Append(" ORDER BY SaleCount ");
                        orderby     = e => e.OrderBy(p => p.SaleCount + TypeHelper.ObjectToInt(p.VirtualSaleCounts));
                        orderByDesc = e => e.OrderByDescending(p => p.SaleCount + TypeHelper.ObjectToInt(p.VirtualSaleCounts));
                        break;

                    case 3:
                        //order.Append(" ORDER BY SalePrice ");
                        orderby     = e => e.OrderBy(p => p.SalePrice);
                        orderByDesc = e => e.OrderByDescending(p => p.SalePrice);
                        break;

                    case 4:
                        //order.Append(" ORDER BY Comments ");
                        orderby     = e => e.OrderBy(p => p.Comments);
                        orderByDesc = e => e.OrderByDescending(p => p.Comments);
                        break;

                    default:
                        //order.Append(" ORDER BY Id ");
                        //按最新的排序规则作为默认排序【序号越大,在前台展示的商品越靠前,序号一致时,优先销量排前,销量一致时,优先上架时间排前】
                        //orderby = e => e.OrderBy(p => p.ProductId);
                        if (isShow)
                        {    //底层已经将虚拟销量累加到销量中
                            orderByDesc = e => e.OrderByDescending(p => p.DisplaySequence).ThenByDescending(p => p.SaleCount).ThenByDescending(p => p.ProductId);
                        }
                        else
                        {
                            orderByDesc = e => e.OrderByDescending(p => p.DisplaySequence).ThenByDescending(p => p.ProductId);
                        }
                        break;
                    }
                    if (model.OrderKey > 1)
                    {
                        if (model.OrderType)
                        {
                            result.Data = orderby(result.Data).ToList();
                        }
                        else
                        {
                            result.Data = orderByDesc(result.Data).ToList();
                        }
                    }
                    else
                    {
                        result.Data = orderByDesc(result.Data).ToList();
                    }
                }
                if (result.Total == 0)
                {
                    ViewBag.BrowsedHistory = BrowseHistrory.GetBrowsingProducts(13, CurrentUser == null ? 0 : CurrentUser.Id);
                    var    category     = _iCategoryService.GetCategory(model.ThirdCateId);
                    string categoryName = category == null ? string.Empty : category.Name;
                    var    brand        = _iBrandService.GetBrand(b_id) ?? new Entities.BrandInfo();
                    string bname        = brand == null ? "" : brand.Name;
                    ViewBag.categoryName = categoryName;
                    ViewBag.bName        = bname;
                }
                total = result.Total;

                //补商品状态
                foreach (var item in result.Data)
                {
                    var _pro = _iProductService.GetProduct(item.ProductId);
                    var skus = ProductManagerApplication.GetSKUs(item.ProductId);
                    if (_pro == null || skus == null)
                    {
                        continue;
                    }
                    if (_pro.SaleStatus == Entities.ProductInfo.ProductSaleStatus.OnSale && _pro.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited)
                    {
                        item.ShowStatus = 0;
                        if (skus.Sum(d => d.Stock) < 1)
                        {
                            item.ShowStatus = 2;
                        }
                    }
                    else
                    {
                        if (_pro.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited && _pro.SaleStatus == Entities.ProductInfo.ProductSaleStatus.InStock)
                        {
                            item.ShowStatus = 3;
                        }
                        else
                        {
                            item.ShowStatus = 1;
                        }
                    }
                }

                if (Core.HimallIO.GetHimallIO().GetType().FullName.Equals("Himall.Strategy.OSS"))
                {
                    ViewBag.IsOss = true;
                }
                else
                {
                    ViewBag.IsOss = false;
                }

                ViewBag.keywords  = model.Keyword;
                ViewBag.cid       = cid;
                ViewBag.b_id      = b_id;
                ViewBag.a_id      = a_id;
                ViewBag.orderKey  = orderKey;
                ViewBag.orderType = orderType;

                #region 分页控制
                PagingInfo info = new PagingInfo
                {
                    CurrentPage  = model.PageNumber,
                    ItemsPerPage = pageSize,
                    TotalItems   = total
                };
                ViewBag.pageInfo = info;
                #endregion
                ViewBag.isSaleCountOnOff = isShow;

                return(View(result.Data));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Beispiel #9
0
        /// <summary>
        /// 抓取单个商品
        /// </summary>
        /// <param name="searchRst"></param>
        /// <returns></returns>
        bool getProduct(SearchProductResult searchRst)
        {
            if (searchRst == null)
            {
                return(false);
            }

            #region//TODO 抓取商品数据
            var detailsHtml = WebClientHelper.GetContent(searchRst.Link, detailsOption.Encoding);

            if (string.IsNullOrWhiteSpace(detailsHtml))
            {
                return(false);
            }

            //商品装载数据
            ProductSetupResult setup = null;
            Regex setupRegex         = new Regex(detailsOption.SetupRegex.Pattern, RegexOptions.IgnoreCase);
            Match setupMatch         = setupRegex.Match(detailsHtml);
            if (setupMatch != null)
            {
                string setupData = setupMatch.Groups[detailsOption.SetupRegex.GroupName].Value;
                setup = JsonConvert.DeserializeObject <ProductSetupResult>(setupData);
            }

            if (setup == null || setup.ItemDO == null)
            {
                return(false);
            }

            //定义商品ID
            long productId = Tools.NewId();

            //图片
            Dictionary <string, string> proImgDic = new Dictionary <string, string>();//key为“商品ID_v序号”组成,value为采集的图片地址
            Regex imagesRegex = new Regex(detailsOption.ImagesDataRegex.Pattern, RegexOptions.IgnoreCase);
            Match imagesMatch = imagesRegex.Match(detailsHtml);
            if (imagesMatch != null)
            {
                string imagesData = imagesMatch.Groups[detailsOption.ImagesDataRegex.GroupName].Value;

                Regex singleImgRegex = new Regex(detailsOption.SingleImageRegex.Pattern, RegexOptions.IgnoreCase);

                MatchCollection singleImgMatches = singleImgRegex.Matches(imagesData);

                Regex removeRegex = new Regex(detailsOption.ImageSrcRemoveRegex.Pattern, RegexOptions.IgnoreCase);

                int proIdx = 0;
                foreach (Match m in singleImgMatches)
                {
                    string src = m.Groups[detailsOption.SingleImageRegex.GroupName].Value.GetFullLink();

                    //移除缩略图标识,保留原图地址
                    src = removeRegex.Replace(src, "");

                    proImgDic.Add($"{setup.ItemDO.ItemId}_v{++proIdx}", src);
                }
            }

            //商品描述
            string desc      = null;
            var    descHtml  = WebClientHelper.GetContent(setup.Api.DescUrl, detailsOption.Encoding);
            Regex  descRegex = new Regex(detailsOption.DescRegex.Pattern, RegexOptions.IgnoreCase);
            Match  descMatch = descRegex.Match(descHtml);
            if (descMatch != null)
            {
                desc = descMatch.Groups[detailsOption.DescRegex.GroupName].Value;
            }

            //描述中的图片
            Dictionary <string, string> descImgDic = new Dictionary <string, string>();//key为“商品ID_d序号”组成,value为采集的图片地址
            Regex           descImgRegex           = new Regex(detailsOption.DescImageRegex.Pattern, RegexOptions.IgnoreCase);
            MatchCollection descImgMatches         = descImgRegex.Matches(desc);
            int             descIdx = 0;
            foreach (Match m in descImgMatches)
            {
                string src = m.Groups[detailsOption.DescImageRegex.GroupName].Value;

                //当前图片标识
                string currentImgTag = $"{setup.ItemDO.ItemId}_d{++descIdx}";

                //将详情描述中的当前图片地址用标识符替换以占位,待上传后用新地址替换
                desc = desc.Replace(src, currentImgTag);

                descImgDic.Add(currentImgTag, src.GetFullLink());
            }
            #endregion

            //下载商品展示图
            proImgDic = WebClientHelper.DownloadFile(proImgDic, uploadOption.VisitAddress, uploadOption.SaveDirectory);

            //下载商品描述图
            descImgDic = WebClientHelper.DownloadFile(descImgDic, uploadOption.VisitAddress, uploadOption.SaveDirectory);

            //将描述中的图更换为上传后的地址
            foreach (var img in descImgDic)
            {
                //将描述中的标识符替换为上传后的图片地址
                desc = desc.Replace(img.Key, img.Value);
            }

            #region // 解析成产品库数据

            string title = setup.ItemDO.Title;

            if (detailsOption.ReplaceItems.Any())
            {
                foreach (var rep in detailsOption.ReplaceItems)
                {
                    title = title.Replace(rep.SourceText, rep.ReplaceTo);
                    desc  = desc.Replace(rep.SourceText, rep.ReplaceTo);
                }
            }

            //商品
            Product product = new Product
            {
                BrandID         = long.Parse(setup.ItemDO.BrandId),
                CategoryID      = searchRst.CategoryId,
                CreateTime      = DateTime.Now,
                Intro           = desc,
                IsDelete        = false,
                mainPic         = proImgDic.Values.FirstOrDefault(),
                Path            = searchRst.Link,
                Pics            = string.Join(",", proImgDic.Values),
                ProductID       = productId,
                Properties      = string.Empty,
                Source          = collectorType,
                Title           = title,
                UpdateTime      = DateTime.Now,
                Weight          = float.Parse(setup.ItemDO.Weight),
                SourceProductID = long.Parse(setup.ItemDO.ItemId)
            };

            //SKU
            ProductSku sku = new ProductSku
            {
                CreateTime = product.CreateTime,
                IsDelete   = false,
                Name       = product.Title,
                ProductID  = product.ProductID,
                SalePrice  = decimal.Parse(setup.Detail.DefaultItemPrice),
                SkuID      = Tools.NewId(),
                UpdateTime = product.UpdateTime,
                Weight     = product.Weight
            };

            #endregion

            #region // 保存到数据库

            using (var db = new DataContext())
            {
                db.Product.Add(product);
                db.ProductSku.Add(sku);

                return(db.SaveChanges() > 0);
            }

            #endregion
        }
Beispiel #10
0
        private SearchProductResult DoSearch(
            string keywords = "", /* 搜索关键字 */
            long cid        = 0,  /* 分类ID */
            long b_id       = 0,  /* 品牌ID */
            string a_id     = "", /* 属性ID, 表现形式:attrId_attrValueId */
            int orderKey    = 1,  /* 排序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间) */
            int orderType   = 1,  /* 排序方式(1:升序,2:降序) */
            int pageNo      = 1,  /*页码*/
            int pageSize    = 10, /*每页显示数据量*/
            long vshopId    = 0   //店铺ID
            )
        {
            #region 初始化查询Model
            SearchProductQuery model = new SearchProductQuery();
            model.ShopId  = 0;
            model.BrandId = b_id;
            if (cid != 0)
            {
                var catelist = _iCategoryService.GetCategories();
                var cate     = catelist.FirstOrDefault(r => r.Id == cid);
                if (cate != null)
                {
                    if (cate.Depth == 1)
                    {
                        model.FirstCateId = cid;
                    }
                    else if (cate.Depth == 2)
                    {
                        model.SecondCateId = cid;
                    }
                    else if (cate.Depth == 3)
                    {
                        model.ThirdCateId = cid;
                    }
                }
            }

            orderType        = orderKey == 3 ? orderType : 2;
            model.AttrValIds = a_id.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            model.Keyword    = keywords;
            model.OrderKey   = orderKey;
            model.OrderType  = orderType == 1;
            model.PageNumber = pageNo;
            model.PageSize   = pageSize;
            model.VShopId    = vshopId;
            if (!string.IsNullOrWhiteSpace(model.Keyword) && model.Keyword.Length == 1)
            {
                model.IsLikeSearch = true;
            }
            #endregion
            SearchProductResult result = _iSearchProductService.SearchProduct(model);
            int  total          = result.Total;
            var  siteSetingInfo = SiteSettingApplication.SiteSettings;
            bool isShow         = siteSetingInfo != null && siteSetingInfo.ProductSaleCountOnOff == 1;
            //当查询的结果少于一页时用like进行补偿(与PC端同步)
            if (result.Total < pageSize)
            {
                model.IsLikeSearch = true;
                SearchProductResult result2 = _iSearchProductService.SearchProduct(model);
                var idList1 = result.Data.Select(a => a.ProductId).ToList();
                var nresult = result2.Data.Where(a => !idList1.Contains(a.ProductId)).ToList();
                if (nresult.Count > 0)
                {
                    result.Total += nresult.Count;
                    result.Data.AddRange(nresult);
                }
                //补充数据后,重新排序
                Func <IEnumerable <ProductView>, IOrderedEnumerable <ProductView> > orderby     = null;
                Func <IEnumerable <ProductView>, IOrderedEnumerable <ProductView> > orderByDesc = null;
                switch (model.OrderKey)
                {
                case 2:
                    //order.Append(" ORDER BY SaleCount ");
                    orderby     = e => e.OrderBy(p => p.SaleCount + Core.Helper.TypeHelper.ObjectToInt(p.VirtualSaleCounts));
                    orderByDesc = e => e.OrderByDescending(p => p.SaleCount + Core.Helper.TypeHelper.ObjectToInt(p.VirtualSaleCounts));
                    break;

                case 3:
                    //order.Append(" ORDER BY SalePrice ");
                    orderby     = e => e.OrderBy(p => p.SalePrice);
                    orderByDesc = e => e.OrderByDescending(p => p.SalePrice);
                    break;

                case 4:
                    //order.Append(" ORDER BY Comments ");
                    orderby     = e => e.OrderBy(p => p.Comments);
                    orderByDesc = e => e.OrderByDescending(p => p.Comments);
                    break;

                default:
                    //order.Append(" ORDER BY Id ");
                    //orderby = e => e.OrderBy(p => p.ProductId);
                    //orderByDesc = e => e.OrderByDescending(p => p.ProductId);
                    //break;
                    //按最新的排序规则作为默认排序【序号越大,在前台展示的商品越靠前,序号一致时,优先销量排前,销量一致时,优先上架时间排前】
                    if (isShow)
                    {
                        orderByDesc = e => e.OrderByDescending(p => p.DisplaySequence).ThenByDescending(p => p.SaleCount + Core.Helper.TypeHelper.ObjectToInt(p.VirtualSaleCounts)).ThenByDescending(p => p.ProductId);
                    }
                    else
                    {
                        orderByDesc = e => e.OrderByDescending(p => p.DisplaySequence).ThenByDescending(p => p.ProductId);
                    }
                    break;
                }
                if (model.OrderKey > 1)
                {
                    if (model.OrderType)
                    {
                        result.Data = orderby(result.Data).ToList();
                    }
                    else
                    {
                        result.Data = orderByDesc(result.Data).ToList();
                    }
                }
                else
                {
                    result.Data = orderByDesc(result.Data).ToList();
                }
            }
            total = result.Total;
            //补商品状态
            foreach (var item in result.Data)
            {
                var _pro = _iProductService.GetProduct(item.ProductId);
                var skus = _iProductService.GetSKUs(item.ProductId);
                if (_pro == null || skus == null)
                {
                    continue;
                }
                if (_pro.SaleStatus == Entities.ProductInfo.ProductSaleStatus.OnSale && _pro.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited)
                {
                    item.ShowStatus = 0;
                    if (skus.Sum(d => d.Stock) < 1)
                    {
                        item.ShowStatus = 2;
                    }
                }
                else
                {
                    if (_pro.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited && _pro.SaleStatus == Entities.ProductInfo.ProductSaleStatus.InStock)
                    {
                        item.ShowStatus = 3;
                    }
                    else
                    {
                        item.ShowStatus = 1;
                    }
                }
            }
            if (Core.MallIO.GetMallIO().GetType().FullName.Equals("Mall.Strategy.OSS"))
            {
                ViewBag.IsOss = true;
            }
            else
            {
                ViewBag.IsOss = false;
            }

            ViewBag.keywords         = model.Keyword;
            ViewBag.Total            = total;
            ViewBag.cid              = cid;
            ViewBag.b_id             = b_id;
            ViewBag.a_id             = a_id;
            ViewBag.orderKey         = orderKey;
            ViewBag.orderType        = orderType;
            ViewBag.isSaleCountOnOff = isShow;
            return(result);
        }
Beispiel #11
0
        public object GetSearchProducts(
            string keywords = "", /* 搜索关键字 */
            long cid        = 0,  /* 分类ID */
            long b_id       = 0,  /* 品牌ID */
            string a_id     = "", /* 属性ID, 表现形式:attrId_attrValueId */
            int orderKey    = 1,  /* 排序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间) */
            int orderType   = 1,  /* 排序方式(1:升序,2:降序) */
            int pageNo      = 1,  /*页码*/
            int pageSize    = 10, /*每页显示数据量*/
            long vshopId    = 0,
            long sid        = 0   /*商家ID*/
            )
        {
            var  siteSetingInfo = SiteSettingApplication.SiteSettings;
            bool isShow         = siteSetingInfo.ProductSaleCountOnOff == 1;

            if (string.IsNullOrEmpty(keywords) && vshopId == 0 && cid <= 0 && b_id <= 0 && a_id == "")
            {
                keywords = siteSetingInfo.Keyword;
            }
            #region 初始化查询Model
            SearchProductQuery model = new SearchProductQuery();
            model.VShopId = vshopId;
            model.ShopId  = sid;
            model.BrandId = b_id;
            if (vshopId == 0 && cid != 0)
            {
                var catelist = ServiceProvider.Instance <ICategoryService> .Create.GetCategories();

                var cate = catelist.FirstOrDefault(r => r.Id == cid);
                if (cate != null)
                {
                    if (cate.Depth == 1)
                    {
                        model.FirstCateId = cid;
                    }
                    else if (cate.Depth == 2)
                    {
                        model.SecondCateId = cid;
                    }
                    else if (cate.Depth == 3)
                    {
                        model.ThirdCateId = cid;
                    }
                }
            }
            else if (vshopId != 0 && cid != 0)
            {
                model.ShopCategoryId = cid;
            }
            model.AttrValIds = a_id.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            model.Keyword    = keywords;
            model.OrderKey   = orderKey;
            model.OrderType  = orderType == 1;
            model.PageNumber = pageNo;
            model.PageSize   = pageSize;
            #endregion
            SearchProductResult result = ServiceProvider.Instance <ISearchProductService> .Create.SearchProduct(model);

            int total = result.Total;
            //当查询的结果少于一页时用like进行补偿(与PC端同步)
            if (result.Total < pageSize)
            {
                model.IsLikeSearch = true;
                SearchProductResult result2 = ServiceProvider.Instance <ISearchProductService> .Create.SearchProduct(model);

                var idList1 = result.Data.Select(a => a.ProductId).ToList();
                var nresult = result2.Data.Where(a => !idList1.Contains(a.ProductId)).ToList();
                if (nresult.Count > 0)
                {
                    result.Total += nresult.Count;
                    result.Data.AddRange(nresult);
                }
                //补充数据后,重新排序
                Func <IEnumerable <ProductView>, IOrderedEnumerable <ProductView> > orderby     = null;
                Func <IEnumerable <ProductView>, IOrderedEnumerable <ProductView> > orderByDesc = null;
                switch (model.OrderKey)
                {
                case 2:
                    //order.Append(" ORDER BY SaleCount ");
                    orderby     = e => e.OrderBy(p => p.SaleCount + Himall.Core.Helper.TypeHelper.ObjectToInt(p.VirtualSaleCounts));
                    orderByDesc = e => e.OrderByDescending(p => p.SaleCount + Himall.Core.Helper.TypeHelper.ObjectToInt(p.VirtualSaleCounts));
                    break;

                case 3:
                    //order.Append(" ORDER BY SalePrice ");
                    orderby     = e => e.OrderBy(p => p.SalePrice);
                    orderByDesc = e => e.OrderByDescending(p => p.SalePrice);
                    break;

                case 4:
                    //order.Append(" ORDER BY Comments ");
                    orderby     = e => e.OrderBy(p => p.Comments);
                    orderByDesc = e => e.OrderByDescending(p => p.Comments);
                    break;

                default:
                    //order.Append(" ORDER BY Id ");
                    //orderby = e => e.OrderBy(p => p.ProductId);
                    //orderByDesc = e => e.OrderByDescending(p => p.ProductId);
                    //break;
                    //按最新的排序规则作为默认排序【序号越大,在前台展示的商品越靠前,序号一致时,优先销量排前,销量一致时,优先上架时间排前】
                    if (isShow)
                    {
                        orderByDesc = e => e.OrderByDescending(p => p.DisplaySequence).ThenByDescending(p => p.SaleCount + Himall.Core.Helper.TypeHelper.ObjectToInt(p.VirtualSaleCounts)).ThenByDescending(p => p.ProductId);
                    }
                    else
                    {
                        orderByDesc = e => e.OrderByDescending(p => p.DisplaySequence).ThenByDescending(p => p.ProductId);
                    }
                    break;
                }
                if (model.OrderKey > 1)
                {
                    if (model.OrderType)
                    {
                        result.Data = orderby(result.Data).ToList();
                    }
                    else
                    {
                        result.Data = orderByDesc(result.Data).ToList();
                    }
                }
                else
                {
                    result.Data = orderByDesc(result.Data).ToList();
                }
            }
            total = result.Total;

            //补商品状态
            foreach (var item in result.Data)
            {
                var pro = ServiceProvider.Instance <IProductService> .Create.GetProduct(item.ProductId);

                var skus = ProductManagerApplication.GetSKUs(pro.Id);
                if (pro == null || skus == null)
                {
                    continue;
                }
                if (pro.SaleStatus == Entities.ProductInfo.ProductSaleStatus.OnSale && pro.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited)
                {
                    item.ShowStatus = 0;
                    if (skus.Sum(d => d.Stock) < 1)
                    {
                        item.ShowStatus = 2;
                    }
                }
                else
                {
                    if (pro.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited && pro.SaleStatus == Entities.ProductInfo.ProductSaleStatus.InStock)
                    {
                        item.ShowStatus = 3;
                    }
                    else
                    {
                        item.ShowStatus = 1;
                    }
                }
            }
            #region 价格更新
            //会员折扣
            //decimal discount = 1M;
            //long SelfShopId = 0;
            //if (CurrentUser != null)
            //{
            //    discount = CurrentUser.MemberDiscount;
            //    var shopInfo = ShopApplication.GetSelfShop();
            //    SelfShopId = shopInfo.Id;
            //}

            //var limit = LimitTimeApplication.GetLimitProducts();
            var fight = FightGroupApplication.GetFightGroupPrice();

            foreach (var item in result.Data)
            {
                item.ImagePath = Core.HimallIO.GetRomoteProductSizeImage(Core.HimallIO.GetImagePath(item.ImagePath), 1, (int)Himall.CommonModel.ImageSize.Size_350);
                //if (item.ShopId == SelfShopId)
                //    item.SalePrice = item.SalePrice * discount;
                //var isLimit = limit.Where(r => r.ProductId == item.ProductId).FirstOrDefault();
                var isFight = fight.Where(r => r.ProductId == item.ProductId).FirstOrDefault();
                //if (isLimit != null)
                //    item.SalePrice = isLimit.MinPrice;
                if (isFight != null)
                {
                    //item.SalePrice = isFight.ActivePrice;
                    item.FightGroupId = isFight.ActiveId;
                }
            }
            #endregion

            return(new
            {
                success = true,
                Product = result.Data,
                total = total,
                keywords = model.Keyword,
                cid = cid,
                b_id = b_id,
                a_id = a_id,
                orderKey = orderKey,
                orderType = orderType,
                isSaleCountOnOff = isShow
            });
        }
Beispiel #12
0
        public object GetSearchProducts(
            string keywords = "", /* 搜索关键字 */
            long cid        = 0,  /* 分类ID */
            long b_id       = 0,  /* 品牌ID */
            string a_id     = "", /* 属性ID, 表现形式:attrId_attrValueId */
            int orderKey    = 1,  /* 排序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间) */
            int orderType   = 1,  /* 排序方式(1:升序,2:降序) */
            int pageNo      = 1,  /*页码*/
            int pageSize    = 10, /*每页显示数据量*/
            long vshopId    = 0,
            long sid        = 0   /*商家ID*/
            )
        {
            if (string.IsNullOrEmpty(keywords) && vshopId == 0 && cid <= 0 && b_id <= 0 && a_id == "")
            {
                keywords = Application.SiteSettingApplication.GetSiteSettings().Keyword;
            }
            #region 初始化查询Model
            SearchProductQuery model = new SearchProductQuery();
            model.VShopId = vshopId;
            model.ShopId  = sid;
            model.BrandId = b_id;
            if (vshopId == 0 && cid != 0)
            {
                var catelist = ServiceProvider.Instance <ICategoryService> .Create.GetCategories();

                var cate = catelist.FirstOrDefault(r => r.Id == cid);
                if (cate.Depth == 1)
                {
                    model.FirstCateId = cid;
                }
                else if (cate.Depth == 2)
                {
                    model.SecondCateId = cid;
                }
                else if (cate.Depth == 3)
                {
                    model.ThirdCateId = cid;
                }
            }
            else if (vshopId != 0 && cid != 0)
            {
                model.ShopCategoryId = cid;
            }
            model.AttrValIds = a_id.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            model.Keyword    = keywords;
            model.OrderKey   = orderKey;
            model.OrderType  = orderType == 1;
            model.PageNumber = pageNo;
            model.PageSize   = pageSize;
            #endregion
            SearchProductResult result = ServiceProvider.Instance <ISearchProductService> .Create.SearchProduct(model);

            int total = result.Total;
            //当查询的结果少于一页时用like进行补偿(与PC端同步)
            if (result.Total < pageSize)
            {
                model.IsLikeSearch = true;
                SearchProductResult result2 = ServiceProvider.Instance <ISearchProductService> .Create.SearchProduct(model);

                var idList1 = result.Data.Select(a => a.ProductId).ToList();
                var nresult = result2.Data.Where(a => !idList1.Contains(a.ProductId)).ToList();
                if (nresult.Count > 0)
                {
                    result.Total += nresult.Count;
                    result.Data.AddRange(nresult);
                }
            }
            total = result.Total;

            #region 价格更新
            //会员折扣
            decimal discount   = 1M;
            long    SelfShopId = 0;
            if (CurrentUser != null)
            {
                discount = CurrentUser.MemberDiscount;
                var shopInfo = ShopApplication.GetSelfShop();
                SelfShopId = shopInfo.Id;
            }

            var limit = LimitTimeApplication.GetLimitProducts();
            var fight = FightGroupApplication.GetFightGroupPrice();

            foreach (var item in result.Data)
            {
                item.ImagePath = Core.HimallIO.GetRomoteProductSizeImage(Core.HimallIO.GetImagePath(item.ImagePath), 1, (int)Himall.CommonModel.ImageSize.Size_350);
                if (item.ShopId == SelfShopId)
                {
                    item.SalePrice = item.SalePrice * discount;
                }
                var isLimit = limit.Where(r => r.ProductId == item.ProductId).FirstOrDefault();
                var isFight = fight.Where(r => r.ProductId == item.ProductId).FirstOrDefault();
                if (isLimit != null)
                {
                    item.SalePrice = isLimit.MinPrice;
                }
                if (isFight != null)
                {
                    item.SalePrice = isFight.ActivePrice;
                }
            }
            #endregion

            return(Json(new
            {
                Success = "true",
                Product = result.Data,
                keywords = model.Keyword,
                Total = total,
                cid = cid,
                b_id = b_id,
                a_id = a_id,
                orderKey = orderKey,
                orderType = orderType
            }));
        }
Beispiel #13
0
        private SearchProductResult DoSearch(
            string keywords = "", /* 搜索关键字 */
            long cid        = 0,  /* 分类ID */
            long b_id       = 0,  /* 品牌ID */
            string a_id     = "", /* 属性ID, 表现形式:attrId_attrValueId */
            int orderKey    = 1,  /* 排序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间) */
            int orderType   = 1,  /* 排序方式(1:升序,2:降序) */
            int pageNo      = 1,  /*页码*/
            int pageSize    = 10, /*每页显示数据量*/
            long vshopId    = 0   //店铺ID
            )
        {
            #region 初始化查询Model
            SearchProductQuery model = new SearchProductQuery();
            model.ShopId  = 0;
            model.BrandId = b_id;
            if (cid != 0)
            {
                var catelist = _iCategoryService.GetCategories();
                var cate     = catelist.FirstOrDefault(r => r.Id == cid);
                if (cate.Depth == 1)
                {
                    model.FirstCateId = cid;
                }
                else if (cate.Depth == 2)
                {
                    model.SecondCateId = cid;
                }
                else if (cate.Depth == 3)
                {
                    model.ThirdCateId = cid;
                }
            }
            model.AttrValIds = a_id.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            model.Keyword    = keywords;
            model.OrderKey   = orderKey;
            model.OrderType  = orderType == 1;
            model.PageNumber = pageNo;
            model.PageSize   = pageSize;
            model.VShopId    = vshopId;
            #endregion
            SearchProductResult result = _iSearchProductService.SearchProduct(model);
            int total = result.Total;

            //当查询的结果少于一页时用like进行补偿(与PC端同步)
            if (result.Total < pageSize)
            {
                model.IsLikeSearch = true;
                SearchProductResult result2 = _iSearchProductService.SearchProduct(model);
                var idList1 = result.Data.Select(a => a.ProductId).ToList();
                var nresult = result2.Data.Where(a => !idList1.Contains(a.ProductId)).ToList();
                if (nresult.Count > 0)
                {
                    result.Total += nresult.Count;
                    result.Data.AddRange(nresult);
                }
            }
            total = result.Total;
            if (Core.HimallIO.GetHimallIO().GetType().FullName.Equals("Himall.Strategy.OSS"))
            {
                ViewBag.IsOss = true;
            }
            else
            {
                ViewBag.IsOss = false;
            }

            ViewBag.keywords  = model.Keyword;
            ViewBag.Total     = total;
            ViewBag.cid       = cid;
            ViewBag.b_id      = b_id;
            ViewBag.a_id      = a_id;
            ViewBag.orderKey  = orderKey;
            ViewBag.orderType = orderType;

            return(result);
        }