import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { CarAreasListItem, CarAreasListResponse, EquipmentDetailsResponse, EquipmentsListItem, EquipmentsListResponse, FamiliesListItem, FamiliesListResponse, LocationsListItem, LocationsListResponse, OccupationsListItem, OccupationsListResponse, SubfamiliesListItem, SubfamiliesListResponse, TrainElementsListItem, TrainElementsListResponse, TrainOccupationsListItem, TrainOccupationsListResponse } from '../../../../../interfaces/equipment-management.interface';
import { GetProvidersActives, ResponseDataGetProvidersActives } from '../../../../../interfaces/acquisition-management/provider.interface';
import { GetAreaWarehouse, GetLevelAreaWarehouse, GetWarehouse, GetZoneLevelAreaWarehouse, RegisterToStock, ResponseDataGetAreaWarehouse, ResponseDataGetLevelAreaWarehouse, ResponseDataGetWarehouse, ResponseDataGetZoneLevelAreaWarehouse } from '../../../../../interfaces/inventory-management/warehouse-management.interface';
import { MatTableDataSource } from '@angular/material/table';
import { TempFileInfo } from '../../../../../interfaces/temp-file-info.interface';
import { lastValueFrom, map, Observable, startWith } from 'rxjs';
import { GetInformationToEquipment, ResponseDataGetInformationToEquipment } from '../../../../../interfaces/acquisition-management/order-reception.interface';
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 { GdelService } from '../../../../../services/gdel.service';
import { ProviderService } from '../../../../../services/acquisition-management/provider.service';
import { EquipmentManagementService } from '../../../../../services/equipment-management.service';
import { DispatchService } from '../../../../../services/acquisition-management/dispatch.service';
import { InventoryManagementService } from '../../../../../services/inventory-management/inventory-management.service';
import { HttpErrorResponse } from '@angular/common/http';
import { FatherLoaderComponent } from '../../../../equipment-management/new-equipment/father-loader/father-loader.component';
import { LocateCarAreaComponent } from '../../../../equipment-management/new-equipment/locate-car-area/locate-car-area.component';
import { SearchEquipmentComponent } from '../../../../equipment-management/new-equipment/search-equipment/search-equipment.component';
import { LocatePccComponent } from '../../../../equipment-management/new-equipment/locate-pcc/locate-pcc.component';
import { availableFiles } from '../../../../../../environments/environment.prod';
import { RegisterMultipleDataComponent } from '../register-multiple-data/register-multiple-data.component';
import { LocateCarComponent } from '../../../../equipment-management/new-equipment/locate-car/locate-car.component';

@Component({
    selector: 'app-move-stock',
    templateUrl: './move-stock.component.html',
    styleUrl: './move-stock.component.css',
    standalone: false
})
export class MoveStockComponent implements OnInit {
  action: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  generatedTag: string;
  formGroup: FormGroup;
  disableAttachActions: boolean;

  locationsArr: LocationsListItem[];
  levelsArr: any[];
  occupations: OccupationsListItem[];
  familiesArr: FamiliesListItem[];
  subfamiliesArr: SubfamiliesListItem[];
  statesArr: any[];
  trainOccupations: TrainOccupationsListItem[];
  carAreas: CarAreasListItem[];
  trainElements: TrainElementsListItem[];
  equipments: EquipmentsListItem[];
  equipmentsStr: string[];
  arrProvider: Array<GetProvidersActives>;
  providersStr: string[];

  arrWarehouse: Array<GetWarehouse>;
  warehouseStr: string[];
  arrAreas: Array<GetAreaWarehouse>;
  areaStr: string[];
  arrLevel: Array<GetLevelAreaWarehouse>;
  levelStr: string[];
  arrZone: Array<GetZoneLevelAreaWarehouse>;
  zoneStr: string[];

  searchingSubfamilies: boolean;
  searchingCarAreas: boolean;
  searchingEquipments: boolean;
  
  searchingArea: boolean;
  searchingLevel: boolean;
  searchingZone: boolean;

  codeControlsStr = [
    'lineControl', 
    'originLocationControl', 
    'originLevelControl', 
    'originOccupationControl', 
    'originElementControl',
    'familyControl', 
    'subfamilyControl', 
    'statusControl', 
    'equipmentTypeControl', 
    'equipmentModelControl', 
    'equipmentIDControl', 
    'pccIntersectionControl',   
    'pccPositionControl', 
    'originKilometersControl', 
    'destinyLocationControl', 
    'destinyLevelControl', 
    'destinyOccupationControl', 
    'destinyElementControl', 
    'destinyKilometersControl', 
    'trainAreaControl', 
    'mixOriginControl', 
    'mixDestinyControl',
    'warehouseIDControl',
    'areaIDControl',
    'levelIDControl',
    'zoneIDControl',
  ];
  equipmentStates = ['Adquisición', 'Stock', 'Traslado', 'Instalación', 'Reparación', 'Disposición'];

  imagesDataSource: MatTableDataSource<TempFileInfo>;
  imagesDisplayedColumns = ['name', 'size', 'acciones'];
  attachedImages: TempFileInfo[];
  uploadingImages: boolean;

  documentsDataSource: MatTableDataSource<TempFileInfo>;
  documentsDisplayedColumns = ['name', 'size', 'acciones'];
  attachedDocuments: TempFileInfo[];
  uploadingDocuments: boolean;

  filteredEquipments?: Observable<string[]>;
  filteredProviders?: Observable<string[]>;

  public isFromAdquisition: boolean  = false;
  private artitleByAdquisicion!: GetInformationToEquipment;
  public numberItems: number = 1;
  public readOnlySerial: boolean = false;
  public isUniqueSerial: boolean = false;
  public isUniqueDueDate: boolean = false;
  public isUniqueBarcorde: boolean = false;
  public orderNumber: string = '';
  public idInformation: number = 0;

  public minDateWarrantyStart!: Date;
  public maxDateWarrantyStart!: Date;

  public minDateWarrantyEnd!: Date;
  public maxDateWarrantyEnd!: Date;
  
  public minDateDue!: Date;

  constructor(
    public resourcesService: ResourcesService,
    private _activatedRoute: ActivatedRoute,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _gdelService: GdelService,
    private _providersService: ProviderService,
    private _equipmentManagementService: EquipmentManagementService,
    private _dispatchService: DispatchService,
    private _inventoryManagementService: InventoryManagementService,
  ) {
    this.action = "";
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.generatedTag = "";
    this.disableAttachActions = false;

    this.locationsArr = [];
    this.levelsArr = [];
    this.occupations = [];
    this.familiesArr = [];
    this.subfamiliesArr = [];
    this.statesArr = [];
    this.trainOccupations = [];
    this.carAreas = [];
    this.trainElements = [];
    this.equipments = [];
    this.equipmentsStr = [];
    this.arrProvider = [];
    this.providersStr = [];

    this.arrWarehouse = [];
    this.warehouseStr = [];
    this.arrAreas = [];
    this.areaStr = [];
    this.arrLevel = [];
    this.levelStr = [];
    this.arrZone = [];
    this.zoneStr = [];

    this.searchingSubfamilies = false;
    this.searchingCarAreas = false;
    this.searchingEquipments = false;

    this.searchingArea = false;
    this.searchingLevel = false;
    this.searchingZone = false;

    this.imagesDataSource = new MatTableDataSource();
    this.attachedImages = [];
    this.uploadingImages = false;

    this.documentsDataSource = new MatTableDataSource();
    this.attachedDocuments = [];
    this.uploadingDocuments = false;

    this.formGroup = new FormGroup({
      //Controles generales
      hierarchyControl: new FormControl('', Validators.required),
      fatherControl: new FormControl({disabled: true, value: ''}, Validators.required),
      codeTypeControl: new FormControl({disabled: true, value: ''}, Validators.required),
      mixOriginControl: new FormControl({disabled: true, value: ''}, Validators.required),
      mixDestinyControl: new FormControl({disabled: true, value: ''}, Validators.required),
      //Controles usado en todos los casos
      lineControl: new FormControl({disabled: true, value: '01'}, Validators.required),
      originLocationControl: new FormControl({disabled: true, value: ''}, Validators.required),
      originLevelControl: new FormControl({disabled: true, value: ''}, Validators.required),
      originOccupationControl: new FormControl({disabled: true, value: ''}, Validators.required),
      originElementControl: new FormControl({disabled: true, value: ''}, Validators.required),
      familyControl: new FormControl({disabled: true, value: ''}, Validators.required),
      subfamilyControl: new FormControl({disabled: true, value: ''}, Validators.required),
      statusControl: new FormControl({disabled: true, value: ''}, Validators.required),
      equipmentTypeControl: new FormControl({disabled: true, value: ''}, [Validators.required, Validators.maxLength(150)]),
      equipmentModelControl: new FormControl({disabled: true, value: ''}, [Validators.required, Validators.maxLength(75)]),
      equipmentIDControl: new FormControl({disabled: true, value: 'XXXXXX'}),
      warehouseIDControl: new FormControl({disabled: false, value: ''}, Validators.required),
      areaIDControl: new FormControl({disabled: true, value: ''}, Validators.required),
      levelIDControl: new FormControl({disabled: true, value: ''}, Validators.required),
      zoneIDControl: new FormControl({disabled: true, value: ''}, Validators.required),
      //Controles específicos para PCC
      pccIntersectionControl: new FormControl({disabled: true, value: '',}, Validators.required),
      pccPositionControl: new FormControl({disabled: true, value: ''}, [Validators.required, Validators.maxLength(2)]),
      //Controles para los casos de origen - destino
      originKilometersControl: new FormControl({disabled: true, value: ''}, Validators.required),
      destinyLocationControl: new FormControl({disabled: true, value: ''}, Validators.required),
      destinyLevelControl: new FormControl({disabled: true, value: ''}, Validators.required),
      destinyOccupationControl: new FormControl({disabled: true, value: ''}, Validators.required),
      destinyElementControl: new FormControl({disabled: true, value: ''}, Validators.required),
      destinyKilometersControl: new FormControl({disabled: true, value: ''}, Validators.required),
      //Controles de información complementaria
      acquisitionDateControl: new FormControl('', Validators.required),
      warrantyStartDateControl: new FormControl('', Validators.required),
      warrantyEndDateControl: new FormControl('', Validators.required),
      equipmentProviderControl: new FormControl('', Validators.required),
      serialNumberControl: new FormControl('', Validators.required),
      hasSoftwareControl: new FormControl('', Validators.required),
      softwareNameControl: new FormControl({disabled: true, value: ''}),
      softwareVersionControl: new FormControl({disabled: true, value: ''}),
      enableSerial: new FormControl({disabled: false, value: false}),
      //Controles para los casos de origen - destino para estaciones y edificios
      originSequenceControl: new FormControl(''),
      destinySequenceControl: new FormControl(''),
      //Controles para los casos de tren
      trainAreaControl: new FormControl({disabled: true, value: ''}, Validators.required),
      //Controles para Stock
      barcodeControl: new FormControl(''),
      turnoverRateControl: new FormControl(''),
      minimumStockControl: new FormControl(''),
      maximumStockControl: new FormControl(''),
      dueDateControl: new FormControl(''),
      dangerLevelControl: new FormControl(''),
      repairableControl: new FormControl(false),
      consumableControl: new FormControl(false),
    });
  }

