import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { ConfigOrderComponent } from './config-order/config-order.component';
import { GetOrderData, ResponseDataOrder } from 'src/app/interfaces/acquisition-management/order.interface';
import { lastValueFrom } from 'rxjs';
import { OrderService } from 'src/app/services/acquisition-management/order.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { HttpErrorResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { EncService } from 'src/app/services/enc/enc.service';
import { AddStateOrderComponent } from './add-state-order/add-state-order.component';
import { MatPaginator } from '@angular/material/paginator';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { DescriptionLineComponent } from '../purchase-line/description-line/description-line.component';
import { ResponseData } from 'src/app/interfaces/response-data';

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

  public displayedColumns: string[] = ['ORCO_NUOR','PROV_NOCO','DESP_NOMB','MEPA_NOMB','ORCO_FEMO','ORCO_ESTA','ACCIONES'];

  public isLoading: boolean = false;
  public isLoadingForm: boolean = false;

  public btnSmall: boolean = false;
  public txtBuscador:string;

  public dataSource: MatTableDataSource<GetOrderData> ;

  @ViewChild(MatPaginator) paginator!: MatPaginator;

  constructor(
    public dialog: MatDialog,
    public resourcesService: ResourcesService,
    private _orderService: OrderService,
    private _router: Router,
    private _encService: EncService,
  ) {
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource<GetOrderData>();
  }

  ngOnInit(): void {
    this.onResize();
    this.getOrders();
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }

  public async getOrders() {
    this.isLoading = true;
    await lastValueFrom(this._orderService.getOrders()).then(
      (responseData: ResponseDataOrder) => {
        if ( !responseData.error ) {
          this.dataSource.data = responseData.response;
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public openForm() {
    // const dialogRef = this.dialog.open(ConfigOrderComponent, {
  }

  public async getInformationOrder( element: GetOrderData) {
    let encOrderNumber: string = await this._encService.encriptar( element.ORCO_NUOR );
    let encProviderNumber: string = await this._encService.encriptar( element.PROV_NUPR );
    this._router.navigate(['/sam/details-order/' + encOrderNumber + '/' + encProviderNumber]);
  }

  public async getDocumentOrder( element: GetOrderData ) {
    console.log(element.ORCO_NUOR);

    let encOrderNumber: string = await this._encService.encriptar( element.ORCO_NUOR );
    this._router.navigate(['/sam/document-order/' + encOrderNumber]);
  }

  public openDialog(typeDialog: string, dataElement: GetOrderData) {
    if (typeDialog === 'STATE') {
      this.dialog.open(AddStateOrderComponent, {
        width: '1200px',
        disableClose: true,
        data: dataElement.ORCO_NUOR
      });
    } else if (typeDialog === 'REORDER') {
      this.dialog.open(DescriptionLineComponent, {
        width: '700px',
        disableClose: true,
      }).afterClosed().subscribe((result:any) => {
        if (result) {
          this.reorderArtitles( dataElement.ORCO_NUOR, result );
        }
      });
    }
  }

  public alert(typeAlert: string, dataElement: GetOrderData) {
    if (typeAlert === 'REORDER') {
      this.dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          icon: 'warning',
          title: 'Reordenar Línea de Solicitud',
          description: '¿Está seguro de volver a pedir los artículos de la orden de compra?'
        }
      }).afterClosed().subscribe( (result:any) => {
        if (result) {
          this.openDialog(typeAlert, dataElement);
        }
      });
    }
  }

  private async reorderArtitles(numberOrder: string, description:string) {
    await lastValueFrom(this._orderService.reorderArtitles({
      ORDEN: await this._encService.encriptar(numberOrder.toString()),
      DESCRIPCION: description,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: '1'
    })).then(
      (responseData: ResponseData) => {
        if ( !responseData.error ) {
          this.resourcesService.openSnackBar('¡La Línea de Solicitud de Articulos se Registró Correctamente!');
          this.resourcesService.openSnackBarAfter('La Solicitud se Encontrará el Proceso de Validación por el Módulo de Gestión de Presupuesto');
          this._router.navigate(['/sam/purchase-requisition-lines']);
        } else{
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  // Método de filtrado de datos
  public applyFilter(event: any, type: string):void {
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

}
