import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ResourcesService, ResponseData } from '../../../../services/resources.service';
import { ActivatedRoute } from '@angular/router';
import { EncService } from '../../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { InventoryManagementService } from '../../../../services/inventory-management/inventory-management.service';
import { lastValueFrom } from 'rxjs';
import { RequestSaveInfo, ResponseDataGetDetailsObjectProperties } from '../../../../interfaces/inventory-management/object-properties-artitle.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-details-object-properties',
    templateUrl: './details-object-properties.component.html',
    styleUrl: './details-object-properties.component.css',
    standalone: false
})
export class DetailsObjectPropertiesComponent implements OnInit {
  public idStock!: string;
  public formGroup: FormGroup;
  public isLoading: boolean;
  public arrImages: Array<string>;
  
  constructor (
    public resourcesService: ResourcesService,
    private _activateRoute: ActivatedRoute,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _inventoryManagementService: InventoryManagementService,
  ) {
    this.formGroup = this._createFormGroup();
    this.isLoading = false;
    this.arrImages = [];
  }

  private _createFormGroup(): FormGroup {
    return new FormGroup({
      CODIGO_EQUIPAMIENTO: new FormControl( { value: null, disabled: false }),
      NOMBRE_FAMILIA: new FormControl( { value: null, disabled: false }),
      NOMBRE_SUBFAMILIA: new FormControl( { value: null, disabled: false }),
      MODELO: new FormControl( { value: null, disabled: false }),
      CODIGO_MODELO: new FormControl( { value: null, disabled: false }),
      CODIGO_BARRA: new FormControl( { value: null, disabled: false }),
      FECHA_VENCIMIENTO: new FormControl( { value: null, disabled: false }),
      TIPO_ADQUISICION: new FormControl( { value: null, disabled: false }),
      ALTO: new FormControl( { value: null, disabled: false }, Validators.min(1)),
      ANCHO: new FormControl( { value: null, disabled: false }, Validators.min(1)),
      LARGO: new FormControl( { value: null, disabled: false }, Validators.min(1)),
      COLOR: new FormControl( { value: null, disabled: false }),
      PRECIO_ADQUIRIDO: new FormControl( { value: null, disabled: false }),
      CODIGO_MONEDA: new FormControl( { value: null, disabled: false }),
      STOCK_MINIMO: new FormControl( { value: null, disabled: false } ),
      STOCK_MAXIMO: new FormControl( { value: null, disabled: false } ),
      NIVEL_PELIGROSIDAD: new FormControl( { value: null, disabled: false }),
      NOMBRE_ALMACEN: new FormControl( { value: null, disabled: false }),
      NOMBRE_AREA: new FormControl( { value: null, disabled: false }),
      NOMBRE_NIVEL: new FormControl( { value: null, disabled: false }),
      NOMBRE_ZONA: new FormControl( { value: null, disabled: false }),
      NOMBRE_PROVEEDPOR: new FormControl( { value: null, disabled: false }),
      DESCRIPCION_PROVEEDOR: new FormControl( { value: null, disabled: false }),
      CARACTERISTICA_PROVEEDOR: new FormControl( { value: null, disabled: false }),
      CONSUMIBLE: new FormControl( { value: null, disabled: true }),
      REPARABLE: new FormControl( { value: null, disabled: true }),
    });
  }

  async ngOnInit() {
    let encStock = this._activateRoute.snapshot.paramMap.get('idStock');
    if (encStock !== null) {
      this.idStock = await this._encService.decrypt(encStock);
      await this.getDetailsObjectProperties();
    } else {
      this.resourcesService.openSnackBar(`Ocurrió un error al recuperar el ID del Stock.`);
      this.resourcesService.goBack();
    }
  }