  async ngOnInit() {
    const dataUrlForm = this._activatedRoute.snapshot.paramMap.get('form');
    if (dataUrlForm !== null) {
      const decDataForm: string = await this._encService.decrypt(dataUrlForm) ;
      const objDataForm: GetDataRegisterArtitle = JSON.parse(decDataForm);
      if (objDataForm.action === 'new' && objDataForm.order === undefined && objDataForm.info === undefined && objDataForm.cantidad === undefined) {
        this.action = 'Registrar';
        await this.getLocations();
      } else if (objDataForm.action === 'new' && objDataForm.order !== undefined && objDataForm.info !== undefined && objDataForm.cantidad !== undefined) {
        this.action = 'Registrar';
        this.isFromAdquisition = true;
        this.numberItems = objDataForm.cantidad;
        this.orderNumber = objDataForm.order;
        this.idInformation = objDataForm.info;
        
        this.readOnlySerial = this.numberItems > 1;

        await this.getLocations();
        await this.getInformartionArtitleToEquipment(objDataForm.order, objDataForm.info);

        this.formGroup.controls['hierarchyControl'].setValue('Padre');
        this.formGroup.controls['hierarchyControl'].disable();
        this.formGroup.controls['codeTypeControl'].setValue('7');
        this.formGroup.controls['codeTypeControl'].disable();
        this.formGroup.controls['barcodeControl'].setValidators(Validators.required);
        this.formGroup.controls['barcodeControl'].updateValueAndValidity();
        
        let objStatus = this.statesArr.find((status) => status.STATUS === "Stock (S)");
        if (objStatus === null || objStatus === undefined) {
          return;
        }
        this.formGroup.controls['statusControl'].setValue(`${objStatus.ID}-enc`);
        this.formGroup.controls['statusControl'].disable();
        
      } else if (objDataForm.action === 'edit') {
        let idEquipmentEnc = objDataForm.id;
        if(idEquipmentEnc == null || idEquipmentEnc == undefined || idEquipmentEnc == ''){
          this.resourcesService.openSnackBar('No se encontró el ID de ningún equipamiento.');
          this.goBack(1);
        }else{
          this.action = 'Editar';
          this.init(idEquipmentEnc);
        }
      } else {
        this.resourcesService.openSnackBar('No se encontró ninguna acción.');
        this.goBack(1);
      }
    } else {
      this.resourcesService.openSnackBar('No se encontró ninguna acción.');
      this.goBack(1);
    }

    this.isLoading = false;

    this.formGroup.controls['hasSoftwareControl'].valueChanges.subscribe(val => {
      this.formGroup.controls['softwareNameControl'].setValue(null);
      this.formGroup.controls['softwareVersionControl'].setValue(null);

      if(val == 'Si'){
        this.formGroup.controls['softwareNameControl'].enable();
        this.formGroup.controls['softwareVersionControl'].enable();
        this.formGroup.controls['softwareNameControl'].setValidators([Validators.required]);
        this.formGroup.controls['softwareVersionControl'].setValidators([Validators.required]);
      }else{
        this.formGroup.controls['softwareNameControl'].disable();
        this.formGroup.controls['softwareVersionControl'].disable();
        this.formGroup.controls['softwareNameControl'].setValidators([]);
        this.formGroup.controls['softwareVersionControl'].setValidators([]);
      }
    });

    this.filteredEquipments = this.formGroup.controls['fatherControl'].valueChanges.pipe(
      startWith(''),
      map(value => this._filterEquipments(value || '')),
    );

    this.filteredProviders = this.formGroup.controls['equipmentProviderControl'].valueChanges.pipe(
      startWith(''),
      map(value => this._filterProviders(value || '')),
    )

    this.formGroup.controls['enableSerial'].valueChanges.subscribe((serialEnable: boolean) => {
      if (serialEnable) {
        this.formGroup.controls['serialNumberControl'].disable();
        this.formGroup.controls['serialNumberControl'].setValue('');
        this.formGroup.controls['serialNumberControl'].updateValueAndValidity();
      } else {
        this.formGroup.controls['serialNumberControl'].enable();
        this.formGroup.controls['serialNumberControl'].setValue('');
        this.formGroup.controls['serialNumberControl'].updateValueAndValidity();
      }
    });


    this.formGroup.controls['acquisitionDateControl'].valueChanges.subscribe((dateAdquisition) => {
      if (typeof dateAdquisition === 'object') {
        this.minDateWarrantyStart = dateAdquisition;
      }
    });

    this.formGroup.controls['warrantyStartDateControl'].valueChanges.subscribe((dateStart) => {
      if (typeof dateStart === 'object') {
        this.minDateWarrantyEnd = dateStart;

      }
    });
    this.formGroup.controls['warrantyEndDateControl'].valueChanges.subscribe((dateEnd) => {
      if (typeof dateEnd === 'object') {
        this.maxDateWarrantyStart = dateEnd;
      }
    });
  }

  private _filterEquipments(value: string): string[]{
    const filterValue = value.toLowerCase();
    return this.equipmentsStr.filter(option => option.toLowerCase().includes(filterValue));
  }

  private _filterProviders(value: string): string[]{
    const filterValue = value.toLowerCase();
    return this.providersStr.filter(option => option.toLowerCase().includes(filterValue));
  }

