import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { DialogCloseResult, DialogRef, DialogService } from '@progress/kendo-angular-dialog';
import { BadgeAlign, BadgePosition } from '@progress/kendo-angular-indicators';
import { TextBoxComponent } from '@progress/kendo-angular-inputs';
import { Observable, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter, map, switchMap, tap } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { FilterProduct } from 'src/app/models/filter-product.model';
import { ItemBanner } from 'src/app/models/item-banner.model';
import { SaleProduct, Stock } from 'src/app/models/sale-product.model';
import { MessageService } from 'src/app/services/messages.service';
import { ProductService } from 'src/app/services/product.service';
import { ShoppingService } from 'src/app/services/shopping.service';
import { ProductModalComponent } from '../components/product-modal/product-modal.component';
import { DeleteItemAction, LoadShoppingAction, LoadShoppingItemsAction, UpdateQuantityItemAction } from '../store/actions/shopping.action';
import { SaleState } from '../store/models/sale-state.model';
import { ShoppingItem } from '../store/models/shopping-item';
import { Shopping } from '../store/models/shopping.model';
import { ChartData, ChartOptions } from 'chart.js';
import { RowClassArgs } from '@progress/kendo-angular-grid';

@Component({
  selector: 'app-home-sales',
  templateUrl: './home-sales.component.html',
  styleUrls: ['./home-sales.component.scss'],
  styles: [
    `
      #my-grid tr.gold {
        background-color: #ffba80;
      }

      #my-grid tr.green {
        background-color: #b2f699;
      }
    `,
  ],
})
export class HomeSalesComponent implements OnInit, OnDestroy {
  searchProduct = new FormControl();
  loadProducts: SaleProduct[];
  existsProduct = false;
  searchSubscription: Subscription;
  products$: Observable<SaleProduct[]>;
  shoppingItems$: Observable<ShoppingItem[]>;
  shopping$: Observable<Shopping>;
  subscriptionShoppingItems: Subscription;
  shoppingItems: ShoppingItem[] = [];
  subscriptionShopping: Subscription;
  shopping: Shopping;
  stock$: Observable<Stock[]>;
  stockSubscription: Subscription;
  loading$: Observable<boolean>;
  updating$: Observable<boolean>;

  squedule$: Observable<any>;

  @ViewChild('productCard') productCard: ElementRef;
  @ViewChild('quantityCart') quantityCart: TextBoxComponent;


  // Scroll for Banners
  public items: ItemBanner[] = [{ title: 'Banner Jurunense', url: '../../../assets/banners/banner_teste.svg' }];
  public width = '100%';
  public height = '400px';
  public animate = true;

  /*Badge cart */
  public position: BadgePosition = 'inside';
  public get align(): BadgeAlign {
    return { vertical: 'top', horizontal: 'end' };
  }
  public themeBadge = 'warning';

  /* Header */
  public userName: string;
  public storeName: string;

  /* Dialogs */
  showInformation = false;
  titleInformation = 'Pedido de venda';
  messageInformation = '';
  informationDescription = '';

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



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

  ngOnDestroy(): void {
    if (this.searchSubscription){
      this.searchSubscription.unsubscribe();
    }
    if (this.stockSubscription) {
      this.stockSubscription.unsubscribe();
    }
  }

  ngOnInit(): void {
    this.userName  = this.authService.getUserName();
    this.storeName = this.authService.getStoreName();

    let idCart = this.shoppingService.getCart();
    if (idCart == null){
      idCart = 'SV';
    }

    console.log('Iniciando pagina HOME');

    localStorage.removeItem('promotion');
    localStorage.removeItem('markdown');
    localStorage.removeItem('opportunity');
    localStorage.removeItem('offers');
    localStorage.removeItem('url');
    localStorage.removeItem('brands');
    localStorage.removeItem('text');

    this.squedule$ = this.shoppingService.getScheduleDelivery();

    this.shopping$ = this.store.select(store => store.shopping.shopping);
    this.shoppingItems$ = this.store.select(store => store.shopping.list);
    this.store.dispatch(new LoadShoppingItemsAction(idCart));
    this.store.dispatch(new LoadShoppingAction(idCart));
    this.store.dispatch(new LoadShoppingItemsAction(idCart));
    this.shoppingItems$.subscribe((data) => {
      this.shoppingItems = JSON.parse(JSON.stringify(data));
      console.log(this.shoppingItems);
    });

    this.searchSubscription = this.searchProduct.valueChanges
      .pipe(
        map(value => value.trim()),
        filter(value => value.length > 3),
        debounceTime(400),
        distinctUntilChanged(),
        tap(value => this.loadProducts = null),
        switchMap(value => this.productService.searchProduct(this.authService.getStore(), 1, 50, value)),
        map(products => this.loadProducts = products),
        tap(products => this.existsProduct = products.length > 0)
      ).subscribe();
  }