  private async getDetailsObjectProperties() {
    this.isLoading = true;
    const encStock: string = await this._encService.encrypt(this.idStock);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getDetailsObjectProperties(encStock, user, line)).then(
      (responseData: ResponseDataGetDetailsObjectProperties) => {
        if (!responseData.error) {
          const info = responseData.response;
        
          let codigoEquipamiento = info.CODIGO_EQUIPAMIENTO;
          let nombreFamilia = `${info.NOMBRE_FAMILIA} (${info.CODIGO_FAMILIA})`;
          let nombreSubfamilia = `${info.NOMBRE_SUBFAMILIA} (${info.CODIGO_SUBFAMILIA})`;
          let modelo = info.MODELO;
          let codigoModelo = info.CODIGO_MODELO;
          let codigoBarra = info.CODIGO_BARRA;
          let fechaVencimiento = info.FECHA_VENCIMIENTO;
          let tipoAdquisicion = info.TIPO_ADQUISICION;
          let alto = info.ALTO;
          let ancho = info.ANCHO;
          let largo = info.LARGO;
          let color = info.COLOR;
          let precioAdquirido = info.PRECIO_ADQUIRIDO;
          let codigo_moneda = info.CODIGO_MONEDA;
          let stockMinimo = info.STOCK_MINIMO;
          stockMinimo = stockMinimo === null ? 'Sin especificar' : stockMinimo;
          let stockMaximo = info.STOCK_MAXIMO;
          stockMaximo = stockMaximo === null ? 'Sin especificar' : stockMaximo;          
          let nivelPeligrosidad = info.NIVEL_PELIGROSIDAD;
          let nombreAlmacen = `${info.NOMBRE_ALMACEN} (${info.CODIGO_ALMACEN})`;
          let nombreArea = `${info.NOMBRE_AREA} (${info.CODIGO_AREA})`;
          let nombreNivel = `${info.NOMBRE_NIVEL} (${info.CODIGO_NIVEL})`;
          let nombreZona = `${info.NOMBRE_ZONA} (${info.CODIGO_ZONA})`;

          let nombreProveedor = '';
          if(info.NOMBRE_PROVEEDOR == null){
            nombreProveedor = `-`;
          }else{
            nombreProveedor = `${info.NOMBRE_PROVEEDOR} (${info.NUMERO_PROVEEDOR})`;
          }

          let descripcionProveedor = info.DESCRIPCION_PROVEEDOR
          let caracteristicaProveedor = info.CARACTERISTICA_PROVEEDOR
          let consumible = info.CONSUMIBLE;
          let reparable = info.REPARABLE

          this.arrImages = info.IMAGENES;

          this.formGroup.controls['CODIGO_EQUIPAMIENTO'].setValue(codigoEquipamiento);
          this.formGroup.controls['NOMBRE_FAMILIA'].setValue(nombreFamilia);
          this.formGroup.controls['NOMBRE_SUBFAMILIA'].setValue(nombreSubfamilia);
          this.formGroup.controls['MODELO'].setValue(modelo);
          this.formGroup.controls['CODIGO_MODELO'].setValue(codigoModelo);
          this.formGroup.controls['CODIGO_BARRA'].setValue(codigoBarra);
          this.formGroup.controls['FECHA_VENCIMIENTO'].setValue(fechaVencimiento);
          this.formGroup.controls['TIPO_ADQUISICION'].setValue(tipoAdquisicion);
          this.formGroup.controls['ALTO'].setValue(alto);
          this.formGroup.controls['ANCHO'].setValue(ancho);
          this.formGroup.controls['LARGO'].setValue(largo);
          this.formGroup.controls['COLOR'].setValue(color);
          this.formGroup.controls['PRECIO_ADQUIRIDO'].setValue(precioAdquirido);
          this.formGroup.controls['CODIGO_MONEDA'].setValue(codigo_moneda);
          this.formGroup.controls['STOCK_MINIMO'].setValue(stockMinimo);
          this.formGroup.controls['STOCK_MAXIMO'].setValue(stockMaximo);
          this.formGroup.controls['NIVEL_PELIGROSIDAD'].setValue(nivelPeligrosidad);
          this.formGroup.controls['NOMBRE_ALMACEN'].setValue(nombreAlmacen);
          this.formGroup.controls['NOMBRE_AREA'].setValue(nombreArea);
          this.formGroup.controls['NOMBRE_NIVEL'].setValue(nombreNivel);
          this.formGroup.controls['NOMBRE_ZONA'].setValue(nombreZona);
          this.formGroup.controls['NOMBRE_PROVEEDPOR'].setValue(nombreProveedor);
          this.formGroup.controls['DESCRIPCION_PROVEEDOR'].setValue(descripcionProveedor);
          this.formGroup.controls['CARACTERISTICA_PROVEEDOR'].setValue(caracteristicaProveedor);
          this.formGroup.controls['CONSUMIBLE'].setValue(consumible);
          this.formGroup.controls['REPARABLE'].setValue(reparable);

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

  public save() {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        title: `Confirmación`,
        description: `¿Está seguro de guardar los datos?`,
        icon: `warning`,
      }
    }).afterClosed().subscribe( async (result) => {
      if (result) {
        await this.saveInfoStock();
      }
    });
  }

  private async saveInfoStock() {
    let alto = this.formGroup.controls['ALTO'].value;
    alto = alto === '' || alto == null ? null : alto.toString().trim();

    let ancho = this.formGroup.controls['ANCHO'].value;
    ancho = ancho === '' || ancho == null ? null : ancho.toString().trim();

    let largo = this.formGroup.controls['LARGO'].value;
    largo = largo === '' || largo == null ? null : largo.toString().trim();

    let color = this.formGroup.controls['COLOR'].value;
    color = color === '' || color == null ? null : color.toString().trim();

    let stock_minimo = this.formGroup.controls['STOCK_MINIMO'].value;
    stock_minimo = stock_minimo === '' || stock_minimo == null ? null : stock_minimo.toString().trim();

    let stock_maximo = this.formGroup.controls['STOCK_MAXIMO'].value;
    stock_maximo = stock_maximo === '' || stock_maximo == null ? null : stock_maximo.toString().trim();

    let nivel_peligrosidad = this.formGroup.controls['NIVEL_PELIGROSIDAD'].value;
    nivel_peligrosidad = nivel_peligrosidad === '' || nivel_peligrosidad == null ? null : nivel_peligrosidad.toString().trim();

    const requestSaveInfoStock: RequestSaveInfo = {
      ALTO: alto,
      ANCHO: ancho,
      LARGO: largo,
      COLOR: color,
      NIVEL_PELIGROSIDAD: nivel_peligrosidad,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
    const encStock = await this._encService.encrypt(this.idStock);
    await lastValueFrom(this._inventoryManagementService.saveInfoStock(requestSaveInfoStock,encStock)).then(
      async (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Actualización de Datos Correcta!`);
          await this.getDetailsObjectProperties();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.saveInfoStock();
        }
      }
    );
  }
}