  async getLocations(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let locations: LocationsListResponse = await lastValueFrom(this._equipmentManagementService.locationConsult(idUser, 1));

      this.hasError = locations.error;
      this.errorStr = locations.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{
        for(const location of locations.response){
          let locationDec = await this._encService.decrypt(location.LOCATION);
          let codeDec = await this._encService.decrypt(location.CODE);

          location.LOCATION = `${locationDec} (${codeDec})`;
          this.locationsArr.push(location);
        }

        await this.fillLevels();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async fillLevels(){
    for(let i = 5; i > 0; i--){
      let tagStr = `S0${i}`;
      let labelStr = `Subterráneo ${i} (${tagStr})`;
      let tagEnc = await this._encService.encrypt(tagStr);

      this.levelsArr.push({
        LABEL: labelStr,
        CODE: tagEnc
      });
    }

    for(let i = 0; i <= 15; i++){
      let tagStr = i < 10 ? `P0${i}` : `P${i}`;
      let labelStr = i == 0 ? 'Planta baja' : `Piso ${i}`;
      labelStr = `${labelStr} (${tagStr})`;

      let tagEnc = await this._encService.encrypt(tagStr);
      this.levelsArr.push({
        LABEL: labelStr,
        CODE: tagEnc
      });
    }

    await this.getOccupations();
  }

  async getOccupations(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let occupations: OccupationsListResponse = await lastValueFrom(this._equipmentManagementService.occupationConsult(idUser, 1));
      
      this.hasError = occupations.error;
      this.errorStr = occupations.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{
        for(const occupation of occupations.response){
          occupation.DESCRIPCION = `${occupation.DESCRIPCION} (${occupation.OCUPACION})`;
          occupation.OCUPACION = await this._encService.encrypt(occupation.OCUPACION);
          
          this.occupations.push(occupation);
        }

        await this.getFamilies();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async getFamilies(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let families: FamiliesListResponse = await lastValueFrom(this._equipmentManagementService.familyConsult(idUser, 1));

      this.hasError = families.error;
      this.errorStr = families.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{        
        for(const family of families.response){
          let codeDec = await this._encService.decrypt(family.CODIGOFAMILIA);

          family.NOMBREFAMILIA = `${family.NOMBREFAMILIA} (${codeDec})`;
          this.familiesArr.push(family);
        }

        await this.fillEquipmentStates();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async fillEquipmentStates(){
    for(const state of this.equipmentStates){
      let id = state.charAt(0);
      let idEnc = await this._encService.encrypt(id);
      
      
      this.statesArr.push({
        STATUS: `${state} (${id})`,
        ID: idEnc
      });

    }

    await this.getTrainOccupations();
  }

  async getTrainOccupations(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let trainOccupations: TrainOccupationsListResponse = await lastValueFrom(this._equipmentManagementService.occupationTrainConsult(idUser, 1));

      this.hasError = trainOccupations.error;
      this.errorStr = trainOccupations.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{
        let trainOccupationsArr: TrainOccupationsListItem[] = [];
        for(const occupation of trainOccupations.response){
          let carDec = await this._encService.decrypt(occupation.CAR);
          let codeDec = await this._encService.decrypt(occupation.CODE);

          occupation.CAR = `${carDec} (${codeDec})`;
          trainOccupationsArr.push(occupation);
        }

        this.trainOccupations = trainOccupationsArr;
        await this.getTrainElements();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async getTrainElements(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let trainElements:TrainElementsListResponse = await lastValueFrom(this._equipmentManagementService.occupationTrainElements(idUser, 1));

      this.hasError = trainElements.error;
      this.errorStr = trainElements.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{
        let trainElementsArr: TrainElementsListItem[] = [];
        for(const element of trainElements.response){
          let codeDec = await this._encService.decrypt(element.CODE);
          let elementDec = await this._encService.decrypt(element.ELEMENT);

          element.ELEMENT = `${elementDec} (${codeDec})`;
          trainElementsArr.push(element);
        }

        this.trainElements = trainElementsArr;
        await this.getProviders();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }
    }
  }

  async getProviders(){
    try{
      const user: string = this.resourcesService.getUser();
      const line: number = this.resourcesService.getLineNumber();
      let providers: ResponseDataGetProvidersActives = await lastValueFrom(this._providersService.getProviderActives(user, line));

      this.hasError = providers.error;
      this.errorStr = providers.msg;

      if(!this.hasError){
        let providersArr: GetProvidersActives[] = [];
        let providersStrArr: string[] = [];

        for(const provider of providers.response as GetProvidersActives[]){
          providersArr.push(provider);
          providersStrArr.push(`(${provider.NUMERO_PROVEEDOR}) ${provider.RAZON_SOCIAL}`);
        }

        this.arrProvider = providersArr;
        this.providersStr = providersStrArr;
      }

      await this.getWarehouseActives();

    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg  == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
      
    }
  }

  private async getWarehouseActives() {
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getWarehouseActives(user, line)).then(
      async (responseData: ResponseDataGetWarehouse) => {
        if (!responseData.error) {
          let tempWareouse: Array<any> = [];
          await Promise.all(responseData.response.map(async (getWarehouse: GetWarehouse) => {
            tempWareouse.push({
              CODIGO_ALMACEN: getWarehouse.CODIGO_ALMACEN,
              NOMBRE_ALMACEN: `${getWarehouse.NOMBRE_ALMACEN} (${getWarehouse.CODIGO_ALMACEN})`,
            })
          }));
          this.arrWarehouse = tempWareouse;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getWarehouseActives();
        }
      }
    );
  }

  private async getInformartionArtitleToEquipment(orderNumber: string, idInformation: number) {
    const encOrder: string = await this._encService.encrypt(orderNumber);
    const encInfo: string = await this._encService.encrypt(idInformation.toString());
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._dispatchService.getInformartionArtitleToEquipment(encOrder, encInfo, user, line)).then(
      async (responseData: ResponseDataGetInformationToEquipment) => {
        if (!responseData.error) {
          this.artitleByAdquisicion = responseData.response;

          const family: string = `${this.artitleByAdquisicion.NOMBRE_FAMILIA} (${this.artitleByAdquisicion.CODIGO_FAMILIA})`;
          
          const familiesListItem = this.familiesArr.find((familiesListItem: FamiliesListItem) => familiesListItem.NOMBREFAMILIA === family);
          if (familiesListItem !== undefined) {
            this.formGroup.controls['familyControl'].setValue(`${familiesListItem.CODIGOFAMILIA}-enc`);
            this.formGroup.controls['familyControl'].disable();
          } else {
            this.resourcesService.openSnackBar(`No se encontró la familia.`);
            this.resourcesService.goBack();
            return;
          }

          await this.searchSubfamilies(`${familiesListItem.CODIGOFAMILIA}-enc`);
          
          const subfamily: string = `${this.artitleByAdquisicion.NOMBRE_SUBFAMILIA} (${this.artitleByAdquisicion.CODIGO_SUBFAMILIA})`;
          const subfamiliesListItem = this.subfamiliesArr.find((subfamiliesListItem: SubfamiliesListItem) => subfamiliesListItem.NOMBRESUBFAMILIA === subfamily);
          if (subfamiliesListItem !== undefined) {
            this.formGroup.controls['subfamilyControl'].setValue(`${subfamiliesListItem.CODIGOSUBFAMILIA}-enc`);
            this.formGroup.controls['subfamilyControl'].disable();
          } else {
            this.resourcesService.openSnackBar(`No se encontró la subfamilia.`);
            this.resourcesService.goBack();
            return;
          }

          

          this.formGroup.controls['equipmentTypeControl'].setValue(this.artitleByAdquisicion.MODELO_INFORMACION);
          this.formGroup.controls['equipmentTypeControl'].disable();
          this.formGroup.controls['equipmentModelControl'].setValue(this.artitleByAdquisicion.CODIGO_INFORMACION);
          this.formGroup.controls['equipmentModelControl'].disable();
          
          let strDateAdquisition: string = this.artitleByAdquisicion.FECHA_ADQUISICION;
          let arrDateAdquisition: Array<string> = strDateAdquisition.split(' ');
          let dateAdquisition: Date = this.resourcesService.formatStrDateToDate(arrDateAdquisition[0]);

          this.formGroup.controls['acquisitionDateControl'].setValue(dateAdquisition);
          this.formGroup.controls['acquisitionDateControl'].disable();
          this.minDateWarrantyStart = dateAdquisition;
          this.minDateDue = dateAdquisition;
          
          this.formGroup.controls['equipmentProviderControl'].setValue(`(${this.artitleByAdquisicion.NUMERO_PROVEEDOR}) ${this.artitleByAdquisicion.NOMBRE_PROVEEDOR}`);
          this.formGroup.controls['equipmentProviderControl'].disable();

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

  async searchSubfamilies(value: string){
    try{
      this.searchingSubfamilies = true;
      let familyCode = value.replace('-enc', '');

      let idUser = localStorage.getItem('idusuario')!;
      let subfamilies: SubfamiliesListResponse = await lastValueFrom(this._equipmentManagementService.subfamilyConsult(familyCode, idUser, 1));

      if(subfamilies.error){
        this.resourcesService.openSnackBar(subfamilies.msg);
        this.formGroup.controls['subfamilyControl'].disable();
      }else{
        this.subfamiliesArr = [];
        this.formGroup.controls['subfamilyControl'].enable();

        let subfamiliesTmp: SubfamiliesListItem[] = [];
        for(const subfamily of subfamilies.response){
          let codeDec = await this._encService.decrypt(subfamily.CODIGOSUBFAMILIA);

          subfamily.NOMBRESUBFAMILIA = `${subfamily.NOMBRESUBFAMILIA} (${codeDec})`;
          subfamiliesTmp.push(subfamily);
        }

        this.subfamiliesArr = subfamiliesTmp;
      }

      this.formGroup.controls['subfamilyControl'].setValue(null);
      this.searchingSubfamilies = false;
      await this.buildPreviewTag('familyControl', value);
    }catch(error: any){
      if(error.error == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  async init(idEquipmentEnc: string){
  }

  async buildPreviewTag(controlName: string, value: string){
    this.generatedTag = "";

    let codeType = this.formGroup.controls['codeTypeControl'].value;
    let controlValues: Map<string, string> = new Map();
    let line = this.formGroup.controls['lineControl'].value;
    controlValues.set('lineControl', line);

    for(const control of this.codeControlsStr){
      if(!controlValues.has(control)){
        let controlValue = "";
        if(controlName == control){
          controlValue = value;
        }else{
          controlValue = this.formGroup.controls[control].value;
        }

        if(controlValue != null && controlValue != undefined && controlValue != ''){
          if(controlValue.includes('-enc')){
            controlValue = controlValue.replace('-enc', '');
            controlValue = await this._encService.decrypt(controlValue);
          }else if((control == 'originElementControl' || control == 'destinyElementControl') && codeType == '4'){
            let codeArr = controlValue.split('_');
            let lbsArr = codeArr[0].split('.').reverse();
            let pbsArr = codeArr[1].split('-').reverse();

            controlValue = lbsArr[0];
            if(control == 'originElementControl'){
              this.formGroup.controls['originSequenceControl'].setValue(pbsArr[0]);
            }else{
              this.formGroup.controls['destinySequenceControl'].setValue(pbsArr[0]);
            }
          }else if((control == 'originElementControl' || control == 'destinyElementControl') && codeType != '2'){
            controlValue = this.processElement(controlValue, 'element');
          }else if(control == 'originElementControl' && codeType == '2'){
            let valArr = controlValue.split('-').reverse();
            controlValue = valArr[0].trim();
          }else if((control == 'originKilometersControl' || control == 'destinyKilometersControl')){
            controlValue = controlValue.replace('-km', '');
            controlValue = controlValue.replace('.', ',');
          }else if(control == 'trainAreaControl'){
            let valueArr = controlValue.split('(').reverse();
            controlValue = valueArr[0].replace(')', '');
          }
        }

        controlValues.set(control, controlValue);
      }
    }
    
    let hierarchy = this.formGroup.controls['hierarchyControl'].value;
    if(hierarchy == 'Hijo'){
      let parentCodeVal = this.formGroup.controls['fatherControl'].value;
      let parentCodeArr = parentCodeVal.split(' - ');

      this.generatedTag = parentCodeArr[0];
      let equipmentControls = ['equipmentTypeControl', 'equipmentModelControl', 'equipmentIDControl'];
      let equipmentTag = "";

      for(const key of equipmentControls){
        let val = controlValues.get(key);
        let codePart = 'N/D';

        if(val != null && val != undefined && val != ''){
          let type = key == 'equipmentModelControl' ? 'model' : 'element';
          codePart = this.processElement(val, type);
        }

        equipmentTag += `${codePart}-`;
      }
      
      equipmentTag = equipmentTag.substring(0, equipmentTag.length - 1);
      this.generatedTag += `.${equipmentTag}`;
    }else{
      switch(codeType){
        case "1": 
          let lbsControls = ['lineControl', 'originLocationControl', 'originLevelControl', 'originOccupationControl', 
          'originElementControl'];
          let lbsTag = "";
  
          for(const key of lbsControls){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            lbsTag += `${codePart}.`;
          }
  
          lbsTag = lbsTag.substring(0, lbsTag.length - 1);
          let pbsControls = ['familyControl', 'subfamilyControl', 'statusControl'];
          let pbsTag = "";
  
          for(const key of pbsControls){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            pbsTag += `${codePart}.`;
          }
  
          pbsTag = pbsTag.substring(0, pbsTag.length - 1);
          let equipmentControls = ['equipmentTypeControl', 'equipmentModelControl', 'equipmentIDControl'];
          let equipmentTag = "";
  
          for(const key of equipmentControls){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              let type = key == 'equipmentModelControl' ? 'model' : 'element';
              codePart = this.processElement(val, type);
            }
  
            equipmentTag += `${codePart}-`;
          }
          
          equipmentTag = equipmentTag.substring(0, equipmentTag.length - 1);
          this.generatedTag = `${lbsTag}_${pbsTag}.${equipmentTag}`;
        break;
        case "2": 
          let lbsControls2 = ['lineControl', 'originLocationControl', 'originLevelControl', 'originOccupationControl', 
          'originElementControl', 'pccIntersectionControl', 'pccPositionControl'];
          let lbsTag1 = "";
  
          for(const key of lbsControls2){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            lbsTag1 += `${codePart}.`;
          }
  
          lbsTag1 = lbsTag1.substring(0, lbsTag1.length - 1);
          let pbsControls1 = ['familyControl', 'subfamilyControl', 'statusControl'];
          let pbsTag1 = "";
  
          for(const key of pbsControls1){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            pbsTag1 += `${codePart}.`;
          }
  
          pbsTag1 = pbsTag1.substring(0, pbsTag1.length - 1);
          let equipmentControls1 = ['equipmentTypeControl', 'equipmentModelControl', 'equipmentIDControl'];
          let equipmentTag1 = "";
  
          for(const key of equipmentControls1){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              let type = key == 'equipmentModelControl' ? 'model' : 'element';
              codePart = this.processElement(val, type);
            }
  
            equipmentTag1 += `${codePart}-`;
          }
          
          equipmentTag1 = equipmentTag1.substring(0, equipmentTag1.length - 1);
          this.generatedTag = `${lbsTag1}_${pbsTag1}.${equipmentTag1}`;
        break;
        case "3":
          let lbsOriginControls = ['lineControl', 'originLocationControl', 'originLevelControl', 'originOccupationControl', 
          'originElementControl', 'originKilometersControl'];
          let lbsOriginTag = "";
  
          for(const key of lbsOriginControls){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            lbsOriginTag += `${codePart}.`;
          }
  
          lbsOriginTag = lbsOriginTag.substring(0, lbsOriginTag.length - 1);
          let lbsDestinyControls = ['destinyLocationControl', 'destinyLevelControl', 'destinyOccupationControl', 'destinyElementControl', 
          'destinyKilometersControl'];
          let lbsDestinyTag = "";
  
          for(const key of lbsDestinyControls){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            lbsDestinyTag += `${codePart}.`;
          }
  
          lbsDestinyTag = lbsDestinyTag.substring(0, lbsDestinyTag.length - 1);
          let pbsControls2 = ['familyControl', 'subfamilyControl', 'statusControl'];
          let pbsTag2 = "";
  
          for(const key of pbsControls2){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            pbsTag2 += `${codePart}.`;
          }
  
          pbsTag2 = pbsTag2.substring(0, pbsTag2.length - 1);
          let equipmentControls2 = ['equipmentTypeControl', 'equipmentModelControl', 'equipmentIDControl'];
          let equipmentTag2 = "";
  
          for(const key of equipmentControls2){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              let type = key == 'equipmentModelControl' ? 'model' : 'element';
              codePart = this.processElement(val, type);
            }
  
            equipmentTag2 += `${codePart}-`;
          }
          
          equipmentTag2 = equipmentTag2.substring(0, equipmentTag2.length - 1);
          this.generatedTag = `${lbsOriginTag}:${lbsDestinyTag}_${pbsTag2}.${equipmentTag2}`;
        break;
        case "4":
          let lbsOriginControls0 = ['lineControl', 'originLocationControl', 'originLevelControl', 'originOccupationControl', 
          'originElementControl'];
          let lbsOriginTag0 = "";
  
          for(const key of lbsOriginControls0){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            lbsOriginTag0 += `${codePart}.`;
          }
  
          let lbsOriginSequence = this.formGroup.controls['originSequenceControl'].value;
          if(lbsOriginSequence != undefined  && lbsOriginSequence != null && lbsOriginSequence != ''){
            lbsOriginTag0 += lbsOriginSequence;
          }else{
            lbsOriginTag0 += 'N/D';
          }
  
          let lbsDestinyControls0 = ['destinyLocationControl', 'destinyLevelControl', 'destinyOccupationControl', 'destinyElementControl'];
          let lbsDestinyTag0 = "";
  
          for(const key of lbsDestinyControls0){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            lbsDestinyTag0 += `${codePart}.`;
          }
  
          let lbsDestinySequence = this.formGroup.controls['destinySequenceControl'].value;
          if(lbsDestinySequence != undefined  && lbsDestinySequence != null && lbsDestinySequence != ''){
            lbsDestinyTag0 += lbsDestinySequence;
          }else{
            lbsDestinyTag0 += 'N/D';
          }
          
          let pbsControls3 = ['familyControl', 'subfamilyControl', 'statusControl'];
          let pbsTag3 = "";
  
          for(const key of pbsControls3){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            pbsTag3 += `${codePart}.`;
          }
  
          pbsTag3 = pbsTag3.substring(0, pbsTag3.length - 1);
          let equipmentControls3 = ['equipmentTypeControl', 'equipmentModelControl', 'equipmentIDControl'];
          let equipmentTag3 = "";
  
          for(const key of equipmentControls3){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              let type = key == 'equipmentModelControl' ? 'model' : 'element';
              codePart = this.processElement(val, type);
            }
  
            equipmentTag3 += `${codePart}-`;
          }
          
          equipmentTag3 = equipmentTag3.substring(0, equipmentTag3.length - 1);
          this.generatedTag = `${lbsOriginTag0}:${lbsDestinyTag0}_${pbsTag3}.${equipmentTag3}`;
        break;
        case "5": 
          let lbsControls3 = ['lineControl', 'originLocationControl', 'originLevelControl', 'originOccupationControl', 
          'trainAreaControl', 'originElementControl'];
          let lbsTag3 = "";
  
          for(const key of lbsControls3){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            lbsTag3 += `${codePart}.`;
          }
  
          lbsTag3 = lbsTag3.substring(0, lbsTag3.length - 1);
          let pbsControls4 = ['familyControl', 'subfamilyControl', 'statusControl'];
          let pbsTag4 = "";
  
          for(const key of pbsControls4){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            pbsTag4 += `${codePart}.`;
          }
  
          pbsTag4 = pbsTag4.substring(0, pbsTag4.length - 1);
          let equipmentControls4 = ['equipmentTypeControl', 'equipmentModelControl', 'equipmentIDControl'];
          let equipmentTag4 = "";
  
          for(const key of equipmentControls4){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              let type = key == 'equipmentModelControl' ? 'model' : 'element';
              codePart = this.processElement(val, type);
            }
  
            equipmentTag4 += `${codePart}-`;
          }
          
          equipmentTag4 = equipmentTag4.substring(0, equipmentTag4.length - 1);
          this.generatedTag = `${lbsTag3}_${pbsTag4}.${equipmentTag4}`;
        break;
        case "7":
          let siteTag: string = '';
          let siteControls: Array<string> = ['lineControl', 'areaIDControl', 'levelIDControl'];
          for(const key of siteControls){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            siteTag += `${codePart}.`;            
          }
          siteTag = siteTag.substring(0, siteTag.length - 1);

          let areaTag: string = '';
          let areaControls: Array<string> = ['warehouseIDControl', 'zoneIDControl'];
          for(const key of areaControls){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            areaTag += `${codePart}.`;  
          }
          areaTag = areaTag.substring(0, areaTag.length - 1);

          let technicalSpecificationTag: string = '';
          let technicalSpecificationControls: Array<string> = ['familyControl', 'subfamilyControl', 'statusControl'];
          for(const key of technicalSpecificationControls){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              codePart = val;
            }
  
            technicalSpecificationTag += `${codePart}.`;  
          }
          technicalSpecificationTag = technicalSpecificationTag.substring(0, technicalSpecificationTag.length - 1);

          let equipmentIdentufierTag: string = '';
          let equipmentIdentufierControls: Array<string> = ['equipmentTypeControl', 'equipmentModelControl', 'equipmentIDControl'];
          for(const key of equipmentIdentufierControls){
            let val = controlValues.get(key);
            let codePart = 'N/D';
  
            if(val != null && val != undefined && val != ''){
              let type = key == 'equipmentModelControl' ? 'model' : 'element';
              codePart = this.processElement(val, type);
            }
  
            equipmentIdentufierTag += `${codePart}-`;
          }
          equipmentIdentufierTag = equipmentIdentufierTag.substring(0, equipmentIdentufierTag.length - 1);
          
          this.generatedTag = `${siteTag}-${areaTag}_${technicalSpecificationTag}.${equipmentIdentufierTag}`;
          break;
      }
    }
  }

  processElement(value: string, type: string): string{
    //PASO 1: Conertir la cadena en mayúsculas
    value = value.toUpperCase();

    //PASO 2: Eliminar acentos
    let valueArr0 = value.split('');
    let validVal0 = "";
    valueArr0.forEach(char => {
      switch(char){
        case "Á": validVal0 += 'A'; break;
        case "É": validVal0 += 'E'; break;
        case "Í": validVal0 += 'I'; break;
        case "Ó": validVal0 += 'O'; break;
        case "Ú": validVal0 += 'U'; break;
        default: validVal0 += char; break;
      }
    });

    //PASO 3: Eliminar conectores
    const CONNECTORS = ['DE', 'PARA', 'Y', 'O', 'DEL', 'EL', 'LA', 'LOS', 'POR', 'EN'];
    let valueArr1 = validVal0.split(' ');
    let validVal1: string[] = [];
    valueArr1.forEach(word => {
      if(!CONNECTORS.includes(word) && word != ""){
        validVal1.push(word);
      }
    });

    //PASO 4: Obtener la longitud del arreglo de palabras válidas
    let validLength = validVal1.length;

    //PASO 5: Obtener el código del elemento según la longitud
    let validVal2 = "";
    if(validLength == 1){
      if(validVal1[0].length < 5){
        validVal2 = validVal1[0];
        for(let i = validVal1[0].length; i < 5; i++){
          if(type == 'model'){
            validVal2 = `X${validVal2}`;
          }else{
            validVal2 = `${validVal2}X`;
          }
        }
      }else{
        validVal2 = validVal1[0].substring(0, 5);
      }
    }else if(validLength == 2){
      let word1 = "";
      if(validVal1[0].length < 2){
        if(type == 'model'){
          word1 = `X${validVal1[0]}`;
        }else{
          word1 = `${validVal1[0]}X`;
        }
      }else{
        word1 = validVal1[0].substring(0, 2);
      }

      let word2 = "";
      if(validVal1[1].length < 3){
        word2 = validVal1[1];
        for(let i = validVal1[1].length; i < 3; i++){
          if(type == 'model'){
            word2 = `X${word2}`;
          }else{
            word2 = `${word2}X`;
          }
        }
      }else{
        word2 = validVal1[1].substring(0, 3);
      }

      validVal2 = `${word1}${word2}`;
    }else if(validLength == 3){
      let word1 = "";
      if(validVal1[0].length < 2){
        if(type == 'model'){
          word1 = `X${validVal1[0]}`;
        }else{
          word1 = `${validVal1[0]}X`;
        }
      }else{
        word1 = validVal1[0].substring(0, 2);
      }

      let word2 = validVal1[1].substring(0, 1);
      
      let word3 = "";
      if(validVal1[2].length < 2){
        if(type == 'model'){
          word3 = `X${validVal1[2]}`;
        }else{
          word3 = `${validVal1[2]}X`;
        }
      }else{
        word3 = validVal1[2].substring(0, 2);
      }

      validVal2 = `${word1}${word2}${word3}`;
    }else if(validLength == 4){
      let word1 = "";
      if(validVal1[0].length < 2){
        if(type == 'model'){
          word1 = `X${validVal1[0]}`;
        }else{
          word1 = `${validVal1[0]}X`;
        }
      }else{
        word1 = validVal1[0].substring(0, 2);
      }

      let word2 = validVal1[1].substring(0, 1);
      let word3 = validVal1[2].substring(0, 1);
      let word4 = validVal1[3].substring(0, 1);

      validVal2 = `${word1}${word2}${word3}${word4}`;
    }else if(validLength >= 5){
      let word1 = validVal1[0].substring(0, 1);
      let word2 = validVal1[1].substring(0, 1);
      let word3 = validVal1[2].substring(0, 1);
      let word4 = validVal1[3].substring(0, 1);
      let word5 = validVal1[4].substring(0, 1);

      validVal2 = `${word1}${word2}${word3}${word4}${word5}`;
    }
    
    return validVal2;
  }

  onResize():void{
    
  }

  async changeHierarchy(value: string){
    if(value == 'Hijo'){
      this.searchingEquipments = true;
      this.formGroup.controls['fatherControl'].enable();
      this.formGroup.controls['codeTypeControl'].disable();
      this.formGroup.controls['codeTypeControl'].setValue(null);

      if (!this.isFromAdquisition) {
        await this.searchEquipments();
      } else if (this.artitleByAdquisicion !== null && this.isFromAdquisition) {
        const codeFamily: string = await this._encService.encrypt(this.artitleByAdquisicion.CODIGO_FAMILIA);
        const codeSubamily: string = await this._encService.encrypt(this.artitleByAdquisicion.CODIGO_SUBFAMILIA);
        await this.getEquipmentsByFamily(codeFamily, codeSubamily);
      }


    }else{
      this.formGroup.controls['fatherControl'].setValue(null);
      this.formGroup.controls['fatherControl'].disable();
      this.formGroup.controls['codeTypeControl'].enable();
    }
  }

  async searchEquipments(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let equipments: EquipmentsListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsult(idUser, 1));

      if(equipments.error){
        this.resourcesService.openSnackBar(equipments.msg);
      }else{
        let equipmentsArr: EquipmentsListItem[] = [];
        let equipmentsStrArr: string[] = [];

        for(const equipment of equipments.response){
          let codeDec = await this._encService.decrypt(equipment.CODIGO);
          let idDec = await this._encService.decrypt(equipment.ID_EQUIPO);
          let equipmentStr = `${codeDec} - ${equipment.TIPO} - ${equipment.MODELO} (${idDec})`;

          equipmentsArr.push(equipment);
          equipmentsStrArr.push(equipmentStr);
        }
        
        this.equipments = equipmentsArr;
        this.equipmentsStr = equipmentsStrArr;
        this.searchingEquipments = false;
      }
    }catch(error: any){
      if(error.error == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.resourcesService.openSnackBar(error.error.msg);
      }

      this.searchingEquipments = false;
    }
  }

  private async getEquipmentsByFamily(family:string, subfamily:string) {
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._equipmentManagementService.equipmentConsultBySubfamily(family, subfamily, user, line)).then(
      async (responseData: EquipmentsListResponse) => {
        if (!responseData.error) {


          if (responseData.response.length === 0) {
            this.formGroup.controls['hierarchyControl'].setValue('Padre');
            this.formGroup.controls['hierarchyControl'].disable();
            this.formGroup.controls['codeTypeControl'].enable();
          } else {
            let equipmentsArr: EquipmentsListItem[] = [];
            let equipmentsStrArr: string[] = [];

            for(const equipment of responseData.response){
              let codeDec = await this._encService.decrypt(equipment.CODIGO);
              let idDec = await this._encService.decrypt(equipment.ID_EQUIPO);
              let equipmentStr = `${codeDec} - ${equipment.TIPO} - ${equipment.MODELO} (${idDec})`;

              equipmentsArr.push(equipment);
              equipmentsStrArr.push(equipmentStr);
            }
            
            this.equipments = equipmentsArr;
            this.equipmentsStr = equipmentsStrArr;
            this.searchingEquipments = false;
          }


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

  verifyFather(value: string){
    let valueArr = value.split(' - ');
    if(valueArr.length != 3 && value != null && value != undefined && value != ''){
      this.resourcesService.openSnackBar('El valor del equipo padre es inválido.');
      return;
    }else if(valueArr.length == 3 && value != null && value != undefined && value != ''){
      this.getFatherDescription(valueArr[0]);
    }
  }

  async getFatherDescription(fatherCode: string){
    let dialogRef = this._dialog.open(FatherLoaderComponent, {
      width: '360px',
      maxWidth: '360px',
      disableClose: true
    });

    let equipmentFilt: EquipmentsListItem | null = null;
    for(const equipment of this.equipments){
      let codeDec = await this._encService.decrypt(equipment.CODIGO);
      if(codeDec == fatherCode){
        equipmentFilt = equipment;
      }
    }

    if(equipmentFilt == null){
      this.resourcesService.openSnackBar('El equipo padre seleccionado no existe.');
    }else{
      let idUser = localStorage.getItem('idusuario')!;
      let equipment: EquipmentDetailsResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultOnly(
        equipmentFilt.CODIGO, 
        idUser, 
        1
      ));

      if(equipment.error){
        this.resourcesService.openSnackBar(equipment.msg);
      }else{
        this.formGroup.controls['codeTypeControl'].setValue(equipment.response.TIPO_CODIGO);

        let originLocationArr = equipment.response.UBICACION_ORIGEN.split('(').reverse();
        let originLocation = originLocationArr[0].replace(')', '');

        for(const location of this.locationsArr){
          let codeDec = await this._encService.decrypt(location.CODE);
          if(codeDec == originLocation){
            this.formGroup.controls['originLocationControl'].setValue(`${location.CODE}-enc`);
          }
        }

        let originLevelArr = equipment.response.NIVEL_ORIGEN.split('(').reverse();
        let originLevel = originLevelArr[0].replace(')', '');

        for(const level of this.levelsArr){
          let codeDec = await this._encService.decrypt(level.CODE);
          if(originLevel == codeDec){
            this.formGroup.controls['originLevelControl'].setValue(`${level.CODE}-enc`);
          }
        }

        let originOccupationArr = equipment.response.OCUPACION_ORIGEN.split('(').reverse();
        let originOccupation = originOccupationArr[0].replace(')', '');

        for(const occupation of this.occupations){
          let occupationDec = await this._encService.decrypt(occupation.OCUPACION);
          if(occupationDec == originOccupation){
            this.formGroup.controls['originOccupationControl'].setValue(`${occupation.OCUPACION}-enc`);
          }
        }

        this.formGroup.controls['originElementControl'].setValue(equipment.response.ELEMENTO_ORIGEN);
        let familyArr = equipment.response.FAMILIA.split('(').reverse();
        let familyStr = familyArr[0].replace(')', '');

        for(const family of this.familiesArr){
          let codeDec = await this._encService.decrypt(family.CODIGOFAMILIA);
          if(codeDec == familyStr){
            this.formGroup.controls['familyControl'].setValue(`${family.CODIGOFAMILIA}-enc`);
          }
        }

        let familyEnc = await this._encService.encrypt(familyStr);
        let subfamilies: SubfamiliesListResponse = await lastValueFrom(this._equipmentManagementService.subfamilyConsult(
          familyEnc,
          idUser,
          1
        ));

        if(subfamilies.error){
          this.resourcesService.openSnackBar(subfamilies.msg);
          dialogRef.close();
          return;
        }
        
        let subfamilyArr = equipment.response.SUBFAMILIA.split('(').reverse();
        let subfamilyStr = subfamilyArr[0].replace(')', '');
        let subfamiliesArr: SubfamiliesListItem[] = [];

        for(const subfamily of subfamilies.response){
          let codeDec = await this._encService.decrypt(subfamily.CODIGOSUBFAMILIA);
          subfamily.NOMBRESUBFAMILIA = `${subfamily.NOMBRESUBFAMILIA} (${codeDec})`;

          if(codeDec == subfamilyStr){
            this.formGroup.controls['subfamilyControl'].setValue(`${subfamily.CODIGOSUBFAMILIA}-enc`);
          }

          subfamiliesArr.push(subfamily)
        };

        this.subfamiliesArr = subfamiliesArr;
        let stateArr = equipment.response.ESTADO.split('(').reverse();
        let stateStr = stateArr[0].replace(')', '');

        for(const state of this.statesArr){
          let idDec = await this._encService.decrypt(state.ID);
          if(idDec == stateStr){
            this.formGroup.controls['statusControl'].setValue(`${state.ID}-enc`);
          }
        }
        
        if (!this.isFromAdquisition) {
          this.formGroup.controls['equipmentTypeControl'].enable();
          this.formGroup.controls['equipmentModelControl'].enable();
        }
        dialogRef.close();

        this.buildPreviewTag('', '');
      }
    }
  }

  async changeCodeType(val: string){
    this.clearForm();
    
    this.formGroup.controls['originLocationControl'].enable();
    this.formGroup.controls['originLevelControl'].enable();
    this.formGroup.controls['originOccupationControl'].enable();
    if (!this.isFromAdquisition) {
      this.formGroup.controls['familyControl'].enable();
      this.formGroup.controls['equipmentTypeControl'].enable();
      this.formGroup.controls['equipmentModelControl'].enable();
    }
    this.formGroup.controls['statusControl'].enable();
    this.formGroup.controls['originElementControl'].enable();

    if(val == '2'){
      this.formGroup.controls['pccPositionControl'].enable();
      this.formGroup.controls['originElementControl'].disable();
    }else if(val == '3'){
      this.formGroup.controls['originKilometersControl'].enable();
      this.formGroup.controls['destinyLocationControl'].enable();
      this.formGroup.controls['destinyLevelControl'].enable();
      this.formGroup.controls['destinyOccupationControl'].enable();
      this.formGroup.controls['destinyElementControl'].enable();
      this.formGroup.controls['destinyKilometersControl'].enable();
    }else if(val == '4'){
      this.formGroup.controls['originElementControl'].disable();
      this.formGroup.controls['originLocationControl'].disable();
      this.formGroup.controls['originLevelControl'].disable();
      this.formGroup.controls['originOccupationControl'].disable();
    }else if(val == '5'){
      this.formGroup.controls['originOccupationControl'].disable();

      for(const level of this.levelsArr){
        let codeDec = await this._encService.decrypt(level.CODE);
        if(codeDec == 'P00'){
          this.formGroup.controls['originLevelControl'].disable();
          this.formGroup.controls['originLevelControl'].setValue(`${level.CODE}-enc`);
        }
      }
    }else if(val == '6'){
      this.formGroup.controls['originLocationControl'].disable();
      this.formGroup.controls['originLevelControl'].disable();
      this.formGroup.controls['originOccupationControl'].disable();
      this.formGroup.controls['originElementControl'].disable();
      this.formGroup.controls['mixDestinyControl'].enable();
      this.formGroup.controls['mixOriginControl'].enable();
    }
    if(val == '7'){
      let state = this.statesArr.find((state) => state.STATUS === 'Stock (S)');
      if (state !== undefined) {
        this.formGroup.controls['statusControl'].setValue(`${state.ID}-enc`);
        this.formGroup.controls['statusControl'].disable();
      } else{
        this.resourcesService.openSnackBar(`No se encontró el estado del Stock`);
      }

      this.formGroup.controls['warehouseIDControl'].setValidators(Validators.required);
      this.formGroup.controls['areaIDControl'].setValidators(Validators.required);
      this.formGroup.controls['levelIDControl'].setValidators(Validators.required);
      this.formGroup.controls['zoneIDControl'].setValidators(Validators.required);
      
      this.formGroup.controls['originLocationControl'].clearValidators();
      this.formGroup.controls['originLocationControl'].updateValueAndValidity();
      this.formGroup.controls['originLevelControl'].clearValidators();
      this.formGroup.controls['originLevelControl'].updateValueAndValidity();
      this.formGroup.controls['originOccupationControl'].clearValidators();
      this.formGroup.controls['originOccupationControl'].updateValueAndValidity();
      this.formGroup.controls['originElementControl'].clearValidators();
      this.formGroup.controls['originElementControl'].updateValueAndValidity();
      
    } else {
      this.formGroup.controls['warehouseIDControl'].clearValidators();
      this.formGroup.controls['warehouseIDControl'].updateValueAndValidity();
      this.formGroup.controls['areaIDControl'].clearValidators();
      this.formGroup.controls['areaIDControl'].updateValueAndValidity();
      this.formGroup.controls['levelIDControl'].clearValidators();
      this.formGroup.controls['levelIDControl'].updateValueAndValidity();
      this.formGroup.controls['zoneIDControl'].clearValidators();
      this.formGroup.controls['zoneIDControl'].updateValueAndValidity();
      
      this.formGroup.controls['originLocationControl'].setValidators(Validators.required);
      this.formGroup.controls['originLevelControl'].setValidators(Validators.required);
      this.formGroup.controls['originOccupationControl'].setValidators(Validators.required);
      this.formGroup.controls['originElementControl'].setValidators(Validators.required);
    }

    this.formGroup.updateValueAndValidity();
    this.buildPreviewTag('', '');
  }

  clearForm(){
    this.codeControlsStr.forEach(control => {
      if(control != 'lineControl' && control != 'equipmentIDControl'){
        if (!this.isFromAdquisition && control !== 'familyControl' && control !== 'subfamilyControl') {
          this.formGroup.controls[control].setValue(null);
          this.formGroup.controls[control].disable();
        }
      }

      if(control == 'originLocationControl'){
        this.formGroup.controls['originLocationControl'].setValidators(Validators.required);
      }
    })
  }

  openCarAreaDialog(){
    let trainOccupation = this.formGroup.controls['originOccupationControl'].value;
    if(trainOccupation == undefined || trainOccupation == null || trainOccupation == ''){
      this.resourcesService.openSnackBar('Aún no ha seleccionado una ocupación.');
    }else{
      let dialogRef = this._dialog.open(LocateCarAreaComponent, {
        width: '1144px',
        maxWidth: '1144px',
        disableClose: true,
        data: {
          trainOccupation: trainOccupation
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res != null && res != undefined && res != ''){
          this.setCarArea(res);
        }
      });
    }
  }

  async setCarArea(areaEnc: string){
    let areaDec = await this._encService.decrypt(areaEnc);
    let areaFilt = null;
    
    for(const area of this.carAreas){
      let codeDec = await this._encService.decrypt(area.CODE);
      if(codeDec == areaDec){
        areaFilt = area;
      }
    }

    if(areaFilt == null){
      this.resourcesService.openSnackBar(`El area ${areaDec} es inválida.`);
    }else{
      this.formGroup.controls['trainAreaControl'].setValue(areaFilt.AREA);
      this.buildPreviewTag('trainAreaControl', areaDec);
    }
  }

  mixChange(type: string, value: string){
    if(type == 'mixOriginControl'){
      if(value == '1'){
        this.formGroup.controls['originLocationControl'].enable();
        this.formGroup.controls['originLevelControl'].enable();
        this.formGroup.controls['originOccupationControl'].enable();
        this.formGroup.controls['originElementControl'].enable();
      }
    }else{

    }
  }

  async openEquipmentSearch(type: string){
    let originElementVal = this.formGroup.controls['originElementControl'].value;
    let destinyElementVal = this.formGroup.controls['destinyElementControl'].value;
    let originElementEnc = originElementVal == undefined || originElementVal == null ? undefined : await this._encService.encrypt(originElementVal);
    let destinyElementEnc = destinyElementVal == undefined || destinyElementVal == null ? undefined : await this._encService.encrypt(destinyElementVal);

    let dialogRef = this._dialog.open(SearchEquipmentComponent, {
      disableClose: true,
      width: '920px',
      maxWidth: '920px',
      data: {
        originElement: originElementEnc,
        destinyElement: destinyElementEnc,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.asignElement(type, res);
      }
    });
  }

  async asignElement(type: string, codeEnc: string){
    let codeDec = await this._encService.decrypt(codeEnc);
    let control = type == 'origin' ? 'originElementControl' : 'destinyElementControl';
    let codeArr = codeDec.split('_');
    let lbsArr = codeArr[0].split('.');

    let control2 = type == 'origin' ? 'destinyElementControl' : 'originElementControl';
    let value2 = this.formGroup.controls[control2].value;
    
    let originLocation = type == 'origin' ? lbsArr[1] : '';
    let destinyLocation = type == 'origin' ? '' : lbsArr[1];
    let originLevel = type == 'origin' ? lbsArr[2] : '';
    let destinyLevel = type == 'origin' ? '' : lbsArr[2];
    let originOccupation = type == 'origin' ? lbsArr[3] : '';
    let destinyOccupation = type == 'origin' ? '' : lbsArr[3];

    if(value2 != null && value2 != undefined && value2 != ''){
      let valueArr2 = value2.split('_');
      let lbsArr2 = valueArr2[0].split('.');

      originLocation = type == 'origin' ? originLocation : lbsArr2[1];
      destinyLocation = type == 'origin' ? lbsArr2[1] : destinyLocation;
      originLevel = type == 'origin' ? originLevel : lbsArr2[2];
      destinyLevel = type == 'origin' ? lbsArr2[2] : destinyLevel;
      originOccupation = type == 'origin' ? originOccupation : lbsArr[3];
      destinyOccupation = type == 'origin' ? lbsArr2[3] : destinyOccupation;
    }

    for(const location of this.locationsArr){
      let codeDec = await this._encService.decrypt(location.CODE);

      if(codeDec == originLocation){
        this.formGroup.controls['originLocationControl'].setValue(`${location.CODE}-enc`);
      }
      
      if(codeDec == destinyLocation){
        this.formGroup.controls['destinyLocationControl'].setValue(`${location.CODE}-enc`);
      }
    }
    
    for(const level of this.levelsArr){
      let codeDec = await this._encService.decrypt(level.CODE);

      if(codeDec == originLevel){
        this.formGroup.controls['originLevelControl'].setValue(`${level.CODE}-enc`);
      }
      
      if(codeDec == destinyLevel){
        this.formGroup.controls['destinyLevelControl'].setValue(`${level.CODE}-enc`);
      }
    }

    for(const occupation of this.occupations){
      let codeDec = await this._encService.decrypt(occupation.OCUPACION);

      if(codeDec == originOccupation){
        this.formGroup.controls['originOccupationControl'].setValue(`${occupation.OCUPACION}-enc`);
      }
      
      if(codeDec == destinyOccupation){
        this.formGroup.controls['destinyOccupationControl'].setValue(`${occupation.OCUPACION}-enc`);
      }
    }

    this.formGroup.controls[control].setValue(codeDec);
    this.buildPreviewTag(control, codeDec);
  }

  openIntersectionSelector(){
    let dialogRef = this._dialog.open(LocatePccComponent, {
      width: '720px',
      maxWidth: '720px',
      disableClose: true,
    });

    dialogRef.afterClosed().subscribe(res =>{
      if(res != undefined && res != null && res != ''){
        this.setElement(res);
      }
    });
  }

  async setElement(dataEnc: string){
    let dataDec = await this._encService.decrypt(dataEnc);
    let dataArr = dataDec.split('|');

    this.formGroup.controls['originElementControl'].setValue(`${dataArr[1]} - ${dataArr[2]}`);
    this.formGroup.controls['pccIntersectionControl'].setValue(dataArr[0]);
    this.buildPreviewTag('', '');
  }

  pccPositionChange(value: string){
    let numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let valueArr = value.split('');
    let validVal = "";

    valueArr.forEach(char => {
      if(numbers.includes(char)){
        validVal += char;
      }
    });

    this.formGroup.controls['pccPositionControl'].setValue(validVal);
    this.formGroup.controls['pccPositionControl'].markAsTouched();
    
    this.buildPreviewTag('pccPositionControl', validVal);
  }

  kilometersChange(value: string, formControl: string){
    let numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'];
    let valueArr = value.split('');
    let validVal = "";

    valueArr.forEach(char => {
      if(numbers.includes(char)){
        if(char != '.'){
          validVal += char;
        }else if(!validVal.includes('.')){
          validVal += char;
        }
      }
    });

    this.formGroup.controls[formControl].setValue(validVal);
    this.buildPreviewTag(formControl, `${validVal}-km`);
  }

  public async searchArea() {
    let encWarehouse = this.formGroup.controls['warehouseIDControl'].value;
    if (encWarehouse === '') {
      return;
    }
    this.searchingArea = true;

    encWarehouse = encWarehouse.replace('-enc', '');

    this.formGroup.controls['levelIDControl'].setValue('');
    this.formGroup.controls['zoneIDControl'].setValue('');

    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getAreaByWarehouse(encWarehouse, user, line)).then(
      async (responseData: ResponseDataGetAreaWarehouse) => {
        if (!responseData.error && responseData.response.length > 0) {
          let tempArea: Array<any> = [];
          await Promise.all(responseData.response.map(async (getAreaWarehouse: GetAreaWarehouse) => {
            const encCode:string = await this._encService.encrypt(getAreaWarehouse.CODIGO_AREA);
            tempArea.push({
              CODIGO_AREA: encCode,
              NOMBRE_AREA: `${getAreaWarehouse.NOMBRE_AREA} (${getAreaWarehouse.CODIGO_AREA})`,
            })
          }));
          this.arrAreas = tempArea;
          this.formGroup.controls['areaIDControl'].enable();
        } else if (!responseData.error && responseData.response.length === 0) {
          this.resourcesService.openSnackBar(`No existen áreas registradas para este almacén.`);
          this.formGroup.controls['areaIDControl'].disable();
          this.formGroup.controls['areaIDControl'].setValue('');
          this.formGroup.controls['levelIDControl'].disable();
          this.formGroup.controls['levelIDControl'].setValue('');
          this.formGroup.controls['zoneIDControl'].disable();
          this.formGroup.controls['zoneIDControl'].setValue('');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.searchArea();
        }
      }
    );

    const idWarehouse: string = await this._encService.decrypt(encWarehouse);
    this.buildPreviewTag('warehouseIDControl', idWarehouse);
    this.searchingArea = false;
  }

  public async searchLevel() {
    let encWarehouse = this.formGroup.controls['warehouseIDControl'].value;
    let encArea = this.formGroup.controls['areaIDControl'].value;
    if (encWarehouse === '' || encArea === '') {
      return;
    }
    
    this.searchingLevel = true;

    encWarehouse = encWarehouse.replace('-enc', '');
    encArea = encArea.replace('-enc', '');

    this.formGroup.controls['zoneIDControl'].setValue('');

    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getLevelByAreaWarehouse(encWarehouse, encArea, user, line)).then(
      async (responseData: ResponseDataGetLevelAreaWarehouse) => {
        if (!responseData.error && responseData.response.length > 0) {
          let tempLevel: Array<any> = [];
          await Promise.all(responseData.response.map(async (getLevelAreaWarehouse: GetLevelAreaWarehouse) => {
            const encCode:string = await this._encService.encrypt(getLevelAreaWarehouse.CODIGO_NIVEL);
            tempLevel.push({
              CODIGO_NIVEL: encCode,
              NOMBRE_NIVEL: `${getLevelAreaWarehouse.NOMBRE_NIVEL} (${getLevelAreaWarehouse.CODIGO_NIVEL})`,
            })
          }));
          this.arrLevel = tempLevel;
          this.formGroup.controls['levelIDControl'].enable();
        } else if (!responseData.error && responseData.response.length === 0) {
          this.resourcesService.openSnackBar(`No existen niveles registrados para esta área.`);
          this.formGroup.controls['levelIDControl'].disable();
          this.formGroup.controls['levelIDControl'].setValue('');
          this.formGroup.controls['zoneIDControl'].disable();
          this.formGroup.controls['zoneIDControl'].setValue('');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.searchLevel();
        }
      }
    );

    const idArea: string = await this._encService.decrypt(encArea);
    this.buildPreviewTag('areaIDControl', idArea);
    this.searchingLevel = false;
  }

  public async searchZone() {
    let encWarehouse = this.formGroup.controls['warehouseIDControl'].value;
    let encArea = this.formGroup.controls['areaIDControl'].value;
    let encLevel = this.formGroup.controls['levelIDControl'].value;
    if (encWarehouse === '' || encArea === '' || encLevel === '') {
      return;
    }

    this.searchingZone = true;    

    encWarehouse = encWarehouse.replace('-enc', '');
    encArea = encArea.replace('-enc', '');
    encLevel = encLevel.replace('-enc', '');

    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getZoneByLevelAreaWarehouse(encWarehouse, encArea, encLevel, user, line)).then(
      async (responseData: ResponseDataGetZoneLevelAreaWarehouse) => {
        if (!responseData.error && responseData.response.length > 0) {
          let tempZone: Array<any> = [];
          await Promise.all(responseData.response.map(async (getZoneLevelAreaWarehouse: GetZoneLevelAreaWarehouse) => {
            const encCode:string = await this._encService.encrypt(getZoneLevelAreaWarehouse.CODIGO_ZONA);
            tempZone.push({
              CODIGO_ZONA: encCode,
              NOMBRE_ZONA: `${getZoneLevelAreaWarehouse.NOMBRE_ZONA} (${getZoneLevelAreaWarehouse.CODIGO_ZONA})`,
            })
          }));
          this.arrZone = tempZone;
          this.formGroup.controls['zoneIDControl'].enable();
        } else if (!responseData.error && responseData.response.length === 0) {
          this.resourcesService.openSnackBar(`No existen zonas registradas para este nivel.`);
          this.formGroup.controls['zoneIDControl'].disable();
          this.formGroup.controls['zoneIDControl'].setValue('');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.searchZone();
        }
      }
    );
    const idLevel: string = await this._encService.decrypt(encLevel);
    this.buildPreviewTag('levelIDControl', idLevel);
    this.searchingZone = false;
  }

  public async setZone() {
    let encZone = this.formGroup.controls['zoneIDControl'].value;
    if (encZone !== '') {
      encZone = encZone.replace('-enc', '');
      const idZone: string = await this._encService.decrypt(encZone);
      this.buildPreviewTag('zoneIDControl', idZone);
    }
  }

  checkFile(event: any, type: string){
    let extArr = event.target.files[0].name.split(".").reverse();
    let extStr = extArr[0];

    if(type == 'imagen'){
      let allowedImages = ['png', 'gif', 'jpg'];
      if(!allowedImages.includes(extStr)){
        this.resourcesService.openSnackBar(`La extensión ${extStr} no corresponde a una imagen.`);
        return;
      }
    }else if(type == 'documento'){
      let allowedImages = ['pdf', 'doc', 'docx', 'ppt', 'pptx'];
      if(!allowedImages.includes(extStr)){
        this.resourcesService.openSnackBar(`La extensión ${extStr} no corresponde a una imagen.`);
        return;
      }
    }else{
      return;
    }
    
    let fileTypes = availableFiles;
    let sizes = Object.keys(fileTypes);
    let extensions = Object.values(fileTypes);
    let maxSizeMB = 0;

    let i = 0;
    extensions.forEach(ext => {
      let size = parseInt(sizes[i]);

      if(ext.includes(extStr)) maxSizeMB = size;
      i++;
    });

    if(maxSizeMB == 0){
      this.resourcesService.openSnackBar(`Los archivos ${extStr} no están soportados`);
    }else{
      let maxFileSize = 1048576 * maxSizeMB;
      let fileSize = event.target.files[0].size;

      if(fileSize > maxFileSize){
        this.resourcesService.openSnackBar(`El tamaño del archivo supera el límite de ${maxSizeMB} MB`);
      }else{
        let alreadyAttached = false;
        this.attachedImages.forEach(file => {
          alreadyAttached = file.name == event.target.files[0].name && file.size == this.resourcesService.formatBytes(event.target.files[0].size);
        });

        if(alreadyAttached){
          this.resourcesService.openSnackBar("El archivo seleccionado ya fue adjuntado.");
        }else{
          if(type == 'imagen'){
            this.uploadingImages = true;
          }else if(type == 'documento'){
            this.uploadingDocuments = true;
          }
          
          this.disableAttachActions = true;
          this.uploadTmp(event.target.files[0], type);
        }
      }
    }
  }

  async uploadTmp(fileData: any, type: string){
    try{
      let idUser = localStorage.getItem('idusuario');
      let formData = new FormData();

      formData.append('file', fileData);
      formData.append('id_user', idUser!);
      formData.append('linea', "1");

      let response = await lastValueFrom(this._gdelService.uploadTempFile(formData));

      if(response.error){
        this.resourcesService.openSnackBar(response.msg);
      }else{
        let uploadedFile: TempFileInfo = {
          id: response.response.idArchivo,
          name: fileData.name,
          size: this.resourcesService.formatBytes(fileData.size),
          type: 'Nuevo',
        };

        if(type == 'imagen'){
          this.attachedImages.push(uploadedFile);
          this.imagesDataSource = new MatTableDataSource(this.attachedImages);
          this.uploadingImages = false;
        }else{
          this.attachedDocuments.push(uploadedFile);
          this.documentsDataSource = new MatTableDataSource(this.attachedDocuments);
          this.uploadingDocuments = false;
        }
      }

      this.disableAttachActions = false;
    }catch(error: any){
      if(error.error == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.resourcesService.openSnackBar(error.error.msg);
      }

      this.uploadingImages = false;
      this.uploadingDocuments = false;
      this.disableAttachActions = false;
    }
  }

  async deleteFile(idFile: string, type: string){
    try{
      this.disableAttachActions = true;
      let idUser = localStorage.getItem('idusuario');
  
      await lastValueFrom(this._gdelService.deleteTempFile({
        'id_user': idUser!,
        'id_file': idFile,
        'linea': 1,
      }));
  
      let attachedAux: TempFileInfo[] = [];
      if(type == 'imagen'){
        this.attachedImages.forEach(item => {
          if(item.id != idFile){
            attachedAux.push(item);
          }
        });

        this.attachedImages = attachedAux;
        this.imagesDataSource = new MatTableDataSource(this.attachedImages);
      }else{
        this.attachedDocuments.forEach(item => {
          if(item.id != idFile){
            attachedAux.push(item);
          }
        });

        this.attachedDocuments = attachedAux;
        this.documentsDataSource = new MatTableDataSource(this.attachedDocuments);
      }

      this.disableAttachActions = false;
    }catch(error: any){
      if(error.error == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.resourcesService.openSnackBar(error.error.msg);
      }

      this.disableAttachActions = false;
    }
  }

  public registerSerieNumber() {
    let enableSerial = this.formGroup.controls['enableSerial'].value;

    if ( this.isFromAdquisition &&  this.numberItems !== 1 && !enableSerial) {

      let strSerialNumber:string = this.formGroup.controls['serialNumberControl'].value;
      let arrSerialNumber: Array<string> = strSerialNumber.split(',');

      if (arrSerialNumber.length > this.numberItems) {
        this.resourcesService.openSnackBar(`Ocurrió un error al abrir el registro de los números de serie.`);
        return;
      }

      let map: Map<string, string | boolean> = new Map<string, string | boolean>();
      map.set('IS_UNIQUE', this.isUniqueSerial);
      map.set('SERIAL_0', arrSerialNumber[0]);

      if (!this.isUniqueSerial) {
        for (let index = 1; index < this.numberItems; index++) {
          if (arrSerialNumber.hasOwnProperty(index)) {
            map.set('SERIAL_'+index, arrSerialNumber[index]);
          } else{
            map.set('SERIAL_'+index, '');
          }
        }
      }
      
      let object = Object.fromEntries(map.entries());

      this._dialog.open(RegisterMultipleDataComponent, {
        disableClose: true,
        width: '400px',
        maxWidth: '400px',
        data: {
          type: 'SERIAL',
          arrModel: object,
          numberItems: this.numberItems,
        },
      }).afterClosed().subscribe((result) => {
        if (result) {
          let strSerialNumber: string = '';
          let arrKeys = Object.keys(result.arrModel);
          arrKeys.forEach(key => {
            if (key === 'IS_UNIQUE') {
              this.isUniqueSerial = result.arrModel[key];
            } else {
              strSerialNumber += result.arrModel[key]+',';
            }
          });
          strSerialNumber = strSerialNumber.substring(0, strSerialNumber.length - 1);
          this.formGroup.controls['serialNumberControl'].setValue(strSerialNumber);
        }
      });
    }
  }

  public registerBarcode() {
    if ( this.isFromAdquisition && this.numberItems !== 1) {

      let strBarcode:string = this.formGroup.controls['barcodeControl'].value;
      let arrBarcode: Array<string> = strBarcode.split(',');

      if (arrBarcode.length > this.numberItems) {
        this.resourcesService.openSnackBar(`Ocurrió un error al abrir el registro de los números de serie.`);
        return;
      }

      let map: Map<string, string | boolean> = new Map<string, string | boolean>();
      map.set('IS_UNIQUE', this.isUniqueBarcorde);
      map.set('BARCODE_0', arrBarcode[0]);

      if (!this.isUniqueBarcorde) {
        for (let index = 1; index < this.numberItems; index++) {
          if (arrBarcode.hasOwnProperty(index)) {
            map.set('BARCODE_'+index, arrBarcode[index]);
          } else{
            map.set('BARCODE_'+index, '');
          }
        }
      }
      
      let object = Object.fromEntries(map.entries());

      this._dialog.open(RegisterMultipleDataComponent, {
        disableClose: true,
        width: '400px',
        maxWidth: '400px',
        data: {
          type: 'BARCODE',
          arrModel: object,
          numberItems: this.numberItems,
        },
      }).afterClosed().subscribe((result) => {
        if (result) {
          let strBarcode: string = '';
          let arrKeys = Object.keys(result.arrModel);
          arrKeys.forEach(key => {
            if (key === 'IS_UNIQUE') {
              this.isUniqueBarcorde = result.arrModel[key];
            } else {
              strBarcode += result.arrModel[key]+',';
            }
          });
          strBarcode = strBarcode.substring(0, strBarcode.length - 1);
          this.formGroup.controls['barcodeControl'].setValue(strBarcode);
        }
      });
    }
  }

  public registerDueDate() {
    if ( this.isFromAdquisition && this.numberItems !== 1 ) {
      let strDueDate:string = this.formGroup.controls['dueDateControl'].value;
      let arrDueDate: Array<string> = strDueDate.split(',');
  
      if (arrDueDate.length > this.numberItems) {
        this.resourcesService.openSnackBar(`Ocurrió un error al abrir el registro de los números de serie.`);
        return;
      }
  
      let dueDate = this.resourcesService.formatStrDateToDate(arrDueDate[0]);
      let map: Map<string, Date | string | boolean> = new Map<string, string | boolean>();
      map.set('IS_UNIQUE', this.isUniqueDueDate);
      map.set('DUE_DATE_0', dueDate);
  
      if (!this.isUniqueDueDate) {
        for (let index = 1; index < this.numberItems; index++) {
          if (arrDueDate.hasOwnProperty(index)) {
  
            let dueDate = this.resourcesService.formatStrDateToDate(arrDueDate[index]);
            map.set('DUE_DATE_'+index, dueDate);
          } else{
            map.set('DUE_DATE_'+index, '');
          }
        }
      }
      let object = Object.fromEntries(map.entries());
  
      this._dialog.open(RegisterMultipleDataComponent, {
        disableClose: true,
        width: '400px',
        maxWidth: '400px',
        data: {
          type: 'FECHA_VENCIMIENTO',
          arrModel: object,
          numberItems: this.numberItems,
          minDate: this.formGroup.controls['acquisitionDateControl'].value
        },
      }).afterClosed().subscribe((result) => {
        if (result) {
          let strDueDate: string = '';
          let arrKeys = Object.keys(result.arrModel);
          arrKeys.forEach(key => {
            if (key === 'IS_UNIQUE') {
              this.isUniqueDueDate = result.arrModel[key];
            } else {
              strDueDate += result.arrModel[key]+',';
            }
          });
          strDueDate = strDueDate.substring(0, strDueDate.length - 1);
          this.formGroup.controls['dueDateControl'].setValue(strDueDate);
        }
      });
    }
    
  }

  async saveEquipment(){
    try{
      if(this.formGroup.invalid){
        this.resourcesService.openSnackBar('Por favor ingrese la información requerida.');
      }else if(this.attachedImages.length < 1){
        this.resourcesService.openSnackBar('La galería de imágenes debe contener por lo menos 1 registro.');
      }else if(this.attachedDocuments.length < 1){
        this.resourcesService.openSnackBar('Los documentos relacionados deben contener por lo menos 1 registro.');
      }else{
        this.resourcesService.openSnackBar('Guardando registro...');
        let formValue = this.formGroup.getRawValue();
        let formData = new FormData();
        let idUser = localStorage.getItem('idusuario')!;
  
        formData.append('id_user', idUser);
        formData.append('linea', '1');
        formData.append('hierarchy', formValue.hierarchyControl);
  
        if(formValue.hierarchyControl == 'Hijo'){
          let parentArr = formValue.fatherControl.split(' - ');
          let parentEnc = await this._encService.encrypt(parentArr[0]);

          formData.append('parent_equipment', parentEnc);
        }
  
        let originLocation = formValue.originLocationControl.replace('-enc', '');
        let originLevel = formValue.originLevelControl.replace('-enc', '');
        let originOccupation = formValue.originOccupationControl.replace('-enc', '');
        let family = formValue.familyControl.replace('-enc', '');
        let subfamily = formValue.subfamilyControl.replace('-enc', '');
        let status = formValue.statusControl.replace('-enc', '');
  
        formData.append('code_type', formValue.codeTypeControl);
        formData.append('origin_location', originLocation);
        formData.append('origin_level', originLevel);
        formData.append('origin_occupation', originOccupation);
        formData.append('origin_element', formValue.originElementControl);
        formData.append('family', family);
        formData.append('subfamily', subfamily);
        formData.append('status', status);
        formData.append('equipment_type', formValue.equipmentTypeControl);
        formData.append('equipment_model', formValue.equipmentModelControl);


        let warehouseID = formValue.warehouseIDControl.replace('-enc', '');;
        let areaID = formValue.areaIDControl.replace('-enc', '');;
        let levelID = formValue.levelIDControl.replace('-enc', '');;
        let zoneID = formValue.zoneIDControl.replace('-enc', '');;

        formData.append('warehouse', warehouseID);
        formData.append('area', areaID);
        formData.append('level', levelID);
        formData.append('zone', zoneID);
        formData.append('number_items', this.numberItems.toString());
        formData.append('id_description', this.artitleByAdquisicion.ID_INFORMACION.toString());
        
  
        let imagesArr = JSON.stringify(this.attachedImages);
        let documentsArr = JSON.stringify(this.attachedDocuments);
        let equipmentCodeEnc = await this._encService.encrypt(this.generatedTag);
        
        let serialNumberEnc = '';
        if (formValue.serialNumberControl !== '' && formValue.serialNumberControl !== null && formValue.serialNumberControl !== undefined) {
          serialNumberEnc = await this._encService.encrypt(formValue.serialNumberControl);
        }
  
        formData.append('images', imagesArr);
        formData.append('documents', documentsArr);
  
        let acquisitionDateObj: Date = new Date(formValue.acquisitionDateControl);
        let acquisitionDateStr = `${acquisitionDateObj.getFullYear()}-${acquisitionDateObj.getMonth() + 1}-${acquisitionDateObj.getDate()}`;
        
        let warrantyStartDateObj: Date = new Date(formValue.warrantyStartDateControl);
        let warrantyStartDateStr = `${warrantyStartDateObj.getFullYear()}-${warrantyStartDateObj.getMonth() + 1}-${warrantyStartDateObj.getDate()}`;
        
        let warrantyEndDateObj: Date = new Date(formValue.warrantyEndDateControl);
        let warrantyEndDateStr = `${warrantyEndDateObj.getFullYear()}-${warrantyEndDateObj.getMonth() + 1}-${warrantyEndDateObj.getDate()}`;
        
        formData.append('acquisition_date', acquisitionDateStr);
        formData.append('warranty_start_date', warrantyStartDateStr);
        formData.append('warranty_end_date', warrantyEndDateStr);

        let providerArr = formValue.equipmentProviderControl.split(')');
        let providerStr = providerArr[0].replace('(', '');
        let providerEnc = await this._encService.encrypt(providerStr);
        
        formData.append('equipment_provider', providerEnc);
        formData.append('serial_number', serialNumberEnc);
        formData.append('has_software', formValue.hasSoftwareControl);
  
        if(formValue.hasSoftwareControl == 'Si'){
          formData.append('software_name', formValue.softwareNameControl);
          formData.append('software_version', formValue.softwareVersionControl);
        }
  
        formData.append('pre_generated_code', equipmentCodeEnc);

        let isExit = false;
        let arrCodification: Array<string> = [];
        await lastValueFrom(this._equipmentManagementService.equipmentPreCodificationStock(formData)).then(
          (responseData: ResponseData) => {
            if (!responseData.error) {
              this.resourcesService.openSnackBar('El registro del equipamiento fue enviado para su revisión correctamente.');
              arrCodification = responseData.response;
              isExit = true;
            } else {
              this.resourcesService.openSnackBar(`${responseData.msg}`);
            }
          }, async (httpErrorResponse: HttpErrorResponse) => {
            let response = this.resourcesService.checkErrors(httpErrorResponse)
            if (response !== null && response.reload) {
              await this.saveEquipment();
            }
          }
        );


        if (this.isFromAdquisition && isExit) {
          const requestForm: RegisterToStock = {
            WAREHOUSE: warehouseID,
            AREA: areaID,
            LEVEL: levelID,
            ZONE: zoneID,
            ORDER: this.orderNumber,
            PRE_CODIFICATE: arrCodification,
            ID_INFORMATION: this.idInformation,
            NUMBER_ITEMS: this.numberItems,
            FAMILIA: family,
            SUBFAMILIA: subfamily,
            MODELO: formValue.equipmentTypeControl,
            CODIGO_MODELO: formValue.equipmentModelControl,
            CODIGO_BARRAS: this.formGroup.controls['barcodeControl'].value,
            FECHA_VENCIMIENTO: this.formGroup.controls['dueDateControl'].value,
            IMAGES: imagesArr,
            PRE_GENERATED_CODE: equipmentCodeEnc,
            REPARABLE: this.formGroup.controls['repairableControl'].value,
            CONSUMIBLE: this.formGroup.controls['consumableControl'].value,
            USUARIO: this.resourcesService.getUser(),
            NUMERO_LINEA: this.resourcesService.getLineNumber(),
          }

          await lastValueFrom(this._inventoryManagementService.registerToStock(requestForm)).then(
            (responseData: ResponseData) => {
              if (!responseData.error) {
                this.resourcesService.openSnackBarAfter(`El registro del equipamiento en el stock fue registrado correctamente.`);
                this.goBack(1);
              } else {
                this.resourcesService.openSnackBar(`${responseData.msg}`);
              }
            }, async (httpErrorResponse: HttpErrorResponse) => {
              let response = this.resourcesService.checkErrors(httpErrorResponse)
              if (response !== null && response.reload) {
                await this.saveEquipment();
              }
            }
          )
        } else if ( isExit) {
          this.goBack(1);
        }

      }
    }catch(error: any){      
      if(error.error == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  openCarDialog(){
    let dialogRef = this._dialog.open(LocateCarComponent, {
      width: '945px',
      maxWidth: '945px',
      disableClose: true,
      data: {
        trainOccupations: this.trainOccupations,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != undefined && res != null && res != ''){
        let resArr = res.split('(').reverse();
        let car = resArr[0].replace(')', '');

        this.formGroup.controls['trainAreaControl'].setValue(null);
        this.formGroup.controls['originOccupationControl'].setValue(car);
        this.buildPreviewTag('originOccupationControl', car);
        this.searchCarAreas(car);
      }
    })
  }

  async searchCarAreas(trainOccupation: string){
    try{
      this.searchingCarAreas = true;

      let idUser =localStorage.getItem('idusuario')!;
      let trainOccupationEnc = await this._encService.encrypt(trainOccupation);
      let carAreas: CarAreasListResponse = await lastValueFrom(this._equipmentManagementService.occupationTrainAreaConsult(
        trainOccupationEnc,
        idUser,
        1
      ));

      if(carAreas.error){
        this.resourcesService.openSnackBar(carAreas.msg);
      }else{
        let carAreasArr: CarAreasListItem[] = [];
        for(const area of carAreas.response){
          let codeDec = await this._encService.decrypt(area.CODE);
          let areaDec = await this._encService.decrypt(area.AREA);

          area.AREA = `${areaDec} (${codeDec})`;
          carAreasArr.push(area);
        }

        this.carAreas = carAreasArr;
      }

      this.searchingCarAreas = false;
    }catch(error: any){
      if(error.error == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.resourcesService.openSnackBar(error.error.msg);
      }

      this.searchingCarAreas = false;
    }
  }
}

export interface GetDataRegisterArtitle {
  order?: string;
  info?: number;
  cantidad?: number;
  id?: string;
  action: 'new' | 'edit';
}
