import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Store } from '@ngrx/store';
import { SelectableSettings, SelectionEvent } from '@progress/kendo-angular-grid';
import { Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';
import { Billing } from 'src/app/models/billing.model';
import { CartItensModel } from 'src/app/models/cart-itens.model';
import { CartModel } from 'src/app/models/cart.model';
import { Customer } from 'src/app/models/customer.model';
import { PaymentPlan } from 'src/app/models/payment-plan.model';
import { CustomerService } from 'src/app/services/customer.service';
import { LookupService } from 'src/app/services/lookup.service';
import { ShoppingService } from 'src/app/services/shopping.service';
import { SaleState } from '../store/models/sale-state.model';
import { ShoppingItem } from '../store/models/shopping-item';
import { LoadShoppingItemsAction } from '../store/actions/shopping.action';
import { OrderService } from 'src/app/services/order.service';
import { AuthService } from 'src/app/auth/services/auth.service';

@Component({
  selector: 'app-sale-customer',
  templateUrl: './sale-customer.component.html',
  styleUrls: ['./sale-customer.component.scss']
})
export class SaleCustomerComponent implements OnInit {
  public themeColor = 'inherit';
  public form: FormGroup;
  public queryField = new FormControl();
  customers: Customer[] = [];
  saleCustomer: Customer = null;
  shopping$: Observable<ShoppingItem[]>;
  totalCart$: Observable<number>;
  paymentPlan$: Observable<PaymentPlan[]>;
  billing$: Observable<Billing[]>;
  saleBilling: Billing = null;
  salePaymentPlan: PaymentPlan = null;
  public openedCustomer = false;
  public selectableSettigns: SelectableSettings = {
    checkboxOnly: false
  };

  constructor(
    private store: Store<SaleState>,
    private customerService: CustomerService,
    private shoppingService: ShoppingService,
    private orderService: OrderService,
    private lookupService: LookupService,
    private formBuilder: FormBuilder,
    private authService: AuthService,
  ) {
    this.form = this.formBuilder.group({
      customer: new FormControl('', [Validators.required, Validators.minLength(3)]),
      addressCustomer: new FormControl('', []),
      numberCustomer: new FormControl('', []),
      neighbordCustomer: new FormControl('', []),
      cityCustomer: new FormControl('', []),
      stateCustomer: new FormControl('', []),
      zipCodeCustomer: new FormControl('', []),
      cellPhoneCustomer: new FormControl('', []),
      phoneCustomer: new FormControl('', []),
    });

    this.shopping$ = this.store.select(data => data.shopping.list);
    this.totalCart$ = this.store.select(data => data.shopping.total);
    this.paymentPlan$ = this.lookupService.getPaymentPlan();
    this.billing$ = this.lookupService.getBilling(1);
    this.store.dispatch(new LoadShoppingItemsAction(this.shoppingService.getCart()));

  }

  ngOnInit(): void {
    // this.saleCustomer = this.shoppingService.getCustomerSale();

    this.queryField.valueChanges
      .pipe(
        map(value => value.trim()),
        filter(value => value.length > 3 || value === ''),
        debounceTime(300),
        distinctUntilChanged(),
        switchMap(async (value) => {
          this.customers = await this.searchCustomer(value);
        })
      ).subscribe();
  }

  public openWindow() {
    this.openedCustomer = true;
    this.queryField.setValue('');
    this.customers = [];
  }

  public close() {
    this.openedCustomer = false;
  }

  onSelectionChangeCustomer(args: SelectionEvent) {
    const selCustomer = args.selectedRows[0].dataItem as Customer;
    this.shoppingService.setCustomerSale(selCustomer);
    this.saleCustomer = selCustomer;
    this.close();
  }

  async searchCustomer(name: string) {
    try {
      this.customerService.getCustomer(name)
        .subscribe((res: Customer[]) => {
          this.customers = res;
        });
    } catch (e) {
      return null;
    }

  }

  async getItens() {
    const itensCart: CartItensModel[] = [];
    this.shopping$.subscribe(data => {
      console.log(data);
      data.forEach((itemShopping) => {
        const item: CartItensModel = {
          idProduct: itemShopping.idProduct, idStock: itemShopping.stockStore,
          deliveryMethod: itemShopping.deliveryType, quantity: itemShopping.quantity, listPrice: itemShopping.price,
          salePrice: itemShopping.price, ean: itemShopping.ean, descriptionAux: itemShopping.auxDescription,
        };
        itensCart.push(item);
      });
    }
    );

    return itensCart;
  }

  async createOrder() {
    console.log('criando cart');
    //  if (!this.form.valid) {
    //     return;
    //    }

    if (!this.saleCustomer) {
      return;
    }
    console.log('Consultando itens');
    const itensCart = await this.getItens();
    console.log(itensCart);
    console.log('criando carrinho');
    console.log(this.form);
    const cart: CartModel = {
      id: this.shoppingService.getCart(),
      userId: this.authService.getUser(),
      saleStore: this.authService.getStore(),
      idCustomer: this.saleCustomer.customerId,
      idPaymentPlan: this.salePaymentPlan.codplpag,
      idBilling: this.saleBilling.codcob,
      idSeller: this.authService.getSeller(),
      idProfessional: 0,
      shippingDate: null,
      scheduleDelivery: false,
      shippingPriority: '',
      shippingValue: 0,
      carrierId: 0,
      idAddress: 0,
      notation1: '',
      notation2: '',
      notation3: '',
      deliveryNote1: '',
      deliveryNote2: '',
      deliveryNote3: '',
      itens: itensCart,
      preCustomerDocument: null,
      preCustomerName: null,
      preCustomerPhone: null,

    };

    console.log(cart);

    const result$ = this.orderService.create(cart);
    result$.pipe(
      map(c => console.log('pedido gerado')),
    ).subscribe();

  }

  setBilling(selectBilling: Billing) {
    this.saleBilling = selectBilling;
  }

  setPaymentoPlan(selectPaymentPlan: PaymentPlan) {
    console.log(selectPaymentPlan);
    this.salePaymentPlan = selectPaymentPlan;
  }

}
