import { Component, Inject } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { FileSelected } from '../../../../../interfaces/upload-files.interface';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { ResourcesService } from '../../../../../services/resources.service';
import { AcquisitionService } from '../../../../../services/acquisition-management/acquisition.service';
import { EncService } from '../../../../../services/enc.service';
import { GdelService } from '../../../../../services/gdel.service';
import { DialogRef } from '@angular/cdk/dialog';
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 { FormReportProblem } from '../../../../../interfaces/acquisition-management/issue-tracking.interface';
import { ResponseData } from '../../../../../interfaces/response-data';

@Component({
    selector: 'app-report-problems-orders',
    templateUrl: './report-problems-orders.component.html',
    styleUrl: './report-problems-orders.component.css',
    standalone: false
})
export class ReportProblemsOrdersComponent {
  public formGroup: FormGroup;
  public arrFileSelected: Array<FileSelected>;
  public isLoadingForm: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public orderNumber: string,
    public resourcesService: ResourcesService,
    public _dialog: MatDialog,
    private _acquisitionService: AcquisitionService,
    private _dialogReg: MatDialogRef<boolean>,
    private _encService: EncService,
    private _gdelService: GdelService,
    private _dialogRef: DialogRef<boolean>,
  ) {
    this.formGroup = this.createFormGroup();
    this.arrFileSelected = [];
    this.isLoadingForm = false;
  }

  private createFormGroup() {
    return new FormGroup({
      TIPO: new FormControl('', Validators.required),
      DESCRIPCION: new FormControl('', Validators.required),
      EVIDENCIA: new FormControl('', Validators.required),
    });
  }

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

        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),
                size: this.resourcesService.formatBytes(file.size),
              });
              arrIdFile.push(responseData.response.idArchivo);
            } else {
              this.resourcesService.openSnackBar(`${responseData.msg}`);
            }
          }, async (httpErrorResponse: HttpErrorResponse) => {
            let response = this.resourcesService.checkErrors(httpErrorResponse)
            if (response !== null && response.reload) {
              await this.loadImg(event);
            }
          }
        );
      })
    );

    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.formGroup.controls['EVIDENCIA'].setValue(arrId);

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

    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));
          const arrId:Array<string> = await Promise.all(this.arrFileSelected.map(( fileSelected:FileSelected) => fileSelected.id));
          this.formGroup.controls['EVIDENCIA'].setValue(arrId);
        } 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;
  }

  public async alert(typeAlert:string, idFile?:string) {
    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) {
          await this.deleteTempFile(idFile!);
        } 
      });
    } else if (typeAlert === 'REPORT') {
      this._dialog.open(AlertComponent,{
        data: {
          icon: 'warning',
          title: 'Enviar Reporte',
          description: '¿Está seguro de enviar el reporte de la orden?'
        }
      }).afterClosed().subscribe((responseDialog: any) => {
        if (responseDialog) {
          this.sendReport();
        }
      });
    }
    this.isLoadingForm = false;
  }

  public async sendReport() {
    this.isLoadingForm = true;
    const objectResponse: FormReportProblem = await this.createObjectResponse();
    
    await lastValueFrom(this._acquisitionService.reportProblem(objectResponse)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar('El reporte se envío correctamente');
          this._dialogReg.close(true);
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.sendReport();
        }
      }
    );
    this.isLoadingForm = false;
  }

  private async createObjectResponse() : Promise<FormReportProblem> {

    let tipo = this.formGroup.controls['TIPO'].value;
    tipo = tipo.toString().trim();
    let descripcion = this.formGroup.controls['DESCRIPCION'].value;
    descripcion = descripcion.toString().trim();
    let evidencia = this.formGroup.controls['EVIDENCIA'].value;

    return {
      ORDER: await this._encService.encrypt(this.orderNumber),
      TIPO: tipo,
      DESCRIPCION: descripcion,
      EVIDENCIA: evidencia,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
  }

  public async closeDialog() {
    await Promise.all(
      this.arrFileSelected.map(async (fileSelected:FileSelected) => {
        await this.deleteTempFile(fileSelected.id);
      })
    );
    this._dialogRef.close(false);
  }
}
