import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { SelectionRange } from '@progress/kendo-angular-dateinputs';
import { GridDataResult } from '@progress/kendo-angular-grid';
import { orderBy, SortDescriptor } from '@progress/kendo-data-query';
import { Observable, Subscription, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { Customer } from 'src/app/models/customer.model';
import { Order } from 'src/app/models/order.model';
import { StoreERP } from 'src/app/models/store.model';
import { CustomerService } from 'src/app/services/customer.service';
import { OrderService } from 'src/app/services/order.service';

@Component({
  selector: 'app-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnInit, OnDestroy {
  // for combobox
  public size = 'medium';
  public rounded = 'medium';
  public fillMode = 'solid';

  stores$: Observable<StoreERP[]>;
  customers$: Observable<Customer[]>;
  stores: StoreERP[] = [];
  storeUser: StoreERP;
  subscriptionStore: Subscription;
  orders: Order[];
  subscriptionOrder: Subscription;
  public range: SelectionRange = { start: null, end: null };
  public errorObject = null;
  public isloading = false;

  public formFilter: FormGroup;
  public gridView: GridDataResult;
  public sort: SortDescriptor[] = [
    {
      field: 'nomeCliente',
      dir: 'asc',
    },
  ];
  constructor(
    private fb: FormBuilder,
    private authService: AuthService,
    private orderService: OrderService,
    private customerService: CustomerService ) { }

  ngOnDestroy(): void {
    this.subscriptionOrder.unsubscribe();
    this.subscriptionStore.unsubscribe();
  }

  ngOnInit(): void {
    const storeUser = this.authService.getStore();
    this.formFilter = this.fb.group({
      store: [],
      initialDate: [''],
      finalDate: [''],
      customer: [],
      status: [''],
    });
    this.subscriptionStore = this.orderService.getStore()
      .subscribe(result => {
        this.stores = result;
        this.storeUser = this.stores.find(s => s.id === this.authService.getStore());
      });
  }

  searchCustomers(value) {
    console.log(value);
    if (value.length > 3) {
      this.customers$ = this.customerService.getCustomer(value);
    }
  }

  async searchOrders() {
    this.isloading = true;
    this.errorObject = null;
    console.log(this.formFilter.value);
    const store = this.formFilter.get('store').value.id;
    const initialDate = this.formatDate(this.formFilter.get('initialDate').value as Date);
    const finalDate = this.formatDate(this.formFilter.get('finalDate').value as Date);
    const customerId = this.formFilter.get('customer').value.customerId === '2' ? '1' : this.formFilter.get('customer').value.customerId;
    console.log(store + ' ' + initialDate + ' ' + finalDate + ' ' + customerId);

    this.subscriptionOrder = this.orderService.getOrder(store,
      initialDate,
      finalDate,
      customerId).subscribe(result => {
        this.orders = result.data as Order[];
        console.log(this.orders);
        this.gridView = {
          data: orderBy(this.orders, this.sort),
          total: this.orders.length,
        };
      }, catchError(err => {
        this.isloading = false;
        this.errorObject = err;
        return throwError(err);
      }) );
    }

  formatDate(date: Date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
    const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    return year + '-' + month + '-' + day;
  }

  public sortChange(sort: SortDescriptor[]): void {
    this.sort = sort;
    this.gridView = {
      data: orderBy(this.orders, this.sort),
      total: this.orders.length,
    };
  }

  public valueNormalizer = (text: Observable<string>) =>
    text.pipe(map((content: string) => {
    return {
      value: this.stores[this.orders.length - 1].id + 1,
      text: content
    };
  })
  )

  getNameStore() {
    let storeUser: StoreERP[] = [];
    this.stores$.subscribe(store => {
      storeUser = store.filter(s => s.id === this.authService.getStore());
    });
    console.log(storeUser[0].shortName);
    return storeUser[0].shortName;
  }


}
