import { Component, OnInit } from '@angular/core';
import { EditEvent, GridDataResult } from '@progress/kendo-angular-grid';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { PreOrder } from 'src/app/models/pre-order.model';
import { StoreERP } from 'src/app/models/store.model';
import { LookupService } from 'src/app/services/lookup.service';
import { PreOrderService } from 'src/app/services/pre-order.service';
import { ShoppingService } from 'src/app/services/shopping.service';

@Component({
  selector: 'app-preorder-list',
  templateUrl: './preorder-list.component.html',
  styleUrls: ['./preorder-list.component.scss']
})
export class PreorderListComponent implements OnInit {
  public range = { start: new Date(), end: new Date() };
  stores: StoreERP[] = [];
  preOrders: PreOrder[] = [];
  store$: Observable<StoreERP[]>;

  // Filtros
  selectStore: StoreERP;

  public columns: { field: string, title: string, width: number}[] = [
    { field: 'data', title: 'Data', width: 100 },
    { field: 'idPreOrder', title: 'N.Orçamento', width: 120 },
    { field: 'seller', title: 'Vendedor', width: 250 },
    { field: 'idCustomer', title: 'Cód.Cliente', width: 100 },
    { field: 'customer', title: 'Cliente', width: 250 },
    { field: 'valor', title: 'Valor', width: 120 },
  ];
  public bindingType = 'array';
  public gridData: PreOrder[] | GridDataResult = this.preOrders;
  public gridDataResult: GridDataResult = {
    data: this.preOrders,
    total: this.preOrders.length,
  };
  public isLoading: boolean;


  constructor(
    private readonly preOrderService: PreOrderService,
    private readonly shoppingService: ShoppingService,
    private readonly lookupService: LookupService,
  ) { }

  ngOnInit(): void {
    this.getPreOrders();
    this.store$ = this.lookupService.getStore();
  }

  selectedStore(store: any) {
    this.selectStore = store;
    console.log(store);
  }

  async getPreOrders() {
    this.preOrders = [];
    this.preOrderService.getPreOrders(null, null, null, null, null, null).pipe(
      map((result) => {
        if (result.success) {
          this.preOrders = result.data;
        }
      }),
      catchError((error) => {
        console.log('erro ao consultar orçamentos.');
        return of(null);
      })
    ).subscribe();
  }

  public selectedPreOrder({ sender, rowIndex, dataItem }: EditEvent): void{
    console.log(dataItem);
  }

}
