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

@Component({
    selector: 'app-get-invoice-control',
    templateUrl: './get-invoice-control.component.html',
    styleUrl: './get-invoice-control.component.css',
    standalone: false
})
export class GetInvoiceControlComponent {
  public isLoadingForm: boolean;

  // public idArchivoPDF: string;
  // public idArchivoXML: string;
  // public description:string;
  // public typeInvoice:string;

  public nameButtonPdf:string;
  public nameButtonXml:string;


  public formGroup: FormGroup;

  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.isLoadingForm = false;
    // this.idArchivoPDF = '';
    // this.idArchivoXML = '';
    // this.typeInvoice = '';
    // this.description = '';

    this.formGroup = this.createFormGroup();

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

  private createFormGroup () {
    return new FormGroup({
      idArchivoPDF: new FormControl('', Validators.required),
      idArchivoXML: new FormControl('', Validators.required),
      typeInvoice: new FormControl('', Validators.required),
      description: new FormControl(''),
    });
  }

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

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

    await this.uploadTempFile(infoUpload, typeDocument);
  }

  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().toString());

    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);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deleteTempFile(idArchivo);
        }
      }
    );
    this.isLoadingForm = false;
  }

  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().toString());

    await lastValueFrom(this._gdelService.uploadTempFile(myFormData)).then(
      (responseDataUploadTempFile: ResponseDataUploadTempFile) => {
        if (!responseDataUploadTempFile.error) {
          if (typeDocument === 'PDF') {
            this.formGroup.controls['idArchivoPDF'].setValue(responseDataUploadTempFile.response.idArchivo);
          } else {
            this.formGroup.controls['idArchivoXML'].setValue(responseDataUploadTempFile.response.idArchivo);
          }
            
          this.resourcesService.openSnackBar(`¡Archivo Subido!`);
        } else {
          this.resourcesService.openSnackBar(responseDataUploadTempFile.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.uploadTempFile(invoice, typeDocument);
        }
      }
    );
    this.isLoadingForm = false;
  }

  public async close() {
    if (this.formGroup.controls['idArchivoPDF'].value !== '') {
      await this.deleteTempFile(this.formGroup.controls['idArchivoPDF'].value);
    }
    
    if (this.formGroup.controls['idArchivoXML'].value !== '') {
      await this.deleteTempFile(this.formGroup.controls['idArchivoXML'].value);
    }

    this._dialogRef.close(false);
  }

  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 compareInvoice() {
    this.isLoadingForm = true;

    const requestInvoice:RequestInvoice = {
      IDARCHIVOPDF: this.formGroup.controls['idArchivoPDF'].value,
      IDARCHIVOXML: this.formGroup.controls['idArchivoXML'].value,
      TYPE_INVOICE: this.formGroup.controls['typeInvoice'].value,
      DESCRIPTION: this.formGroup.controls['description'].value,
      ID_DOCUMENT: null,
      USER: this.resourcesService.getUser(),
      LINE_NUMBER: this.resourcesService.getLineNumber(),
      REQUEST_LINE: this.requestLines.ID_LINEA_SOLICITUD.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}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.compareInvoice();
        }
      }
    );

    this.isLoadingForm = false;
  }
}
