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 { ResponseData } from 'src/app/interfaces/response-data';
import { OrderService } from 'src/app/services/acquisition-management/order.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-add-state-order',
  templateUrl: './add-state-order.component.html',
  styleUrls: ['./add-state-order.component.css']
})
export class AddStateOrderComponent implements OnInit {

  public arrStatesOrders: Array<string>;
  public formGroup: FormGroup;

  public imgBase1: string;
  public imgBase2: string;
  public imagen1: any = null;
  public imagen2: any = null;
  public textLabel1: string;
  public textLabel2: string;
  public textoImagenMostrada: string;
  private isChangeImg1: boolean;
  private isChangeImg2: boolean;
  public textImgUpdate: string;


  constructor(
    @Inject(MAT_DIALOG_DATA) public orderNumber: string,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _orderService: OrderService,
    private _dialogRef: MatDialogRef<AddStateOrderComponent> ,
  ) {
    this.arrStatesOrders = ['Editado','En curso','Recibido Parcial','Recibido','Facturado','Anulado'];
    this.formGroup = this.createFormGroup();

    this.imgBase1 = 'assets/img/empty-img.svg';
    this.imgBase2 = 'assets/img/empty-img.svg';
    this.textLabel1 = 'Subir imagen *';
    this.textLabel2 = 'Subir imagen';
    this.textImgUpdate = '';
    this.textoImagenMostrada = '';
    this.isChangeImg1 = false;
    this.isChangeImg2 = false;
  }

  ngOnInit(): void {
  }

  private createFormGroup() {
    return new FormGroup({
      'ESTADO': new FormControl('', Validators.required),
      'DESCRIPCION': new FormControl('', Validators.required),
      'EVIDENCIA1': new FormControl('', Validators.required),
      'NOMBRE_IMAGEN1': new FormControl('', Validators.required),
      'EVIDENCIA2': new FormControl(''),
      'NOMBRE_IMAGEN2': new FormControl(''),
      'PORCENTAJE': new FormControl('', [Validators.required, Validators.max(100)]),
      'NUMERO_ORDEN': new FormControl(this.orderNumber, Validators.required),
      'NUMERO_LINEA': new FormControl('1', Validators.required),
      'USUARIO': new FormControl(this.resourcesService.getUser(), Validators.required),
    })
  }

  // Ejecuta el input file
  public getFile1() {
    document.getElementById("upfile1")!!.click();
  }
  public getFile2() {
    document.getElementById("upfile2")!!.click();
  }


  // Método para cargar la imagen
  public loadImg1(obj: any, event: any) {
    this.imagen1 = event.target.files[0];
    var file = obj.value;
    if (file !== '') {
      var fileName = file.split("\\");
      this.textLabel1 = fileName[fileName.length - 1];
      this.convertisBase64(this.imagen1).then((image: any) => {
        this.imgBase1 = image.base
        this.EVIDENCIA1?.setValue(image.base);
        this.NOMBRE_IMAGEN1?.setValue(this.textLabel1);
      });
      this.textoImagenMostrada = 'Imagen seleccionada';
      this.EVIDENCIA1?.setValue(this.imagen1);
      this.isChangeImg1 = true;
    } else {
      this.textLabel1 = "Subir imagen *";
      this.imgBase1 = 'assets/img/empty-img.svg';
      this.textoImagenMostrada = '';
      this.EVIDENCIA1?.setValue('');
      this.NOMBRE_IMAGEN1?.setValue('');
    }
  }

  public loadImg2(obj: any, event: any) {
    this.imagen2 = event.target.files[0];
    var file = obj.value;
    if (file !== '') {
      var fileName = file.split("\\");
      this.textLabel2 = fileName[fileName.length - 1];
      this.convertisBase64(this.imagen2).then((image: any) => {
        this.imgBase2 = image.base
        this.EVIDENCIA2?.setValue(image.base);
        this.NOMBRE_IMAGEN2?.setValue(this.textLabel2);
      });
      this.textoImagenMostrada = 'Imagen seleccionada';
      this.EVIDENCIA2?.setValue(this.imagen2);
      this.isChangeImg2 = true;
    } else {
      this.textLabel2 = "Subir imagen";
      this.imgBase2 = 'assets/img/empty-img.svg';
      this.textoImagenMostrada = '';
      this.EVIDENCIA2?.setValue('');
      this.NOMBRE_IMAGEN1?.setValue('');
    }
  }


  public setImage1 (image:string) {
    if (image === 'assets/img/empty-img.svg') {
      return image;
    } else  if (image.includes('data:image')){
      return image;
    }else{
      return 'http://192.168.1.4:8000/storage/GEAD/FO/' + image;
    }
  }
  public setImage2 (image:string) {
    if (image === 'assets/img/empty-img.svg') {
      return image;
    } else  if (image.includes('data:image')){
      return image;
    }else{
      return 'http://192.168.1.4:8000/storage/GEAD/FO/' + image;
    }
  }

  // Mostrar imagen seleccionada
  private convertisBase64 = async ($event: any) => new Promise((resolve) => {
    try {
      let reader = new FileReader();
      reader.readAsDataURL($event);
      reader.onload = () => { resolve({ base: reader.result }); };
      reader.onerror = () => { resolve({ base: null }); };
    } catch (error) {
      return null
    }
    return resolve;
  });

  // Método para ejecutar una alerta
  public async alert() {
    this._dialog.open(AlertComponent, {
      data: {
        icon: "warning",
        title: "Modificar Estado",
        description: "¿Está seguro de modificar el estado de la orden de compra?"
      },
      disableClose: true,
      // width: '500px',
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.updateStateOrder();
      }
    });

  }

  public async updateStateOrder() {
    await lastValueFrom(this._orderService.updateStateHistory(this.formGroup.value)).then(
      (responseData: ResponseData) => {
        if ( !responseData.error ) {
          this.resourcesService.openSnackBar('¡Modificación de Estado Exitoso!');
          this._dialogRef.close(true);
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error:  HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );


  }


  get ESTADO() { return this.formGroup.get('ESTADO')!; }
  get DESCRIPCION() { return this.formGroup.get('DESCRIPCION')!; }
  get EVIDENCIA1() { return this.formGroup.get('EVIDENCIA1')!; }
  get NOMBRE_IMAGEN1() { return this.formGroup.get('NOMBRE_IMAGEN1')!; }
  get EVIDENCIA2() { return this.formGroup.get('EVIDENCIA2')!; }
  get NOMBRE_IMAGEN2() { return this.formGroup.get('NOMBRE_IMAGEN2')!; }
  get PORCENTAJE() { return this.formGroup.get('PORCENTAJE')!; }
  get NUMERO_ORDEN() { return this.formGroup.get('NUMERO_ORDEN')!; }
  get NUMERO_LINEA() { return this.formGroup.get('NUMERO_LINEA')!; }
  get USUARIO () { return this.formGroup.get('USUARIO')!; }

}
