import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { GetProvidersActives, InformationsData, ResponseDataGetProvidersActives } from '../../../../../interfaces/acquisition-management/provider.interface';
import { DataDescriptionArticle, DialogInformationArtitle, FormRequestInformation, GetUnits, ResponseDataGetUnits } from '../../../../../interfaces/acquisition-management/artitle.interface';
import { MatTableDataSource } from '@angular/material/table';
import { TempFiles } from '../../../../../interfaces/upload-files.interface';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { ResourcesService } from '../../../../../services/resources.service';
import { ProviderService } from '../../../../../services/acquisition-management/provider.service';
import { GdelService } from '../../../../../services/gdel.service';
import { AcquisitionService } from '../../../../../services/acquisition-management/acquisition.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { ResponseDataUploadTempFile } from '../../../../../interfaces/gdel.interface';
import { OpenImageSliderComponent } from '../../../../resources/dialogs/open-image-slider/open-image-slider.component';
import { AlertComponent } from '../../../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-artitle-description-form',
    templateUrl: './artitle-description-form.component.html',
    styleUrl: './artitle-description-form.component.css',
    standalone: false
})
export class ArtitleDescriptionFormComponent implements OnInit {
  public formGroup: FormGroup;
  
  public arrProvider: GetProvidersActives[];
  public arrUnits: GetUnits[];
  public dataSource: MatTableDataSource<TempFiles>;
  public displayedColumns: string[];
  
  public type!: 'R' | 'M';
  public title!: string;

  public isLoading: boolean;
  public isLoadingTable: boolean;
  public txtLoading: string;

  constructor(
    @Inject(MAT_DIALOG_DATA) public dataDialog: DialogInformationArtitle,
    public resourcesService: ResourcesService,
    private _providerServices: ProviderService,
    private _gdelService: GdelService,
    private _artitleService: AcquisitionService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<InformationsData>,
  ) {

    this.formGroup = this.createFormGroup();
    this.isLoading = false;
    this.isLoadingTable = false;
    this.txtLoading = "Cargando el formulario";
    this.arrProvider = [];
    this.arrUnits = [];
    this.dataSource = new MatTableDataSource<TempFiles>();
    this.displayedColumns = ['NAME','SIZE','ACTIONS'];
  }

  private createFormGroup() {
    return new FormGroup({
      'PROVEEDOR': new FormControl('', Validators.required),
      'TIPO_UNIDAD': new FormControl('', Validators.required),
      'CANTIDAD_UNIDAD': new FormControl({ value: '', disabled: true }, [Validators.required, Validators.min(1)]),
      'DESCRIPCION': new FormControl('', Validators.required),
      'CARACTERISTICAS': new FormControl(''),
    });
  }

  async ngOnInit() {
    this.isLoading = true;
    this.txtLoading = "Cargando el formulario";
    this.type = this.dataDialog.type;
    await this._getProvidersActives();
    await this._getUnits();
    await this.getDataDialog();
    this.isLoading = false;

    this.formGroup.controls['TIPO_UNIDAD'].valueChanges.subscribe((value: GetUnits) => {
      if (value.UNIDAD === 'Unidad') {
        this.formGroup.controls['CANTIDAD_UNIDAD'].disable();
        this.formGroup.controls['CANTIDAD_UNIDAD'].setValue(1);
      } else {
        this.formGroup.controls['CANTIDAD_UNIDAD'].enable();
        this.formGroup.controls['CANTIDAD_UNIDAD'].setValue(null);
      }
    })
  }

