import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Observable, Subscription, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { ProductsOrder } from 'src/app/models/products-order.model';
import { StoreERP } from 'src/app/models/store.model';
import { LookupService } from 'src/app/services/lookup.service';
import { OrderService } from 'src/app/services/order.service';
import { ShoppingService } from 'src/app/services/shopping.service';

@Component({
  selector: 'app-product-orders',
  templateUrl: './product-orders.component.html',
  styleUrls: ['./product-orders.component.scss']
})
export class ProductOrdersComponent implements OnInit {

  constructor(
    private readonly shoppingService: ShoppingService,
    private readonly lookupService: LookupService,
    private readonly orderService: OrderService,
    private readonly fb: FormBuilder,
    private readonly router: Router,
    private readonly authService: AuthService
  ) { }

  formFilterOrder: FormGroup;
  store$: Observable<StoreERP[]>;
  subscriptionOrders: Subscription;
  selectStore: StoreERP;
  orders: ProductsOrder[];
  loading = false;
  public filterPreOrder = {
    start: '',
    end: '',
    store: '',
    idOrder: ' ',
  };
  optionsFilterProduct = [
    { id: 'ID', option: 'Código' },
    { id: 'EAN', option: 'Ean' },
    { id: 'TEXT', option: 'Descrição' },
    { id: 'PARTNER', option: 'Código Fábrica' }
  ];

  ngOnInit() {
    this.store$ = this.lookupService.getStore();
    this.formFilterOrder = this.fb.group({
      document: new FormControl('', []),
      nameCustomer: new FormControl('', []),
      product: new FormControl('', []),
      typeFilterProduct: new FormControl('', []),
    });
  }

  selectedStore(store: any) {
    this.selectStore = store;
    this.filterPreOrder.store = store.id;
  }

  async getOrders() {
    this.orders = [];
    const document = this.formFilterOrder.get('document').value;
    const name = this.formFilterOrder.get('nameCustomer').value;
    const typeFilterProduct = this.formFilterOrder.get('typeFilterProduct').value;
    const productText = this.formFilterOrder.get('product').value;

    if ( this.filterPreOrder.store == '') {
      this.filterPreOrder.store = '99';
    }

    this.loading = true;
    this.subscriptionOrders = this.orderService.findProductsOrder(this.filterPreOrder.store, this.filterPreOrder.start,
      this.filterPreOrder.end, document, name, this.filterPreOrder.idOrder, typeFilterProduct, productText).pipe(
        map((result) => {
          this.orders = result as ProductsOrder[];
          this.orderService.setProductsOrder(this.orders);
          this.router.navigateByUrl('sales/menu/list-product-order');
        }),
        catchError((error) => {
          console.log('erro ao consultar dados de venda.');
          return of(null);
        })
      ).subscribe(() => {
        this.loading = false;
      });
  }

}
