import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { ResourcesService, ResponseData } from '../../../../services/resources.service';
import { InventoryManagementService } from '../../../../services/inventory-management/inventory-management.service';
import { GdelService } from '../../../../services/gdel.service';
import { docClassification } from '../../../../../environments/environment.prod';
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 { RequestFormDocument } from '../../../../interfaces/inventory-management/document-association.interface';

@Component({
    selector: 'app-form-document',
    templateUrl: './form-document.component.html',
    styleUrl: './form-document.component.css',
    standalone: false
})
export class FormDocumentComponent {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public formGroup: FormGroup;
  public arrTypeFile: Array<{category:string,code:string}>;
  public nameButton: string;
  public idArchivo?: string | null;
  
  constructor (
    @Inject(MAT_DIALOG_DATA) public idStock: string,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<boolean>,
    private _inventoryManagementService: InventoryManagementService,
    private _gdelService: GdelService,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.formGroup = this._createFormGroup();
    this.arrTypeFile = docClassification;
    this.nameButton = 'Click para cargar documento';
  }
    
  private _createFormGroup(): FormGroup {
    return new FormGroup({
      NOMBRE_ARCHIVO: new FormControl(null, Validators.required),
      TIPO_ARCHIVO: new FormControl(null, Validators.required),
      ARCHIVO: new FormControl(null, Validators.required),
    });
  }

  public async loadDocument(event: any) {
    const FILE: File = event.target.files[0];
    this.nameButton = FILE.name;
    await this.uploadTempFile(FILE);
  }

  private async uploadTempFile(invoice: File) {
    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) {
          this.formGroup.controls['ARCHIVO'].setValue(responseDataUploadTempFile.response.idArchivo);
          this.resourcesService.openSnackBar(`¡Archivo Cargado!`);
        } else {
          this.nameButton = 'Click para cargar documento';
          this.formGroup.controls['ARCHIVO'].setValue(null);
          this.resourcesService.openSnackBar(responseDataUploadTempFile.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.uploadTempFile(invoice);
        } else {
          this.nameButton = 'Click para cargar documento';
          this.formGroup.controls['ARCHIVO'].setValue(null);
        }
      }
    );
    this.isLoadingForm = false;
  }

  public alert() {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de registrar el documento?`,
        icon: `warning`,
      }
    }).afterClosed().subscribe(async (result) => {
      if (result) {
        await this.registerDocumentOrder();
      }
    });
  }

  private async registerDocumentOrder() {    
    const requestDocument:RequestFormDocument = {
      ID_STOCK: this.idStock,
      NOMBRE_ARCHIVO: this.formGroup.controls['NOMBRE_ARCHIVO'].value,
      TIPO_ARCHIVO: this.formGroup.controls['TIPO_ARCHIVO'].value,
      ARCHIVO: this.formGroup.controls['ARCHIVO'].value,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    };
    await lastValueFrom(this._inventoryManagementService.registerDocumentStock( requestDocument )).then(
      (responseData: ResponseData) => {
        if ( !responseData.error ) {
          this.resourcesService.openSnackBar('¡Registro de Documento Exitoso!');
          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.registerDocumentOrder();
        }
      }
    );
  }
}
