import { Component, EventEmitter, HostListener, OnInit, Output, } from '@angular/core'; import { MatSnackBar } from '@angular/material/snack-bar'; import { Store } from '@ngrx/store'; import { MessageService } from 'primeng/api'; import { combineLatest } from 'rxjs'; import { SnackBarComponent } from 'src/app/components/snack-bar/snack-bar.component'; import { ICardCustomer } from 'src/app/interface/data'; import { Order } from 'src/app/models/order'; import { OrderProduct } from 'src/app/models/order-product'; import { CartService, ProductAmountAction, } from 'src/app/services/cart.service'; import { OrderService } from 'src/app/services/order.service'; import { selectCustomerCards, selectCustomerWalletBalance, } from 'src/app/state/profile/profile.reducer'; import * as ProfileActions from '../../state/profile/profile.actions'; import { CookiesService } from 'src/app/services/cookies.service'; @Component({ selector: 'app-cart', templateUrl: './cart.component.html', styleUrls: ['./cart.component.scss'], }) export class CartComponent implements OnInit { @Output() showAuthoriztion = new EventEmitter(); public loading = false; public orderConfirmed = false; public order!: Order; public price!: number; public visibleSidebar: boolean = false; public isFullScreen!: boolean; public width!: number; public CardsCustomer!: ICardCustomer[]; public WalletBalanceCustomer!: number; private CardsCustomer$ = this.store.select(selectCustomerCards); private WalletBalanceCustomer$ = this.store.select( selectCustomerWalletBalance ); constructor( private orderService: OrderService, private cartService: CartService, private messageService: MessageService, private _snackBar: MatSnackBar, private store: Store, private cookiesService: CookiesService ) {} async ngOnInit() { this.width = window.innerWidth; this.changeDullScreenMode(); await this.loadCart(); combineLatest([this.CardsCustomer$, this.WalletBalanceCustomer$]).subscribe( { next: ([cards, balance]) => { this.CardsCustomer = cards!; this.WalletBalanceCustomer = balance!; if (cards && balance) this.loading = false; }, error: (err) => { console.error('Произошла ошибка!'); }, } ); } // Изменение размера окна @HostListener('window:resize', ['$event']) onResize(event: any) { this.width = event.target.innerWidth; this.changeDullScreenMode(); } toggleSideBar(): void { this.visibleSidebar = !this.visibleSidebar; this.orderConfirmed = false; this.loadCart(); } hide() { this.orderConfirmed = false; } changeDullScreenMode() { if (this.width < 650) { this.isFullScreen = true; } else { this.isFullScreen = false; } } async loadCart(): Promise { this.loading = true; this.order = await this.orderService.getOrder(true); const token = this.cookiesService.getItem('token'); if (!token) { this._snackBar.open('Авторизуйтесь!', 'Ок'); this.userNotFound(); return; } if (this.order?.userData?.errorCode === 'Customer_CustomerNotFound') { this.userNotFound(); return; } if (this.order) this.price = this.order.price; this.store.dispatch(ProfileActions.getProfile()); } userNotFound(event: null = null) { this.visibleSidebar = false; // this._snackBar.open('Пользователь не найден в системе! Обратитесь к руководству', 'Ок') } async removeFromCart(event: Event, guid: string) { event.preventDefault(); this.orderService.removeFromCart(guid); await this.loadCart(); } confirmOrder(event: Event): void { event.preventDefault(); this.showAuthoriztion.emit(true); if (!this.CardsCustomer[0].IsActivated || !this.CardsCustomer.length) { this._snackBar.open( 'Ваша карта неактивна! Обратитесь к руководству', 'Ок' ); return; } if (this.WalletBalanceCustomer < this.order.price) { this._snackBar.open( 'На Вашей карте недостаточно средств для оформления заказа!', 'Ок' ); return; } this.orderConfirmed = true; // this.confirm.emit(); } setAmount(product: OrderProduct, method: 'plus' | 'minus') { if (method === 'plus') { this.cartService.changeAmountProduct( product.guid, ProductAmountAction.increment ); product.amount++; this.price = this.price + Number(product.price); } else if (method === 'minus' && product.amount > 1) { this.cartService.changeAmountProduct( product.guid, ProductAmountAction.decrement ); product.amount--; this.price = this.price - Number(product.price); } } orderSubmitted(orderid: number) { this.visibleSidebar = false; this._snackBar.open(`Заказ оформлен! Номер заказа: ${orderid}`, 'Ок'); } confirmClearCart() { const snackBar = this._snackBar.openFromComponent(SnackBarComponent, { duration: 4000, data: { text: 'Очистить корзину?', }, }); snackBar.afterDismissed().subscribe(({ dismissedByAction }) => { if (dismissedByAction) { this.cartService.clearCart(); this.loadCart(); this.visibleSidebar = false; } }); } }