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 { InformationArtitle } from 'src/app/interfaces/acquisition-management/artitle.interface';
import { InformationsData, ResponseDataProviderInformation } from 'src/app/interfaces/acquisition-management/provider.interface';
import { UnitService } from 'src/app/services/acquisition-management/unit.service';
import { ProviderService } from 'src/app/services/acquisition-management/provider.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { FileSelected } from 'src/app/interfaces/upload-files.interface';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { ResponseDataUploadTempFile } from 'src/app/interfaces/gdel.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';

export interface DialogData {
  dataSource: Array<InformationArtitle>,
  elementData: InformationArtitle,
}

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

  public formGroupInformation: FormGroup;
  
  public arrProvider: Array<InformationsData>;
  public arrUnits: Array<UnitData>;
  public arrFileSelected: Array<FileSelected>;
  public arrRegisterImages: Array<string>;
  
  public type: string;

  public isLoading: boolean;
  public isLoadingForm: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: DialogData,
    public resourcesService: ResourcesService,
    private _providerServices: ProviderService,
    private _unitService: UnitService,
    private _gdelService: GdelService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<InformationsData>,
  ) {

    this.formGroupInformation = this.createFormGroup();
    this.isLoading = false;
    this.isLoadingForm = false;

    this.type = this.dataDialog.elementData === undefined ? 'REG' : 'MOD';
    this.arrProvider = [];
    this.arrUnits = [];
    this.arrFileSelected = [];
    this.arrRegisterImages = [];
  }

  async ngOnInit() {
    await this.getProvidersActives();
    if (this.dataDialog.elementData !== undefined) {
      this.setDataForm();
    }
    this.getUnits();

  }

  private async setDataForm () {
    this.isLoading = true;

    let objProvider:InformationsData = this.arrProvider.find((element:InformationsData) => element.PROV_NUPR === this.dataDialog.elementData.PROVEEDOR.PROV_NUPR)!;
    
    this.formGroupInformation.controls['NO'].setValue(this.dataDialog.elementData.NO);
    this.formGroupInformation.controls['DESCRIPCION'].setValue(this.dataDialog.elementData.DESCRIPCION);
    this.formGroupInformation.controls['CARACTERISTICAS'].setValue(this.dataDialog.elementData.CARACTERISTICAS);
    this.formGroupInformation.controls['TIPO_UNIDAD'].setValue(this.dataDialog.elementData.TIPO_UNIDAD);
    this.formGroupInformation.controls['PROVEEDOR'].setValue(objProvider);
    this.formGroupInformation.controls['COMPRA_WEB'].setValue(this.dataDialog.elementData.COMPRA_WEB);
    this.formGroupInformation.controls['DETAILS'].setValue(this.dataDialog.elementData.DETAILS);
    this.formGroupInformation.controls['IMAGEN'].setValue(this.dataDialog.elementData.IMAGEN);
    this.formGroupInformation.controls['DATA_IMAGEN'].setValue(this.dataDialog.elementData.DATA_IMAGEN);

    
    if ( this.dataDialog.elementData.ESTADO !== 'Nuevo' && this.dataDialog.elementData.DATA_IMAGEN.length === 0) {
      this.dataDialog.elementData.IMAGEN.forEach(async element => {
        let arrUrl: Array<string> = element.split('/');
        let codeDocument = arrUrl.pop();
        if (codeDocument === undefined) {
          this.resourcesService.openSnackBar(`No se pudo obtener el código de las imágenes del artículo.`);
          this._dialogRef.close();
          return;
        }
        
        let encCodeDocument: string = await this._encService.encrypt(codeDocument);
        this.arrRegisterImages.push(encCodeDocument);
        
        let arrCode: Array<string> = element.split('=');
        let fileName = arrCode.pop();
        if (fileName === undefined) {
          this.resourcesService.openSnackBar(`No se pudo obtener el nombre de las imágenes del artículo.`);
          this._dialogRef.close();
          return;
        }
        this.arrFileSelected.push({
          id: encCodeDocument,
          file: new File(['foo'], fileName),
          view: element,
          state: 'REGISTRADO',
        });
      });
    } else if (this.dataDialog.elementData.ESTADO !== 'Nuevo' && this.dataDialog.elementData.DATA_IMAGEN.length > 0) {
      this.arrFileSelected = this.dataDialog.elementData.DATA_IMAGEN;

      this.dataDialog.elementData.DATA_IMAGEN.forEach(element => {
        this.arrRegisterImages.push(element.id);
      });
    } else {
      this.arrFileSelected = this.dataDialog.elementData.DATA_IMAGEN;
    }
    console.log( this.dataDialog.elementData.ESTADO );
    
    if ( this.dataDialog.elementData.ESTADO !== 'Nuevo' ) {
      this.formGroupInformation.controls['ESTADO']?.setValue('Modificado');
    }
    
    this.isLoading = false;
  }

  private createFormGroup() {
    return new FormGroup({
      'NO': new FormControl('1', Validators.required),
      'IMAGEN': new FormControl([]),
      'DATA_IMAGEN': new FormControl([]),
      'DESCRIPCION': new FormControl('', Validators.required),
      'CARACTERISTICAS': new FormControl(''),
      'TIPO_UNIDAD': new FormControl('', Validators.required),
      'PROVEEDOR': new FormControl('', Validators.required),
      'COMPRA_WEB': new FormControl(false),
      'ESTADO': new FormControl('Nuevo', Validators.required),
      'DETAILS': new FormControl([]),
      'DELETE_FILE': new FormControl([]),
    });
  }

  private async getUnits() {
    this.isLoading = true;
    await lastValueFrom(this._unitService.getUnitsActives()).then(
      (responseData: ResponseDataUnit) => {
        this.arrUnits = responseData.response;
      }, (error:HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }
  private async getProvidersActives() {
    this.isLoading = true;
    await lastValueFrom(this._providerServices.getProviderActives()).then(
      (responseData:ResponseDataProviderInformation) => {
        if (!responseData.error) {

          if (this.dataDialog.elementData !== undefined) {
            let arrProviderValidate: Array<InformationsData> = [];
            let validateExists: boolean = false;

            responseData.response.map((elementProvider: InformationsData) => {
              this.dataDialog.dataSource.map((elementArtitle: InformationArtitle) => {
                if (elementProvider.PROV_NUPR === elementArtitle.PROVEEDOR.PROV_NUPR ) {                
                  validateExists = true;
                }
              });
              if (!validateExists) {
                arrProviderValidate.push(elementProvider);
              }
            });
            arrProviderValidate.push(this.dataDialog.elementData.PROVEEDOR);
            this.arrProvider = arrProviderValidate;

          } else {
            this.arrProvider = responseData.response;
          }
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public async alert(typeAlert:string, selectedFile:FileSelected) {
    this.isLoadingForm = true;
    if (typeAlert === 'DELETE_TEMP') {
      this._dialog.open(AlertComponent, {
        data: {
          icon: "warning",
          title: "Eliminar Archivo",
          description: "¿Está seguro de eliminar el archivo seleccionado?"
        },
        disableClose: true,
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          console.log(this.dataDialog.elementData.ESTADO);
          
          if ( selectedFile.state === 'REGISTRADO' && this.arrRegisterImages.includes(selectedFile.id)) {
            let arrDeleteSelected:Array<string> = this.formGroupInformation.controls['DELETE_FILE'].value;
            arrDeleteSelected.push(selectedFile.id);
            this.formGroupInformation.controls['DELETE_FILE'].setValue(arrDeleteSelected);

            this.arrFileSelected = await Promise.all(this.arrFileSelected.filter((selected:FileSelected) => selected.id !== selectedFile?.id));
            this.formGroupInformation.controls['DATA_IMAGEN'].setValue(this.arrFileSelected);

            const arrId:Array<string> = await Promise.all(this.arrFileSelected.map(( fileSelected:FileSelected) => fileSelected.id));
            this.formGroupInformation.controls['IMAGEN'].setValue(arrId);
            
          } else {
            await this.deleteTempFile(selectedFile.id);
          }
        } 
      });
    } 
    this.isLoadingForm = false;
  }

  public async uploadTempFile(event: any) {
    this.isLoadingForm = true;

    let arrFiles: Array<File> = Array.from(event.target.files);
    if (arrFiles.length > 1) {
      this.resourcesService.openSnackBar(`Analizando los ${arrFiles.length} archivos seleccionados.`)
    } else {
      this.resourcesService.openSnackBar(`Analizando el archivo seleccionado`);
    }

    let arrIdFile: Array<string> = [];

    await Promise.all(
      arrFiles.map(async (file:File) => {
        var myFormData = new FormData();
        myFormData.append('file', file);
        myFormData.append('id_user', this.resourcesService.getUser());
        myFormData.append('linea', this.resourcesService.getLineNumber());

        await lastValueFrom(this._gdelService.uploadTempFile(myFormData )).then(
          async (responseData: ResponseDataUploadTempFile) => {
            if (!responseData.error) {            
              this.arrFileSelected.push({
                id: responseData.response.idArchivo, 
                file: file,
                view: URL.createObjectURL(file),
                state: 'TEMPORAL',
              });
              arrIdFile.push(responseData.response.idArchivo);
            } else {
              this.resourcesService.openSnackBar(`${responseData.msg}`);
            }
          }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
        );
      })
    );

    if (arrIdFile.length != arrFiles.length) {
      this.resourcesService.openSnackBar(`Ocurrió un error con algún archivo, eliminando los archivos.`);
      await Promise.all(
        arrIdFile.map(async (idFile:string) => {
          await this.deleteTempFile(idFile);
        })
      );
      this.arrFileSelected = this.arrFileSelected.filter((selected:FileSelected) => !arrIdFile.includes(selected.id));

    } else {
      this.resourcesService.openSnackBar(`¡Archivos Analizados Exitosamente!`);
      const arrId:Array<string> = this.arrFileSelected.map(( fileSelected:FileSelected) => fileSelected.id);
      this.formGroupInformation.controls['IMAGEN'].setValue(arrId);
      this.formGroupInformation.controls['DATA_IMAGEN'].setValue(this.arrFileSelected);

    }
    this.isLoadingForm = false;    
  }

  private async deleteTempFile(idArchivo:string) {
    this.isLoadingForm = true;
    this.resourcesService.openSnackBar(`Eliminando archivo, espere un momento`);
    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(
      async (responseData: ResponseDataUploadTempFile) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Eliminación del archivo temporal exitosa!`);
          this.arrFileSelected = await Promise.all(this.arrFileSelected.filter((selected:FileSelected) => selected.id !== idArchivo && selected.state === 'TEMPORAL'));
          const arrId:Array<string> = await Promise.all(this.arrFileSelected.map(( fileSelected:FileSelected) => fileSelected.id));
          this.formGroupInformation.controls['IMAGEN'].setValue(arrId);
          this.formGroupInformation.controls['DATA_IMAGEN'].setValue(this.arrFileSelected);
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  public async save() {
    console.log(this.formGroupInformation.value);
    
    this._dialogRef.close(this.formGroupInformation.value);
    /* if(this.type === 'MOD') {
      // let arrDeleteFile = this.arrFileSelected.filter((infoUpload: InfoUpload) => infoUpload.status === 'DELETE');
      // this.formGroupInformation.controls['DELETE_FILE'].setValue(arrDeleteFile);
      this._dialogRef.close(this.formGroupInformation.value);
    } else {
      this._dialogRef.close(this.formGroupInformation.value);
    } */

  }
}

export interface ResponseDataUnit {
  error: boolean;
  msg: string;
  response: Array<UnitData>;
}
export interface UnitData {
  ID_UNIDAD: number;
  UNIDAD: string;
  USUARIO_REGISTRA: string;
  FECHA_REGISTRA: string;
  USUARIO_MODIFICA: string;
  FECHA_MODIFICA: string;
}
