import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { WindowState } from '@progress/kendo-angular-dialog';
import { EditEvent } from '@progress/kendo-angular-grid';
import { Observable, of, Subscription } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { OrderDelivery } from 'src/app/models/order-delivery.model';
import { OrderItens } from 'src/app/models/order-itens.model';
import { Order } from 'src/app/models/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';
import { AuthService } from '../../../auth/services/auth.service';
import { PixReceiveService } from '../../../services/pix-receive.service';
import { PixOrder } from 'src/app/models/pix-order.model';
import {
  createQRCodeValidator,
  QRCodeEncoding,
} from "@progress/kendo-angular-barcodes";

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

  store$: Observable<StoreERP[]>;
  subscriptionOrders: Subscription;
  selectStore: StoreERP;
  orders: Order[] = [];
  public loadingIcon = '';
  //  sellers$: Observable<Seller[]>;
  public filterPreOrder = {
    start: '',
    end: '',
    store: '',
    idOrder: ' ',
  };
  formFilterOrder: FormGroup;
  isLoading = false;
  public columns: { field: string, title: string, width: number, textEnd: boolean, }[] = [
    { field: 'createDate', title: 'Data', width: 100, textEnd: false },
    { field: 'orderId', title: 'N.Pedido', width: 120, textEnd: false },
    { field: 'status', title: 'Situação', width: 100, textEnd: false },
    { field: 'customerId', title: 'Cód.Cliente', width: 100, textEnd: true },
    { field: 'customerName', title: 'Cliente', width: 250, textEnd: false },
    { field: 'orderValue', title: 'Valor', width: 120, textEnd: true },
  ];
  showInformation = false;
  titleInformation = 'Consulta de pedidos de venda';
  messageInformation = '';
  informationDescription = '';
  statusOrder = '';

  showInformationSeller = false;

  openedItensOrder = false;
  orderItens: OrderItens[];

  urlPrintOrder = '';
  modelPrintOrder = 'A';
  openedModelPrintOrder = false;
  openedPrintOrder = false;
  formModelOrder: FormGroup;
  orderNumber = 0;
  orderStatus = '';
  public windowState: WindowState = 'maximized';

  /* Receive order  */
  showReceivePix = false;
  formReceivePix: FormGroup;
  pixValue = 0;
  orderSelected: Order;
  qrCodePix: '';
  processPix = false;
  showQrCode = false;
  public readonly encoding: QRCodeEncoding = "ISO_8859_1";
  openedPrintReceivePix = false;
  urlPrintCreditPix = '';

  loadingPanelVisible = false;

  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,
    private readonly pixReceiveService: PixReceiveService,
  ) { }

  ngOnInit(): void {
    this.formFilterOrder = this.fb.group({
      document: new FormControl('', []),
      nameCustomer: new FormControl('', []),
    });
    this.store$ = this.lookupService.getStore();
    this.formModelOrder = this.fb.group({
      model: new FormControl("A"),
    });
    this.formReceivePix = this.fb.group({
      pixValue: new FormControl(),
    });

  }

  ngOnDestroy(): void {
    if (this.subscriptionOrders != null) {
      this.subscriptionOrders.unsubscribe();
    }
  }

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

  async getOrders() {
    console.log(JSON.stringify(this.filterPreOrder));
    this.loadingIcon = 'loading';
    this.orders = [];
    const document = this.formFilterOrder.get('document').value;
    const name = this.formFilterOrder.get('nameCustomer').value.toUpperCase();
    this.subscriptionOrders = this.orderService.getOrders(this.filterPreOrder.store, this.filterPreOrder.start,
      this.filterPreOrder.end, document, name, this.filterPreOrder.idOrder).pipe(
        map((result) => {
          this.loadingIcon = '';
          this.orders = result as Order[];
          console.log(this.orders);
        }),
        catchError((error) => {
          this.loadingIcon = '';
          console.log('erro ao consultar pedido de venda.');
          return of(null);
        })
      ).subscribe();
  }

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

    if (dataItem.status == 'FATURADO' || dataItem.status == 'MONTADO') {
      this.statusOrder = dataItem.status;
      this.messageInformation = "Pedido não pode ser alterado!"
      this.informationDescription = `Pedido encontra-se ${dataItem.status} sua alteração não é permitida.`;
      this.showInformation = true;
      return;
    }

    if (dataItem.pixCreate == 'S') {
      this.statusOrder = dataItem.status;
      this.messageInformation = "Pedido não pode ser alterado!"
      this.informationDescription = `PIX já gerado para este pedido, alteração não é permitida.`;
      this.showInformation = true;
      return;
    }


    const sellerId = this.authService.getSeller();

    if (dataItem.sellerId !== sellerId && (!this.authService.isManager())) {
      this.showInformationSeller = true;
      return;
    }



    this.orderService.getCartId(dataItem.orderId).pipe(
      map((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));
        }
        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,
          priorityDelivery: result.priorityDelivery,
          scheduleDelivery: result.scheduleDelivery,
        };
        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();
  }

  closeInformation(close: boolean) {
    this.showInformation = close;
  }

  closeInformationSeller(close: boolean) {
    this.showInformationSeller = close;
  }

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

  showItensOrder({ sender, rowIndex, dataItem }: EditEvent): void {
    console.log(dataItem);
    this.orderService.getItensOrder(dataItem.orderId).subscribe(itens => {
      this.orderItens = itens;
      this.openedItensOrder = true;
    });
  }

  showItensOrder2(data: any): void {
    console.log(data);
    this.orderNumber = data.orderId;
    this.openedModelPrintOrder = true;
    // this.orderService.getItensOrder(dataItem.orderId).subscribe(itens => {
    //   this.orderItens = itens;
    //   this.openedItensOrder = true;
    // });
  }

  openPrintOrder() {
    //this.urlPrintOrder = 'http://localhost:52986/Viewer/{action}?orderId=' +
    //'http://172.35.0.219:8068/Viewer/{action}?orderId=' +
    this.urlPrintOrder = 'http://172.35.0.219:8068/Viewer/{action}?orderId=' +
      this.orderNumber + '&model=' + this.modelPrintOrder;
    this.titleInformation = 'Gravar pedido de venda';
    this.openedPrintOrder = true;
  }

  closeModelPrintOrder(action: string) {
    this.openedModelPrintOrder = false;
    this.modelPrintOrder = this.formModelOrder.get('model').value;
    if (action === 'Sim') {
      this.openPrintOrder();
    }
  }

  public openClosePrintOrder(isOpened: boolean): void {
    this.openedPrintOrder = isOpened;
  }

  openPrintReceivePix() {
    this.urlPrintCreditPix = 'http://172.35.0.219:8068/Viewer/{action}?order=' +
      this.orderNumber;
    this.titleInformation = 'Recibo pagamento via PIX';
    this.openedPrintReceivePix = true;
  }

  closePrintReceivePix(action: string) {
    this.openedPrintReceivePix = false;
    if (action === 'Sim') {
      this.openPrintReceivePix();
    }
  }

  closeReceivePix(action: string) {

    if (action !== 'Sim') {
      this.showReceivePix = false;
      return;
    }

    if (action === 'Sim') {
      if (this.pixValue < this.formReceivePix.get('pixValue').value) {
        this.showReceivePix = false;
        this.titleInformation = 'Geração pix';
        this.messageInformation = 'Valor do PIX inválido!';
        this.informationDescription = 'O Valor do PIX não pode ser superior ao valor do pedido de venda!';
        this.showInformation = true;
        return;
      }
      this.pixValue = this.formReceivePix.get('pixValue').value;

      const pixOrder: PixOrder = {
        customerId: this.orderSelected.customerId,
        orderId: this.orderSelected.orderId,
        amount: this.pixValue,
      };
      this.processPix = true;
      this.pixReceiveService.create(pixOrder).pipe(
        map((result) => {
          this.qrCodePix = result.qrCode;
          console.log(result);
          this.processPix = false;
          this.showQrCode = true;
        }),
        catchError((error) => {
          console.log('Erro ao gerar pix');
          console.log(error);
          this.processPix = false;
          this.showReceivePix = false;
          this.showInformation = true;
          this.titleInformation = 'Pedido de venda';
          this.messageInformation = 'Erro ao criar cobrança PIX';
          this.informationDescription = error.message;
          return of(null);
        })
      ).subscribe();


    }
  }

  public openReceivePix(isOpened: boolean, order: any): void {
    if (isOpened) {
      if (order.status == "FATURADO") {
        this.titleInformation = 'Geração pix';
        this.messageInformation = 'Pedido já esta FATURADO!';
        this.informationDescription = 'Para geração do PIX o pedido deve estar na posição LIBERADO ou BLOQUEADO.';
        this.showInformation = true;
        return;
      }
      if (order.customerId == 1) {
        this.titleInformation = 'Geração pix';
        this.messageInformation = 'Não é permido gerar PIX para CONSUMIDOR FINAL!';
        this.informationDescription = 'Para geração do PIX é necessário identificar o cliente no pedido de venda!';
        this.showInformation = true;
        return;
      }
      this.orderSelected = order;
      this.pixValue = Number.parseFloat(order.orderValue.toFixed(2));
      this.formReceivePix.patchValue({
        pixValue: Number.parseFloat(order.orderValue.toFixed(2)),
      });
    }

    console.log(JSON.stringify(order));

    this.loadingPanelVisible = true;
    this.pixReceiveService.find(order.orderId)
      .pipe(
        map(pix => {
          console.log(JSON.stringify(pix));
          if (pix == null) {
            this.showQrCode = false;
            this.showReceivePix = isOpened;
            this.loadingPanelVisible = false;
          } else {
            if (pix.status == "CONCLUIDA") {
              this.orderNumber = pix.orderId;
              this.loadingPanelVisible = false;
              this.openPrintReceivePix();
            } else {
              console.log(JSON.stringify(pix));
              this.qrCodePix = pix.qrCode;
              this.pixValue = pix.valor.original;
              this.loadingPanelVisible = false;
              this.showQrCode = true;
              this.showReceivePix = isOpened;
            }
          }
        }),
        catchError((error) => {
          console.log(error);
          this.loadingPanelVisible = false;
          this.showReceivePix = false;
          this.showInformation = true;
          this.titleInformation = 'Pedido de venda';
          this.messageInformation = 'Erro ao consultar dados do PIX, comunique ao TI.';
          this.informationDescription = error.message;
          return of(null);
        })
      ).subscribe();

  }

}
