public static async Task LoadBasket() { try { List <BasketDB> basketDBList = BasketDB.GetItems(); List <Basket> basketProfileList = await Basket.GetProductInBasketAsync(); int[] produtIDs = basketDBList.Select(g => g.ProductID).Distinct().ToArray(); if (produtIDs.Length == 0) { return; } List <Product> productList = await Product.GetProductsByIDsListAsync(produtIDs); int[] deleteBasketDBList = await Basket.UpdateBasketAsync(basketDBList, basketProfileList, productList); BasketDB.DeleteItems(deleteBasketDBList); } catch { } }
public async void ShowBasketAsync() { basketList = new List <Basket>(); if (User.Singleton != null) { try { if (BasketDB.GetItems().Count > 0) { await User.LoadBasket(); } basketList = await Basket.GetProductInBasketAsync(true); } catch (Exception) { eventRefresh = null; eventRefresh += (sender, e) => { Button content = sender as Button; content.IsEnabled = false; ShowBasketAsync(); }; Content = OnePage.mainPage.ShowMessageError(eventRefresh); return; } try { /// Нужно для определения минимальной суммы заказа. Для этого узнать были ли сделаны до этого заказы User.Singleton.OrderStatusList = await OrderStatus.GetOrderStatusListAsync(); } catch (Exception) { if (eventRefresh == null) { eventRefresh += (sender, e) => { Button content = sender as Button; content.IsEnabled = false; ShowBasketAsync(); } } ; Content = OnePage.mainPage.ShowMessageError(eventRefresh); return; } } List <Basket> basketFromDB = BasketDB.GetItemsToBasketList(); if (basketFromDB != null) { int[] idsProduct = basketFromDB.Select(g => g.ProductID).ToArray(); List <Product> productsList; try { productsList = await Product.GetProductsByIDsListAsync(idsProduct); } catch (Exception) { if (eventRefresh == null) { eventRefresh += (sender, e) => { Button content = sender as Button; content.IsEnabled = false; ShowBasketAsync(); } } ; Content = OnePage.mainPage.ShowMessageError(eventRefresh); return; } foreach (Basket basetBD in basketFromDB) { Product product = productsList.FirstOrDefault(g => g.ProductsID == basetBD.ProductID); if (product != null) { if (product.productsAttributes?.Count > 0) { ProductsAttributes productsAttribute = product.productsAttributes.FirstOrDefault(g => g.OptionValue.ID == basetBD.SizeValueId); if (productsAttribute != null) { basetBD.ProductActualQuantity = productsAttribute.Quantity; } } else { basetBD.ProductActualQuantity = product.Quantity; } basetBD.ProductsQuantityOrderMin = product.ProductsQuantityOrderMin; basetBD.ProductsQuantityOrderUnits = product.ProductsQuantityOrderUnits; basetBD.ProductAvailable = true; } else { basetBD.ProductAvailable = false; } } basketList.AddRange(basketFromDB); } if (basketList == null || basketList.Count == 0) { Content = layoutProductZero; return; } countPage = (int)Math.Ceiling((double)basketList.Count / countProductPage); SetProductList(); total = 0; notValidBasketList = new List <Basket>(); foreach (var item in basketList) { if (!item.ProductAvailable) { notValidBasketList.Add(item); continue; } if (item.Quantity > item.ProductActualQuantity) { if (!item.IsLocalBasket) { notValidBasketList.Add(item); } total += item.ProductActualQuantity * item.Price; } else { total += item.Quantity * item.Price; } } //total = basketList.Sum (g => Math.Ceiling(g.Price) * g.Quantity); lblTotal = new Label { FontSize = 24, TextColor = ApplicationStyle.GreenColor, VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, HorizontalTextAlignment = TextAlignment.Center, FontAttributes = FontAttributes.Bold, }; Button btnOrder = new Button { Text = "Оформить", FontSize = Utils.GetSize(18), TextColor = Color.White, BackgroundColor = ApplicationStyle.RedColor, HorizontalOptions = LayoutOptions.FillAndExpand, BorderRadius = 0, }; btnOrder.Clicked += ClickCheckOut; Grid gridBottom = new Grid { HeightRequest = Utils.GetSize(49), VerticalOptions = LayoutOptions.FillAndExpand, ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(50, GridUnitType.Star) }, new ColumnDefinition { Width = new GridLength(50, GridUnitType.Star) }, }, BackgroundColor = Color.White, }; MyPicker pickerAuthorization = new MyPicker { TextColor = Color.Transparent, BackgroundColor = Color.Transparent, Items = { login, registration, "Отмена" } }; pickerAuthorization.Unfocused += OnLoginClick; Grid gridPicker = new Grid(); gridPicker.Children.Add(btnOrder, 0, 0); if (User.Singleton == null) { gridPicker.Children.Add(pickerAuthorization, 0, 0); } gridBottom.Children.Add(lblTotal, 0, 0); gridBottom.Children.Add(gridPicker, 1, 0); StackLayout layoutBottom = new StackLayout { VerticalOptions = LayoutOptions.FillAndExpand, Spacing = 0, Children = { new BoxView(), gridBottom } }; mainGrid = new Grid { VerticalOptions = LayoutOptions.FillAndExpand, RowSpacing = 0, RowDefinitions = { new RowDefinition { Height = new GridLength(100, GridUnitType.Star) }, new RowDefinition { Height = Utils.GetSize(50) }, } }; mainGrid.Children.Add(scrollProduct, 0, 0); mainGrid.Children.Add(layoutBottom, 0, 1); Content = mainGrid; if (total > 0) { lblTotal.Text = total + "р."; } } void OnGoToProduct(object sender, EventArgs e) { OnePage.redirectApp.RedirectToPage(PageName.Catalog, false, false); } void OnLoginClick(object sender, FocusEventArgs e) { Picker picker = sender as Picker; if (picker.SelectedIndex == -1) { return; } string doUser = picker.Items [picker.SelectedIndex]; switch (doUser) { case login: Task.Run(() => { Task.Delay(20); Device.BeginInvokeOnMainThread(() => { OnePage.redirectApp.RedirectToPage(PageName.Login, false, true); }); }); break; case registration: Task.Run(() => { Task.Delay(20); Device.BeginInvokeOnMainThread(() => { OnePage.redirectApp.RedirectToPage(PageName.Login, true, false); OnePage.redirectApp.loginView.GoToPersonalData(true); }); }); break; default: break; } } async void OnClickProduct(object sender, SelectedItemChangedEventArgs e) { if (e.SelectedItem == null) { return; } Basket basket = e.SelectedItem as Basket; if (!basket.ProductAvailable) { ListView entity = sender as ListView; entity.SelectedItem = null; return; } //await Task.Delay(500); Product product = await Product.GetProductsByIDAsync(basket.ProductID); OnePage.redirectApp.RedirectToPage(PageName.Catalog, true, true); OnePage.redirectApp.catalogView.GoToProductAsync(basket, product); }
async Task AddToBasket(int maxCountProduct) { /// Если пользователь не зарегистрирован или товар из локальной корзины if (User.Singleton == null || (oldBasket != null && oldBasket.IsLocalBasket)) { BasketDB basketBD = new BasketDB { ProductID = ProductItem.ProductsID, Article = ProductItem.Article, ProductName = ProductItem.productsDescription.Name, SizeName = selectSize.Value, Image = ProductItem.Image, SizeID = selectSize.Key, Price = ProductItem.Price, Quantity = int.Parse(entCount.Text), ProductExpress = ProductItem.Express, IsSchedule = ProductItem.SchedulesList.Count > 0 }; /// Если мы изменяем размер товара в корзине if (oldBasket != null) { if (oldBasket.SizeValueId != selectSize.Key || oldBasket.Quantity != basketBD.Quantity) { /// Не дает добавить товаров больше чем они есть на складе if (basketBD.Quantity > maxCountProduct) { basketBD.Quantity = maxCountProduct; } BasketDB.Update(basketBD, oldBasket.ProductID, oldBasket.SizeValueId ?? 0); } OnePage.redirectApp.BackToHistory(); return; } else { BasketDB basketProfile; if (basketBD.SizeID == 0) { basketProfile = BasketDB.GetItemByID(basketBD.ProductID); } else { basketProfile = BasketDB.GetItem(basketBD.ProductID, basketBD.SizeID); } if (basketProfile != null) { /// Не дает добавить товаров больше чем они есть на складе if (basketBD.Quantity + basketProfile.Quantity > maxCountProduct) { basketBD.Quantity = maxCountProduct - basketProfile.Quantity; } } BasketDB.AddCount(basketBD); } } else /// Если залогинен { Basket basket = new Basket { ProductID = ProductItem.ProductsID, SizeValueId = selectSize.Key, Quantity = int.Parse(entCount.Text) }; /// Если мы изменяем размер товара в корзине if (oldBasket != null) { if (oldBasket.SizeValueId != selectSize.Key || oldBasket.Quantity != basket.Quantity) { /// Удаляем позицию товара из заказа oldBasket.Quantity = -oldBasket.Quantity; try { await Basket.PushToBasketAsync(oldBasket); } catch (Exception) { eventRefresh = null; eventRefresh += (obj, evn) => { Button content = obj as Button; content.IsEnabled = false; AddToBasket(maxCountProduct).Wait(); }; Content = OnePage.mainPage.ShowMessageError(eventRefresh); return; } /// Не дает добавить товаров больше чем они есть на складе if (basket.Quantity > maxCountProduct) { basket.Quantity = maxCountProduct; } try { await Basket.PushToBasketAsync(basket); } catch (Exception) { eventRefresh = null; eventRefresh += (obj, evn) => { Button content = obj as Button; content.IsEnabled = false; AddToBasket(maxCountProduct).Wait(); }; Content = OnePage.mainPage.ShowMessageError(eventRefresh); return; } } OnePage.redirectApp.BackToHistory(); return; } else /// Если перешли в товар НЕ из корзины { List <Basket> basketProfileList; try { basketProfileList = await Basket.GetProductInBasketAsync(); } catch (Exception) { eventRefresh = null; eventRefresh += (obj, evn) => { Button content = obj as Button; content.IsEnabled = false; AddToBasket(maxCountProduct).Wait(); }; Content = OnePage.mainPage.ShowMessageError(eventRefresh); return; } Basket basketProfile; if (basket.SizeValueId != null) { basketProfile = basketProfileList.SingleOrDefault(g => g.ProductID == basket.ProductID && g.SizeValueId == basket.SizeValueId); } else { basketProfile = basketProfileList.SingleOrDefault(g => g.ProductID == basket.ProductID); } if (basketProfile != null) { /// Не дает добавить товаров больше чем они есть на складе if (basket.Quantity + basketProfile.Quantity > maxCountProduct) { basket.Quantity = maxCountProduct - basketProfile.Quantity; } } try { await Basket.PushToBasketAsync(basket); } catch (Exception) { eventRefresh = null; eventRefresh += (obj, evn) => { Button content = obj as Button; content.IsEnabled = false; AddToBasket(maxCountProduct).Wait(); }; Content = OnePage.mainPage.ShowMessageError(eventRefresh); return; } } } }