import { AfterViewInit, Component, OnInit, ViewChild } 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 { DocumentFormComponent } from '../document-form/document-form.component';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ActivatedRoute } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { OrderDocumentsService } from 'src/app/services/acquisition-management/order-documents.service';
import { TypeDocumentsService } from 'src/app/services/document-management/type-documents.service';
import { GetTypeDocument, ResponseDataGetTypeDocument } from 'src/app/interfaces/document-management/type-document.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { GetDocumentOrder, ResponseDataGetDocumentOrder } from 'src/app/interfaces/acquisition-management/document-order.interface';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { ResponseData } from 'src/app/interfaces/response-data';

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

  public displayedColumns: Array<string> = ['DOOR_IDDO','DOOR_CODO','DOOR_DESC','TIDO_TIPO','DOOR_FEMO','DOOR_VERS','DOOR_ESTA','ACCIONES'];

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


  public btnSmall: boolean = false;

  public dataSource: MatTableDataSource<GetDocumentOrder>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public txtBuscador:string;

  public numberOrder:string;

  constructor(
    public dialog: MatDialog,
    private _activatedRouter: ActivatedRoute,
    private _encService: EncService,
    public resourcesService: ResourcesService,
    private orderDocumentsService: OrderDocumentsService,
    private typeDocumentsService: TypeDocumentsService,
    private _dialog: MatDialog,
  ) {
    this.dataSource = new MatTableDataSource();
    this.txtBuscador = '';
    this.numberOrder = '';
  }

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

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

  public async getDataURL() {
    this.isLoading = true;
    let encOrderNumber = this._activatedRouter.snapshot.paramMap.get('numberOrder')!;
    this.numberOrder = await this._encService.desencriptar(encOrderNumber)!;

    this.getDocuments(encOrderNumber);
  }

  public async getDocuments(encOrderNumber: string){
    await lastValueFrom(this.orderDocumentsService.getDocumentsByOrder(encOrderNumber)).then(
      (responseData: ResponseDataGetDocumentOrder) => {
        if ( !responseData.error ) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public async openDialog(action: string, dataElement?: GetDocumentOrder) {
    if (action === 'REG') {
      let arrTypeDocuments = await this.getTypeDocuments();
      if (arrTypeDocuments) {
        this.dialog.open(DocumentFormComponent, {
          width: '450px',
          disableClose: true,
          data: {
            arrTypeDocuments: arrTypeDocuments,
            orden: this.numberOrder,
            formData: null
          }
        }).afterClosed().subscribe((result) => {
          if (result) {
            this.getDataURL();
          }
        });
      }
    } else if (action === 'UPD') {
      let arrTypeDocuments = await this.getTypeDocuments();
      if (arrTypeDocuments) {
        this.dialog.open(DocumentFormComponent, {
          width: '450px',
          disableClose: true,
          data: {
            arrTypeDocuments: arrTypeDocuments,
            orden: this.numberOrder,
            formData: dataElement
          }
        }).afterClosed().subscribe((result:any) => {
          if (result) {
            this.getDataURL();
          }
        });
      }
    }

  }

  public async getTypeDocuments(){
    this.isLoadingForm = true;
    return await lastValueFrom(this.typeDocumentsService.getTypeDocuments()).then(
      (responseData: ResponseDataGetTypeDocument) => {
        let getResponse: Array<GetTypeDocument> |  boolean;
        if ( !responseData.error ) {
          getResponse = responseData.response;
        } else {
          getResponse = false
          this.resourcesService.openSnackBar(responseData.msg);
        }
        this.isLoadingForm = false;
        return getResponse;
      }, (error: HttpErrorResponse) => {
        this.resourcesService.checkErrors(error);
        this.isLoadingForm = false;
        return false;
      }
    );

  }

  public getItemDocument(documentCode: string, type: string){
    let response: string = '';
    let arrCodeDocument: Array<string> = documentCode.split('=');

    if ( type === 'VERSION' ) {
      let arrCode = arrCodeDocument[0].split('-');
      response = arrCode[5];
    } else if ( type === 'NAME' ) {
      response = arrCodeDocument[1];
    }

    return response;
  }

  public async alert(type: string, dataElement?: GetDocumentOrder):Promise<void> {
    if (type === 'ELIM') {
      this._dialog.open(AlertComponent, {
        data: {
          icon: "warning",
          title: "Eliminar Documento",
          description: "¿Está seguro de eliminar el documento?",
        },
        disableClose: true,
        width: '400px'
      }).afterClosed().subscribe((result) => {
        if ( result ) {
          this.deleteDocumentOrder(dataElement?.DOOR_IDDO!);
        }
      });

    }else if (type === 'DOWNLOAD') {
      this._dialog.open(AlertComponent, {
        data: {
          icon: "warning",
          title: "Redireccionamiento",
          description: "¿Esta seguro de descargar el documento?",
        },
        disableClose: true,
        width: '400px'
      }).afterClosed().subscribe((result) => {
        if ( result ) {
          this.redirectLink( dataElement!.DOOR_TIPO, dataElement!.DOOR_CODO);
        }
      });
    }
  }

  private async deleteDocumentOrder(idDocument: number) {
    await lastValueFrom( this.orderDocumentsService.deleteDocumentOrder({
      ID_DOCUMENTO: idDocument,
      NUMERO_LINEA: '1',
      USUARIO: this.resourcesService.getUser()
    })).then(
      ( responseData: ResponseData ) => {
        if ( !responseData.error ) {
          this.resourcesService.openSnackBar('¡Eliminación de Documento Exitoso!');
          this.getDataURL();
        } 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();
    }
  }

  public redirectLink( tpyeDocument: string, codeDocument: string) {
    window.open(`http://192.168.1.4:8000/storage/GEAD/${tpyeDocument}/${codeDocument}`, '_blank');
  }

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

}