  private async _getProvidersActives() {
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._providerServices.getProviderActives(user, line)).then(
      (responseData: ResponseDataGetProvidersActives) => {
        if (!responseData.error) {

          let arrTemp: GetProvidersActives[] = [];
          for (const element of responseData.response) {
            if (!this.dataDialog.providersSelected.includes(element.NUMERO_PROVEEDOR)) {
              arrTemp.push(element)
            }
            if (this.type === 'M' && this.dataDialog.elementData !== undefined && this.dataDialog.elementData.NUMERO_PROVEEDOR === element.NUMERO_PROVEEDOR) {
              arrTemp.push(element)
            }
          }
          responseData.response = arrTemp;
          
          if (responseData.response.length === 0 && this.type === 'R') {
            this.resourcesService.openSnackBar(`No hay proveedores disponibles.`);
            this._dialogRef.close(false);
            return;
          } 
          this.arrProvider = responseData.response;

        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._getProvidersActives();
        }
      }
    );
  }

  private async _getUnits() {
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._artitleService.getUnitsActives(user, line)).then(
      (responseData: ResponseDataGetUnits) => {
        if (!responseData.error) {
          this.arrUnits = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${ responseData.msg }`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._getUnits();
        }
      }
    );
  }

  private async getDataDialog () {
    if (this.type === 'R') {
      this.title = 'Registro de la descripción del artículo';

    } else if (this.type === 'M' &&  this.dataDialog.elementData !== undefined) {
      this.title = 'Modificación de la descripción del artículo';        
      const DATA_DESCRIPTION: DataDescriptionArticle = this.dataDialog.elementData;

      let providerElement: GetProvidersActives = {} as GetProvidersActives;
      for (const provider of this.arrProvider) {
        if (provider.NUMERO_PROVEEDOR === DATA_DESCRIPTION.NUMERO_PROVEEDOR) {
          providerElement = provider;
        }
      }
      this.formGroup.controls['PROVEEDOR'].setValue(providerElement)

      let unitElement: GetUnits = {} as GetUnits;
      for (const unit of this.arrUnits) {
        if (unit.ID_UNIDAD === DATA_DESCRIPTION.ID_UNIDAD) {
          unitElement = unit;
        }
      }
      this.formGroup.controls['TIPO_UNIDAD'].setValue(unitElement);
      this.formGroup.controls['DESCRIPCION'].setValue(DATA_DESCRIPTION.DESCRIPCION);
      this.formGroup.controls['CARACTERISTICAS'].setValue(DATA_DESCRIPTION.CARACTERISTICAS);

      this.dataSource.data = DATA_DESCRIPTION.ARCHIVOS;

    } else {
      this.resourcesService.openSnackBar(`Opción no disponible`);
      this._dialogRef.close(false);
    }
  }

  public async uploadTempFile(event: any) {
    this.isLoadingTable = true;
    const FILE_LIST: File[] = Object.values(event.target.files);
    
    const arrExtAviable = ['jpg','png','gif','jpeg'];
    for (const FILE of FILE_LIST) {
      const NAMEFILE: string = FILE.name;
      const ARR_NAMEFILE: string[] = NAMEFILE.split('.');
      const EXT = ARR_NAMEFILE.at(-1);
      if (EXT === undefined) {
        this.resourcesService.openSnackBar(`El archivo con el nombre ${NAMEFILE} no tiene extensión.`);
        return;
      }
      if (!arrExtAviable.includes(EXT)) {
        this.resourcesService.openSnackBar(`La extensión ${EXT} de la archivo ${NAMEFILE} no corresponde a una imagen.`);
        return;
      }
    }
      
    for (const FILE of FILE_LIST) {
      var myFormData = new FormData();
      myFormData.append('file', FILE);
      myFormData.append('id_user', this.resourcesService.getUser());
      myFormData.append('linea', this.resourcesService.getLineNumber().toString());

      await lastValueFrom(this._gdelService.uploadTempFile(myFormData)).then(
        async (responseData: ResponseDataUploadTempFile) => {
          if (!responseData.error) {
            
            let datasource = this.dataSource.data;
            datasource.push({
              ID: responseData.response.idArchivo,
              NAME: FILE.name,
              SIZE: this.resourcesService.formatBytes(FILE.size),
              SHOW: URL.createObjectURL(FILE),
              TYPE: 'R',
            });
            this.dataSource.data = datasource;
            
          } else {
            this.resourcesService.openSnackBar(`${responseData.msg}`);
          }
        }, async (httpErrorResponse: HttpErrorResponse) => {
          let response = this.resourcesService.checkErrors(httpErrorResponse)
          if (response !== null && response.reload) {
            await this.uploadTempFile(event);
          }
        }
      );
    }
    let upload = document.getElementById('uploadImage') as HTMLInputElement;
    upload.value = ''
    this.isLoadingTable = false;
  }

  public openImage(tempFile: TempFiles) {
    this._dialog.open(OpenImageSliderComponent, {
      data: tempFile.SHOW,
      height: 'calc(100% - 50px)',
    })
  }

  public alertDeleteTemp(tempFile: TempFiles, index: number) {
    this._dialog.open(AlertComponent, {
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de eliminar la imagen?`,
        icon: `warning`,
      },
      disableClose: true,
    }).afterClosed().subscribe(async (response) => {
      if (response) {

        if (tempFile.TYPE === 'R') {
          await this._deleteTempFile(tempFile.ID);
        } else if (tempFile.TYPE === 'O') {
          let datasource: TempFiles[] = this.dataSource.data;
          datasource[index].TYPE = 'OD';
          this.dataSource.data = datasource;
        } else if (tempFile.TYPE === 'OD') {
          this.resourcesService.openSnackBar(`El elemento ya fue eliminado.`);
        }
      }
    })
  }

  private async _deleteTempFile(idArchivo: string) {
    this.isLoadingTable = true;
    
    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(
      async (responseData: ResponseDataUploadTempFile) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Eliminación del archivo temporal exitosa!`);
          this.dataSource.data = this.dataSource.data.filter((tempFile: TempFiles) => tempFile.ID !== idArchivo);
        } 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.isLoadingTable = false;
  }

  public restoreFile(index: number) {
    let datasource: TempFiles[] = this.dataSource.data;
    datasource[index].TYPE = 'O';
    this.dataSource.data = datasource;
  }

  public async close() {
    if (this.type === 'R') {
      this.isLoading = true;
      this.txtLoading = "Cerrando el formulario";
      for (const element of this.dataSource.data) {
        await this._deleteTempFile(element.ID);
      }
      this.isLoading = false;
    }
    this._dialogRef.close(false);
  }

  public async save() {
    let PROVEEDOR: GetProvidersActives = this.formGroup.controls['PROVEEDOR'].value;
    let TIPO_UNIDAD: GetUnits = this.formGroup.controls['TIPO_UNIDAD'].value;

    let CANTIDAD_UNIDAD = this.formGroup.controls['CANTIDAD_UNIDAD'].value;
    if (TIPO_UNIDAD.UNIDAD === 'Unidad') {
      CANTIDAD_UNIDAD = 1;
    }

    let DESCRIPCION = this.formGroup.controls['DESCRIPCION'].value;
    DESCRIPCION = DESCRIPCION.toString().trim();

    let CARACTERISTICAS = this.formGroup.controls['CARACTERISTICAS'].value;
    if (CARACTERISTICAS !== null && CARACTERISTICAS !== undefined) {
      CARACTERISTICAS = CARACTERISTICAS.toString().trim();
    }

    const REQUEST_FORM: FormRequestInformation = {
      NUMERO_PROVEEDOR: PROVEEDOR.NUMERO_PROVEEDOR,
      PROVEEDOR: PROVEEDOR.RAZON_SOCIAL,
      ID_UNIDAD: TIPO_UNIDAD.ID_UNIDAD,
      UNIDAD: TIPO_UNIDAD.UNIDAD,
      CANTIDAD_UNIDAD: CANTIDAD_UNIDAD,
      DESCRIPCION: DESCRIPCION,
      CARACTERISTICAS: CARACTERISTICAS,
      ARCHIVOS: this.dataSource.data,
    }
    console.log(REQUEST_FORM);
    this._dialogRef.close(REQUEST_FORM);
  }
}
