import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { RequestInvoice } from 'src/app/interfaces/acquisition-management/invoice.interface';
import { RequestLines } from 'src/app/interfaces/acquisition-management/order.interface';
import { ResponseDataUploadTempFile } from 'src/app/interfaces/gdel.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { InvoiceService } from 'src/app/services/acquisition-management/invoice.service';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-get-invoice-control',
  templateUrl: './get-invoice-control.component.html',
  styleUrls: ['./get-invoice-control.component.css']
})
export class GetInvoiceControlComponent {

  public idArchivoPDF: string;
  public idArchivoXML: string;
  public isLoadingForm: boolean;

  public nameButtonPdf:string;
  public nameButtonXml:string;

  public typeInvoice:string;
  public description:string;

  constructor(
    public resourcesService: ResourcesService,
    private _gdelService: GdelService,
    @Inject(MAT_DIALOG_DATA) public requestLines: RequestLines,
    private invoiceService: InvoiceService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<boolean>,
  ) {
    this.idArchivoPDF = '';
    this.idArchivoXML = '';
    this.isLoadingForm = false;
    this.typeInvoice = '';
    this.description = '';

    this.nameButtonPdf = 'Subir PDF';
    this.nameButtonXml = 'Subir XML';
  }

  public async loadFile(event:any, typeDocument: string) {
    let infoUpload: File = event.target.files[0];

    if (typeDocument === 'PDF' && this.idArchivoPDF !== '') {
      await this.deleteTempFile(this.idArchivoPDF);
      this.idArchivoPDF = '';
      this.nameButtonPdf = infoUpload.name;
    } else if (typeDocument === 'PDF') {
      this.nameButtonPdf = infoUpload.name;
    }
    if (typeDocument === 'XML' && this.idArchivoXML !== '') {
      await this.deleteTempFile(this.idArchivoPDF);
      this.idArchivoXML = '';
      this.nameButtonXml = infoUpload.name;
    } else if (typeDocument === 'XML') {
      this.nameButtonXml = infoUpload.name;
    }

    await this.uploadTempFile(infoUpload, typeDocument);
  }

  public alert() {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        icon: "warning",
        title: "Confirmación",
        description: `¿Está seguro de subir la información de la factura?`
      },
    }).afterClosed().subscribe((result) => {
      if (result ) {
        this.compareInvoice();
      }
    });
  }

  private async uploadTempFile(invoice: File, typeDocument: string) {
    this.isLoadingForm = true;    
    this.resourcesService.openSnackBar(`Subiendo Archivo ...`);
    let myFormData = new FormData();
    myFormData.append('file', invoice!);
    myFormData.append('id_user', this.resourcesService.getUser());
    myFormData.append('linea', this.resourcesService.getLineNumber());

    await lastValueFrom(this._gdelService.uploadTempFile(myFormData)).then(
      (responseDataUploadTempFile: ResponseDataUploadTempFile) => {
        if (!responseDataUploadTempFile.error) {
          if (typeDocument === 'PDF') {
            this.idArchivoPDF = responseDataUploadTempFile.response.idArchivo;
          } else {
            this.idArchivoXML = responseDataUploadTempFile.response.idArchivo;
          }
            
          this.resourcesService.openSnackBar(`¡Archivo Subido!`);
        } else {
          this.resourcesService.openSnackBar(responseDataUploadTempFile.msg);
        }
      }, (httpErrorResponse:HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }

  private async deleteTempFile(idArchivo:string) {
    this.isLoadingForm = true;
    this.resourcesService.openSnackBar(`Eliminando Archivo Anterior ...`);
    var myFormData = new FormData();
    myFormData.append('id_file', idArchivo);
    myFormData.append('id_user', this.resourcesService.getUser());
    myFormData.append('linea', this.resourcesService.getLineNumber());

    await lastValueFrom(this._gdelService.deleteTempFile(myFormData)).then(
      (responseData: ResponseDataUploadTempFile) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Eliminación del archivo temporal exitosa!`);
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  private async compareInvoice() {
    this.isLoadingForm = true;

    const requestInvoice:RequestInvoice = {
      IDARCHIVOPDF: this.idArchivoPDF,
      IDARCHIVOXML: this.idArchivoXML,
      TYPE_INVOICE: this.typeInvoice,
      DESCRIPTION: this.description,
      ID_DOCUMENT: null,
      USER: this.resourcesService.getUser(),
      LINE_NUMBER: this.resourcesService.getLineNumber(),
      REQUEST_LINE: this.requestLines.LINE_IDLI.toString(),
    }

    await lastValueFrom(this.invoiceService.compareInvoice(requestInvoice)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡La comparación de factura ha sido exitosa!`);
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse:HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );

    this.isLoadingForm = false;
  }

  public async close() {
    if (this.idArchivoPDF !== '') {
      await this.deleteTempFile(this.idArchivoPDF);
    }
    
    if (this.idArchivoXML !== '') {
      await this.deleteTempFile(this.idArchivoXML);
    }

    this._dialogRef.close(true);
  }
}