  keyDownFunction(event) {
    if (event.keyCode === 13) {
      // tslint:disable-next-line: no-shadowed-variable
      this.filterProduct();
     // const filter: FilterProduct = { brands: [], text: this.searchProduct.value };
     // this.searchProducts(this.searchProduct.value);
    }
  }

  searchProducts(text: string) {
    try {
      this.products$ = this.productService.searchProduct(this.authService.getStore(), 1, 5000, text.toUpperCase());
      this.products$
        .subscribe(products => {
          this.loadProducts = products;
        });
    }
    catch (e) {
      console.log('Erro ao consultar produtos.');
      console.log(e);
    }
  }

  filterProduct() {
    const text = this.searchProduct.value.toUpperCase();
    localStorage.setItem('text', text);
    localStorage.setItem('promotion', 'false');
    localStorage.setItem('markdown', 'false');
    localStorage.setItem('oportunity', 'false');
    localStorage.setItem('offers', 'false');
    this.router.navigate([`product-list`]);
  }

  filterMarkdown(){
    localStorage.setItem('text', '');
    localStorage.setItem('promotion', 'false');
    localStorage.setItem('markdown', 'true');
    localStorage.setItem('oportunity', 'false');
    localStorage.setItem('offers', 'false');
    this.router.navigate([`product-list`]);
  }

  filterPromotion(){
    localStorage.setItem('text', '');
    localStorage.setItem('promotion', 'true');
    localStorage.setItem('markdown', 'false');
    localStorage.setItem('oportunity', 'false');
    localStorage.setItem('offers', 'false');
    this.router.navigate([`product-list`]);
  }

  filterOportunity(){
    localStorage.setItem('text', '');
    localStorage.setItem('promotion', 'false');
    localStorage.setItem('markdown', 'false');
    localStorage.setItem('oportunity', 'true');
    localStorage.setItem('offers', 'false');
    this.router.navigate([`product-list`]);
  }

  filterOffers(){
    localStorage.setItem('text', '');
    localStorage.setItem('promotion', 'false');
    localStorage.setItem('markdown', 'false');
    localStorage.setItem('oportunity', 'false');
    localStorage.setItem('offers', 'true');
    this.router.navigate([`product-list`]);
  }

  navTo(url: string){
    this.router.navigate([url]);
  }

  logout() {
    this.shoppingService.cancelShopping();
    this.authService.logout();
  }

  /* Funções para alterar quantidade dos itens existentes no carrinho */
  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.stockSubscription = this.stock$.subscribe(stocks => {
      const stock = stocks.filter(s => s.store === product.stockStore);
      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, letter: value.letter, line: value.line, color: value.color, can: value.can,
      }));
    } catch (e) {
      console.log(e);
    }
  }

  editShoppingItem(item: ShoppingItem) {

    this.productService.getSaleProduct(this.authService.getStore(), item.idProduct)
      .subscribe((product) => {
        console.log(product);
        let resultProduct: any;
        const dialogRef: DialogRef = this.dialogService.open({
          content: ProductModalComponent,
        });
        const productInfo = dialogRef.content.instance as ProductModalComponent;
        productInfo.product = product;
        productInfo.shoppingItem = item;
        dialogRef.result.subscribe((result) => {
          if (result instanceof DialogCloseResult) {
            console.log('WindowCloseResult', result);
          } else {
            console.log('action', result);
            resultProduct = JSON.stringify(result);
            console.log(resultProduct);
            this.messageService.showMessage(JSON.parse(resultProduct).message);
          }
        });
      }
      );

  }

  async showConfirmationCancelItem(item: ShoppingItem) {
    console.log(item);
    this.itemCancel = item;
    this.titleMessage = 'Pedido de venda';
    this.messageConfirmation = `Confirma a exclusão do item do pedido?`;
    this.textButtonConfirmation = 'Confirma';
    this.openedConfirmationCancelItem = true;
  }

  async returnConfirmationCancelItem(result: any) {
    this.openedConfirmationCancelItem = false;
    if (result && this.itemCancel != null) {
      this.store.dispatch(new DeleteItemAction(this.itemCancel.id));
      this.updating$.subscribe((update) => {
        if (!update) {
          this.store.dispatch(new LoadShoppingItemsAction(this.shoppingService.getCart()));
          this.store.dispatch(new LoadShoppingAction(this.shoppingService.getCart()));
          this.itemCancel = null;
        }
      });
    }
  }

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

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

  returnConfirmationCancel(confirmation: any) {
    if (confirmation) {
      this.shoppingService.cancelShopping();
      this.router.navigate(['/sales/menu']);
    } else {
      this.showConfirmationCancelSale = false;
    }
  }

  public rowCallback = (context: RowClassArgs) => {
    return context.dataItem.delivery === 'N' ? 'red-row' : '';
  };


}
