import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { WindowState } from '@progress/kendo-angular-dialog';
import { EditEvent, GridDataResult } from '@progress/kendo-angular-grid';
import { BadgeAlign, BadgePosition } from '@progress/kendo-angular-indicators';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { OrderDelivery } from 'src/app/models/order-delivery.model';
import { PreOrderItens } from 'src/app/models/pre-order-itens.model';
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',
  templateUrl: './preorder.component.html',
  styleUrls: ['./preorder.component.scss']
})
export class PreorderComponent implements OnInit {
  public range = { start: new Date(), end: new Date() };
  stores: StoreERP[] = [];
  preOrders: PreOrder[] = [];
  store$: Observable<StoreERP[]>;

  // Filtros
  selectStore: StoreERP;

  //print pre-order
  openedModelPrintPreOrder = false;
  modelPrintPreOrder = '';
  formModelPreOrder: FormGroup;
  preOrderNumber: number;
  openedModelPrintOrder = false;
  urlPrintPreOrder = 'http://172.35.0.219:8068/Viewer/{action}?order=';
  showInformationCreateOrder = false;
  openedPrintPreOrder = false;
  public windowState: WindowState = 'maximized';

  public columns: { field: string, title: string, width: number, textEnd: boolean, }[] = [
    { field: 'data', title: 'Data', width: 100, textEnd: false },
    { field: 'idPreOrder', title: 'N.Orçamento', width: 120, textEnd: false },
    { field: 'status', title: 'Situação', width: 150, textEnd: false },
    { field: 'idCustomer', title: 'Cód.Cliente', width: 100, textEnd: false },
    { field: 'customer', title: 'Cliente', width: 250, textEnd: false },
    { field: 'value', title: 'Valor', width: 120, textEnd: true },
    { field: 'seller', title: 'Vendedor', width: 250, textEnd: false },
  ];
  public bindingType = 'array';
  public gridData: PreOrder[] | GridDataResult = this.preOrders;
  public gridDataResult: GridDataResult = {
    data: this.preOrders,
    total: this.preOrders.length,
  };
  public isLoading: boolean;
  public filterPreOrder = {
    start: '',
    end: '',
    store: '',
    idPreOrder: 0,
    document: '',
    nameCustomer: ''
  };
  showInformation = false;
  titleInformation = 'Consulta de orçamentos';
  messageInformation = '';
  informationDescription = '';


  public vertical: "top" | "bottom" = "top";
  public horizontal: "start" | "end" = "start";

  public position: BadgePosition = "edge";

  openedItensPreOrder = false;
  preOrderItens: PreOrderItens[] = [];


  public get align(): BadgeAlign {
    return { vertical: this.vertical, horizontal: this.horizontal };
  }

  constructor(
    private readonly preOrderService: PreOrderService,
    private readonly shoppingService: ShoppingService,
    private readonly lookupService: LookupService,
    private readonly router: Router,
    private readonly fb: FormBuilder,
  ) { }

  ngOnInit(): void {
    this.store$ = this.lookupService.getStore();
    this.formModelPreOrder = this.fb.group({
      model: new FormControl('B'),
    });
  }

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

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

  public selectedPreOrder({ sender, rowIndex, dataItem }: EditEvent): void {

    if (dataItem.status === "ORÇAMENTO UTILIZADO") {
      this.showInformation = true;
      this.titleInformation = "Alterar Orçamento"
      this.messageInformation = "Orçamento não pode ser editado."
      this.informationDescription = "Orçamento já foi convertido em pedido de venda, alteração não permitida."
      return;
    }

    this.preOrderService.getCartId(dataItem.idPreOrder).pipe(
      map((result) => {
        console.log(result);
        localStorage.setItem('cart', result.cartId);
        localStorage.setItem('customer', JSON.stringify(result.customer));
        localStorage.setItem('paymentPlan', JSON.stringify(result.paymentPlan));
        localStorage.setItem('billing', JSON.stringify(result.billing));
        if (result.partner) {
          localStorage.setItem('partner', JSON.stringify(result.partner));
        }
        if (result.address) {
          localStorage.setItem('address', JSON.stringify(result.address));
        }
        if (result.preCustomer) {
          localStorage.setItem('preCustomer', JSON.stringify(result.preCustomer));
        }
        localStorage.setItem('invoiceStore', JSON.stringify(result.invoiceStore));
        const orderDelivery: OrderDelivery = {
          notification: result.notification1 ?? '',
          notification1: result.notification2 ?? '',
          notification2: '',
          notificationDelivery1: result.notificationDelivery1 ?? '',
          notificationDelivery2: result.notificationDelivery2 ?? '',
          notificationDelivery3: result.notificationDelivery3 ?? '',
          dateDelivery: result.deliveryDate,
          scheduleDelivery: result.squeduleDelivery,
          priorityDelivery: result.priorityDelivery,
        };
        localStorage.setItem('dataDelivery', JSON.stringify(orderDelivery));
        this.router.navigate(['sales/home']);
      }),
      catchError((error) => {
        this.showInformation = true;
        this.titleInformation = 'Consulta de orçamentos';
        this.messageInformation = 'Ops! Houve um erro ao consultar os orçamentos.';
        this.informationDescription = error.message;
        return of(null);
      })
    ).subscribe();
  }

  returnShowInformation() {
    this.showInformation = false;
  }

  closeModelItensPreOrder(action: string) {
    console.log(`Dialog result: ${action}`);
    this.openedItensPreOrder = false;
  }

  showItensPreOrder({ sender, rowIndex, dataItem }: EditEvent): void {
    console.log(dataItem);
    this.preOrderService.getItensPreOrder(dataItem.idPreOrder).subscribe(itens => {
      this.preOrderItens = itens;
      this.openedItensPreOrder = true;
    });
  }

  closeModelPrintPreOrder(action: string) {
    console.log(`Dialog result: ${action}` + ' - ' + this.formModelPreOrder.get('model').value);
    this.openedModelPrintPreOrder = false;
    this.modelPrintPreOrder = this.formModelPreOrder.get('model').value;
    if (action === 'Sim') {
      this.openPrintPreOrder();
    }
  }

  showPrinterPreOrder(data: any): void {
    console.log(data);
    this.preOrderNumber = data.idPreOrder;
    this.openedModelPrintPreOrder = true;
  }

  openPrintPreOrder() {
    // this.urlPrintPreOrder = 'http://localhost:52986//Viewer/{action}?order=' +
    this.urlPrintPreOrder = 'http://172.35.0.219:8068/Viewer/{action}?order=' +
      this.preOrderNumber + '&model=' + this.modelPrintPreOrder;
    this.openedPrintPreOrder = true;
  }

  public openClosePrintPreOrder(isOpened: boolean): void {
    this.openedPrintPreOrder = isOpened;
  }



}
