import { DialogRef } from '@angular/cdk/dialog';
import { HttpErrorResponse } from '@angular/common/http';
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 { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { GetDocumentOrder, RegisterFormDocument } from 'src/app/interfaces/acquisition-management/document-order.interface';
import { GetTypeDocument } from 'src/app/interfaces/document-management/type-document.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { OrderDocumentsService } from 'src/app/services/acquisition-management/order-documents.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

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

  public formGroup: FormGroup;
  public labelDocument: string;
  public documentExtension: string;
  public inputFileDisable: boolean;
  public isLoadingForm: boolean;
  public fileDocument?: File;
  public titleForm: string;

  constructor(
    @Inject(MAT_DIALOG_DATA) public elementDialog: { arrTypeDocuments: Array<GetTypeDocument>; formData?: GetDocumentOrder, orden: string },
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _orderDocumentsService: OrderDocumentsService,
    private _dialogRef: MatDialogRef<any>,
  ) {
    this.formGroup = this.createFromGroup();
    this.labelDocument = "Seleccionar Documento";
    this.documentExtension = '*';
    this.inputFileDisable = true;
    this.isLoadingForm = false;
    this.titleForm = '';
  }

  ngOnInit(): void {
    if ( this.elementDialog.formData !== null ) {
      this.titleForm = 'Modificación de Documento';
      this.setDataForm(this.elementDialog.formData!);
    } else {
      this.titleForm = 'Registro de Documento';

    }
  }

  // Creación de formulario de registro de módulos
  private createFromGroup(): FormGroup {
    return new FormGroup({
      ID_DOCUMENT: new FormControl(''),
      CODE_DOCUMENT: new FormControl(''),
      ORDEN: new FormControl(this.elementDialog.orden, Validators.required),
      DESCRIPCION: new FormControl('', Validators.required),
      TIPO: new FormControl('', Validators.required),
      NAME_DOCUMENT: new FormControl('', Validators.required),
      DOCUMENTO: new FormControl('', Validators.required),
      USUARIO: new FormControl(this.resourcesService.getUser(), Validators.required),
      NUMERO_LINEA: new FormControl('1', Validators.required),
    });
  }

  private setDataForm( formData: GetDocumentOrder ) {
    this.isLoadingForm = true;

    this.ID_DOCUMENT.setValue( formData.DOOR_IDDO );
    this.DESCRIPCION.setValue( formData.DOOR_DESC );
    this.NAME_DOCUMENT.setValue( formData.DOOR_CODO );
    this.DOCUMENTO.setValue( "unmodified" );
    this.CODE_DOCUMENT.setValue( formData.DOOR_CODO.split('=')[0] );

    this.inputFileDisable = false;
    let getType: GetTypeDocument = this.elementDialog.arrTypeDocuments.find((element:GetTypeDocument) => element.TIDO_ACRO === formData.DOOR_TIPO )!;
    this.TIPO.setValue( getType );
    this.selectedTypeDocument();
    this.labelDocument = formData.DOOR_CODO;

    this.isLoadingForm = false;
  }

  // Ejecuta el input file
  public getFile() {
    if (!this.inputFileDisable) {
      document.getElementById("upfile")!!.click();
    }
  }

  // Método para cargar la imagen
  public async loadDocument(event: any) {
    this.fileDocument = event.target.files[0];

    if ( this.fileDocument === undefined ) {
      this.labelDocument = "Seleccionar Documento";
      this.NAME_DOCUMENT.setValue('');
      if ( this.elementDialog.formData !== null ) {
        this.DOCUMENTO.setValue( "unmodified" );
      } else {
        this.DOCUMENTO.setValue('');
      }
    } else {

      await this.resourcesService.convertisBase64(this.fileDocument).then((document: any) => {
        this.DOCUMENTO.setValue(document.base);
      });

      if ( this.DOCUMENTO.value === 'data:') {
        this.labelDocument = "Seleccionar Documento";
        if ( this.elementDialog.formData !== null ) {
          this.DOCUMENTO.setValue( "unmodified" );
        } else{
          this.DOCUMENTO.setValue( "" );
        }
        this.resourcesService.openSnackBar('El documento se encuentra vacio, favor de subir un documento con información en su contenido.');
      }else{
        this.labelDocument = this.fileDocument?.name!;
        this.NAME_DOCUMENT.setValue(this.labelDocument);

      }
    }
  }

  public selectedTypeDocument() {
    let objTypeDocument: GetTypeDocument = this.TIPO.value;
    let arrExtension: Array<string> = JSON.parse(objTypeDocument.TIDO_EXTE);
    let strExtension: string = '';
    arrExtension.map((extension:string) => {
      extension = extension.trim();
      extension = extension.toLowerCase();
      strExtension += '.' + extension + ', ';
    });

    this.documentExtension = strExtension.substring(0, strExtension.length - 2);
    this.inputFileDisable = false;

    const elementInputFile: HTMLInputElement = <HTMLInputElement>document.getElementById('upfile')!;
    elementInputFile.value = '';
    this.labelDocument = "Seleccionar Documento";

  }

  public alert() {
    this._dialog.open(AlertComponent, {
      data: {
        icon: 'warning',
        title: 'Registro de Documento',
        description: '¿Está seguro de registrar el documento?',
      }
    }).afterClosed().subscribe((result: boolean) => {
      if (result) {
        if ( this.elementDialog.formData !== null ) {
          this.updateDocumentOrder();
        } else {
          this.registerDocumentOrder();
        }
      }
    });
  }

  private async registerDocumentOrder() {
    await lastValueFrom(this._orderDocumentsService.registerDocumentOrder( this.generateObjectRequest() )).then(
      (responseData: ResponseData) => {
        if ( !responseData.error ) {
          this.resourcesService.openSnackBar('¡Registro de Documento Exitoso!');
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  private async updateDocumentOrder() {
    await lastValueFrom(this._orderDocumentsService.updateDocumentOrder(this.generateObjectRequest())).then(
      (responseData: ResponseData) => {
        if ( !responseData.error ) {
          this.resourcesService.openSnackBar('¡Modificación de Documento Exitoso!');
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  private generateObjectRequest(): RegisterFormDocument{
    return {
      ID_DOCUMENT: this.ID_DOCUMENT.value,
      CODE_DOCUMENT: this.CODE_DOCUMENT.value,
      ORDEN: this.ORDEN.value,
      DESCRIPCION: this.DESCRIPCION.value.trim(),
      TIPO: this.TIPO.value.TIDO_ACRO,
      NAME_DOCUMENT: this.NAME_DOCUMENT.value,
      DOCUMENTO: this.DOCUMENTO.value,
      USUARIO: this.USUARIO.value,
      NUMERO_LINEA: this.NUMERO_LINEA.value,
    }
  }

  get ID_DOCUMENT() { return this.formGroup.get('ID_DOCUMENT')!; }
  get CODE_DOCUMENT() { return this.formGroup.get('CODE_DOCUMENT')!; }
  get ORDEN() { return this.formGroup.get('ORDEN')!; }
  get DESCRIPCION() { return this.formGroup.get('DESCRIPCION')!; }
  get TIPO() { return this.formGroup.get('TIPO')!; }
  get NAME_DOCUMENT() { return this.formGroup.get('NAME_DOCUMENT')!; }
  get DOCUMENTO() { return this.formGroup.get('DOCUMENTO')!; }
  get USUARIO() { return this.formGroup.get('USUARIO')!; }
  get NUMERO_LINEA() { return this.formGroup.get('NUMERO_LINEA')!; }
}
