import { HttpErrorResponse } from '@angular/common/http';
import { Component, ViewChild, OnInit, AfterViewInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { ContentArtitle } from 'src/app/interfaces/acquisition-management/acquisition/artitle.interface';
import { ObjectGetRequest, RequestLines, ResponseDataRequestLines, ResponseRequestLines } from 'src/app/interfaces/acquisition-management/acquisition/order.interface';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { OrderService } from 'src/app/services/acquisition-management/acquisition/order.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { DetailsLineComponent } from './details-line/details-line.component';

@Component({
  selector: 'app-purchase-line',
  templateUrl: './purchase-line.component.html',
  styleUrls: ['./purchase-line.component.css']
})
export class PurchaseLineComponent implements AfterViewInit, OnInit {
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<RequestLines>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public txtBuscador:string;

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public btnSmall: boolean;

  public quantityCarArtitle: number;

  constructor(
    private _encService: EncService,
    private _orderService: OrderService,
    private _resourcesServices: ResourcesService,
    private _dialog: MatDialog,
    private _router: Router,
  ) {
    this.displayedColumns = [ 'ID_LINEA_SOLICITUD', 'DESCRIPCION', 'CANTIDAD', 'FECHA_REGISTRA', 'USUARIO_REGISTRA', 'ESTADO', 'ACCIONES' ];
    this.dataSource = new MatTableDataSource();
    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;
    this.txtBuscador = '';
    this.quantityCarArtitle = null !;
  }
  ngOnInit(): void {
    this.onResize();
    this.getAllRequestLines();
  }

  ngAfterViewInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  // Método para ejecutar una alerta
  public async alert(type: string, dataElement: any = null):Promise<void> {
    this.isLoadingForm = true;
    let dataDialog: AlertData = {} as AlertData;
    if (type === 'CANCEL') {
      dataDialog = {
        icon: "warning",
        title: "Cancelar Solicitud",
        description: "¿Está seguro de cancelar la línea de solicitud de compra?"
      };
    }

    // Se ejecuta la alerta
    const dialogRef = this._dialog.open(AlertComponent, {
      data: dataDialog,
      disableClose: true,
      // width: '500px',
    });

    // Se obtiene la respuesta obtenida por la alerta
    dialogRef.afterClosed().subscribe((result) => {
      if (result && type === 'CANCEL') {
        this.cancelRequestLine(dataElement);
      }
    });
    this.isLoadingForm = false;
  }

  public goBack(steps: number):void {
    window.history.go(steps * -1);
  }

  public async getAllRequestLines():Promise<void> {
    this.isLoading = true;
    await lastValueFrom(this._orderService.getAllRequestLines()).then(
      (data:ResponseRequestLines) => {
        this.dataSource.data =  !data.error ? data.response : [];
      }, (error: HttpErrorResponse) => this._resourcesServices.checkErrors(error)
    );
    this.isLoading = false;
  }

  public async getRequestLine(idRequestLine: string): Promise<ResponseDataRequestLines>{
    return await lastValueFrom(this._orderService.getRequestLine(idRequestLine));
  }

  public async cancelRequestLine(idRequestLine: string):Promise<void>{
    let objGetRequest: ObjectGetRequest = {
      idRequestLine: await this._encService.encriptar(idRequestLine),
      line: await this._encService.encriptar('1'),
      user: this._resourcesServices.getUser(),
    }
    await lastValueFrom(this._orderService.cancelRequestLine(objGetRequest)).then(
      (data:ResponseRequestLines) => {
       if(!data.error){
        this._resourcesServices.openSnackBar('¡La solicitud fue cancelada correctamente!');
        this.getAllRequestLines();
       }
      }, (error: HttpErrorResponse) => this._resourcesServices.checkErrors(error)
    );
  }

  public async createGroup(idRequestLine: string):Promise<void> {
    let encIdRequestLine:string = await this._encService.encriptar(idRequestLine);
    this._router.navigate([`sam/group-request-line/${encIdRequestLine}`]);
  }

  public async openDialog(type:string, dataElement:any = null):Promise<void> {
    this.isLoadingForm = true;
    let encIdRequestLine: string = await this._encService.encriptar(dataElement.ID_LINEA_SOLICITUD);
    let responseDataRequestLines:ResponseDataRequestLines = await this.getRequestLine(encIdRequestLine);
    this.isLoadingForm = false;

    const dialogRef = this._dialog.open(DetailsLineComponent, {
      data: responseDataRequestLines.response,
      disableClose: true,
      width: '1300px',
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
      }
    });
  }

  // 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;
  }

  // Método para dar formato a las fechas y horas
  public formatDate(dateRegister:string, dateUpdate:string | null):string {
    let date:string = (dateUpdate === null) ? dateRegister : dateUpdate;
    let arrDateTime:Array<string> = date.split(' ');
    let arrDate:Array<string> = arrDateTime[0].split('-');
    return `${arrDate[2]}-${arrDate[1]}-${arrDate[0]} ${arrDateTime[1]}`;
  }
}
