import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { TextBoxComponent } from '@progress/kendo-angular-inputs';
import { Observable, Subscription } from 'rxjs';
import { Stock } from 'src/app/models/sale-product.model';
import { ProductService } from 'src/app/services/product.service';
import { ShoppingService } from 'src/app/services/shopping.service';
import { UpdateQuantityItemAction } from '../../store/actions/shopping.action';
import { SaleState } from '../../store/models/sale-state.model';
import { ShoppingItem } from '../../store/models/shopping-item';
import { AuthService } from 'src/app/auth/services/auth.service';

@Component({
  selector: 'app-list-shoppingitem',
  templateUrl: './list-shoppingitem.component.html',
  styleUrls: ['./list-shoppingitem.component.scss']
})
export class ListShoppingitemComponent implements OnInit {
  shopping$: Observable<ShoppingItem[]>;
  shoppingItens: ShoppingItem[] = [];
  stock$: Observable<Stock[]>;
  loading$: Observable<boolean>;
  error$: Observable<Error>;
  updating$: Observable<boolean>;
  subscriptionStock: Subscription;
  @ViewChild('quantityCart') quantityCart: TextBoxComponent;
  @ViewChild('card-itens') cardItens: ElementRef;

  showInformation = false;
  titleInformation = 'Pedido de venda';
  messageInformation = '';
  informationDescription = '';

  showConfirmationCancelSale = false;
  titleMessage = 'Pedido de venda';
  messageConfirmation = 'Confirma cancelamento da venda?';
  textButtonConfirmation = 'Sim';
  textButtonCancel = 'Não';

  constructor(
    private store: Store<SaleState>,
    private readonly productService: ProductService,
    private readonly shoppingService: ShoppingService,
    private readonly authService: AuthService,
    private readonly router: Router,
    ) { }

  ngOnInit(): void {
    this.shopping$ = this.store.select(store => store.shopping.list);
    this.updating$ = this.store.select(store => store.shopping.updating);
    const altura = document.getElementById('teste').clientHeight;
    console.log(altura);
  }

  addQuantity(product: ShoppingItem) {
    const oldValue = product.quantity;
    let addQuantity = 1;
    if (product.mutiple !== 1) {
      addQuantity = product.mutiple;
    }
    const newValue = (oldValue + addQuantity);
    this.stock$ = this.productService.getStocks(this.authService.getStore(), product.idProduct);
    this.subscriptionStock = this.stock$.subscribe(stocks => {
      const stock = stocks.filter(s => s.store === product.stockStore);
      if (product.deliveryType !== 'EF') {
        if (stock[0].quantity >= newValue) {
          this.quantityCart.value = newValue.toString();
          this.updateItem(product, newValue);
        }
        else {
          this.quantityCart.value = oldValue.toString();
          this.messageInformation = 'Produto sem estoque!';
          this.informationDescription = 'Produto esta sem estoque disponível para atender o pedido na filial de retira selecionada.';
          this.showInformation = true;
        }
      }
      console.log(this.quantityCart.value);
    });
  }

  minusQuantity(dataItem) {
    const oldValue = dataItem.quantity; // this.formQuantity.get('quantity').value;
    let addQuantity = 1;
    if (dataItem.mutiple !== 1) {
      addQuantity = dataItem.mutiple;
    }
    let newValue = (oldValue - addQuantity);
    if (newValue < 0 || newValue < dataItem.mutiple) {
      newValue = dataItem.mutiple;
    }
    let updateItem: ShoppingItem;
    updateItem = JSON.parse(JSON.stringify(dataItem));
    updateItem.quantity = newValue;
    this.updateItem(updateItem, newValue);
  }

  updateItem(value: ShoppingItem, quantity: number) {
    try {
      const idCart = this.shoppingService.getCart();
      this.store.dispatch(new UpdateQuantityItemAction({
        id: value.id, idCart, invoiceStore: value.invoiceStore,
        idProduct: value.idProduct, description: value.description, image: value.image, productType: value.productType,
        quantity, price: value.price, deliveryType: value.deliveryType, stockStore: value.stockStore,
        seller: value.seller, discount: value.discount, discountValue: value.discountValue, ean: value.ean,
        listPrice: value.listPrice, userDiscount: value.userDiscount, mutiple: value.mutiple,
        percentUpQuantity: value.percentUpQuantity, upQuantity: value.upQuantity,
        auxDescription: null, smallDescription: value.smallDescription, brand: value.brand, promotion: value.promotion,
        base: value.base, line: value.line, color: value.color, can: value.can, letter: value.letter,
      }));
    } catch (e) {
      console.log(e);
    }
  }

  cancelSale() {
    this.messageConfirmation = 'Confirma cancelamento da venda?';
    this.showConfirmationCancelSale = true;
  }

  returnConfirmationCancel(confirmation: any) {
    if (confirmation) {
      localStorage.removeItem('cart');
      localStorage.removeItem('customer');
      localStorage.removeItem('preCustomer');
      localStorage.removeItem('paymentPlan');
      localStorage.removeItem('billing');
      localStorage.removeItem('address');
      localStorage.removeItem('invoiceStore');
      localStorage.removeItem('partner');
      localStorage.removeItem('shoppingItem');
      localStorage.removeItem('dataDelivery');
      localStorage.removeItem('taxDelivery');
      localStorage.removeItem('authorizationTax');
      localStorage.removeItem('authorizationPartner');
      this.router.navigate(['/sales/menu']);
    } else {
      this.showConfirmationCancelSale = false;
    }
  }

  public confirmSale(offCanvasId: string) {
    this.router.navigate(['sales/cart']);
  }


}
