import { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { CorrectiveWorkOrderDetails, CorrectiveWorkOrderDetailsResponse, SecurityManagementListItem, SecurityManagementListResponse } from '../../../../interfaces/corrective-maintenance.interface';
import { PriorityInterface } from '../../../system-admin/system-params/system-params.component';
import { EquipmentDetails, EquipmentDetailsResponse, EquipmentsListItem, EquipmentsListResponse } from '../../../../interfaces/equipment-management.interface';
import { EmployeesListItem, EmployeesListResponse } from '../../../../interfaces/personal-managment/employee.interface';
import { SubcontratistItem, SubcontratistsResponse } from '../../../../interfaces/personal-managment/subcontratists.interface';
import { TempFileInfo } from '../../../../interfaces/temp-file-info.interface';
import { CounterLastMeasureDetailsResponse, CounterLastMeasuresListItem, CountersByEquipmentListItem, CountersByEquipmentListResponse } from '../../../../interfaces/counters-activators.interface';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatTableDataSource } from '@angular/material/table';
import { debounceTime, distinctUntilChanged, filter, lastValueFrom, map, Observable, startWith, switchMap, tap } from 'rxjs';
import { DOCUMENT } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { ResourcesService } from '../../../../services/resources.service';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { EncService } from '../../../../services/enc.service';
import { EquipmentManagementService } from '../../../../services/equipment-management.service';
import { EmployeeService } from '../../../../services/personal-management/employee.service';
import { SubcontratistService } from '../../../../services/personal-management/subcontratist.service';
import { WorkTeamService } from '../../../../services/personal-management/work-team.service';
import { MatDialog } from '@angular/material/dialog';
import { GdelService } from '../../../../services/gdel.service';
import { CountersActivatorsService } from '../../../../services/counters-activators.service';
import { FunctionsService } from '../../../../services/functions.service';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { CounterDetailsComponent } from '../../../counters-activators/counters-management/counter-details/counter-details.component';
import { MeasuresHistoryComponent } from './measures-history/measures-history.component';
import { MeasuresGraphComponent } from './measures-graph/measures-graph.component';
import { SpecificValueComponent } from '../../../resources/dialogs/specific-value/specific-value.component';
import { SearchFileDialogComponent } from '../../../gdel/search-file-dialog/search-file-dialog.component';
import { FindedFile } from '../../../../interfaces/finded-files.interface';
import { availableFiles } from '../../../../../environments/environment.prod';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { GraphicEquipmentSearchComponent } from '../../../equipment-management/graphic-equipment-search/graphic-equipment-search.component';
import { EquipmentDetailsDialogComponent } from '../../../equipment-management/new-equipment/equipment-details-dialog/equipment-details-dialog.component';
import { EquipmentDocumentsComponent } from '../../../equipment-management/equipment-documents/equipment-documents.component';
import { SpecialtiesListItem, SpecialtiesListResponse } from '../../../../interfaces/specialties.interface';
import { InterventionService } from '../../../../services/personal-management/intervention.service';
import { ResponseDataGetToolsAndSpare, ToolsAndSpare } from '../../../../interfaces/inventory-management/tools-and-spare.interface';
import { InventoryManagementService } from '../../../../services/inventory-management/inventory-management.service';

@Component({
    selector: 'app-corrective-order-form',
    templateUrl: './corrective-order-form.component.html',
    styleUrl: './corrective-order-form.component.css',
    standalone: false
})
export class CorrectiveOrderFormComponent implements OnInit {
  action: string;
  isNew: boolean;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  deleteFilesDisabled: boolean;
  screenSize: number;
  loadingCounters: boolean;
  loadingMeasures: boolean;
  savingWorkOrder: boolean;
  correctiveWorkOrder: CorrectiveWorkOrderDetails | null;
  searchingEquipments: boolean;
  
  orderPriorities: PriorityInterface[];
  equipments: EquipmentsListItem[];
  subcontratists: SubcontratistItem[];
  attached: TempFileInfo[];
  equipmentCounters: CountersByEquipmentListItem[];
  tools: ToolsAndSpare[];
  spareParts: ToolsAndSpare[];
  classifications: string[];
  responsibleUsers: any[];
  securityManagements: SecurityManagementListItem[];
  specialties: SpecialtiesListItem[];
  toolsParts: ToolsAndSpare[];

  toolsConf: any;
  partsConf: any;

  autoCompleteEquipments: string[];

  orderFormGroup: FormGroup;
  symptomsDataSource: MatTableDataSource<CounterLastMeasuresListItem>;
  symptomsDisplayedColumns = ['ID', 'VALOR', 'WEBSERVICE', 'FECREG', 'ACCIONES'];
  dataSource: MatTableDataSource<EquipmentDetails>;
  displayedColumns = ['EQUIPO', 'ACCIONES'];
  specialtiesDataSource: MatTableDataSource<SpecialtiesListItem>;
  specialtiesDisplayedColumns = ['ITEM', 'CANTREQ'];
  toolsDataSource?: MatTableDataSource<ToolsAndSpare>;
  toolsDisplayedColumns = ['ITEM', 'TIPO', 'CANTDISP', 'CANTNEC', 'CANTRES'];

  @ViewChild('file') private uploader?: ElementRef;
  filteredClassifications?: Observable<string[]>;

  responsibleAtentionUserEnabled: boolean;
  workTypesClassificationEnabled: boolean;
  failDateTimeCaptureEnabled: boolean;
  materialReservationEnabled: boolean;
  securityManagementEnabled: boolean;

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _activatedRoute: ActivatedRoute,
    private _resourcesService: ResourcesService,
    private _sysAdminService: SystemAdminService,
    private _encService: EncService,
    private _equipmentsService: EquipmentManagementService,
    private _subcontratistService: SubcontratistService,
    private _dialog: MatDialog,
    private _gdelService: GdelService,
    private _countersActivatorsService: CountersActivatorsService,
    private _functionsService: FunctionsService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _router: Router,
    private _interventionService: InterventionService,
    private _inventoryManagementService: InventoryManagementService,
  ) {
    this.action = '';
    this.isNew = true;
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.deleteFilesDisabled = false;
    this.screenSize = window.innerWidth;
    this.loadingCounters = false;
    this.loadingMeasures = false;
    this.savingWorkOrder = false;
    this.correctiveWorkOrder = null;
    this.searchingEquipments = false;

    this.orderPriorities = [];
    this.equipments = [];
    this.subcontratists = [];
    this.attached = [];
    this.equipmentCounters = [];
    this.tools = [];
    this.spareParts = [];
    this.classifications = [];
    this.responsibleUsers = [];
    this.securityManagements = [];
    this.autoCompleteEquipments = [];
    this.specialties = [];
    this.toolsParts = [];
    
    this.toolsConf = {};
    this.partsConf = {};

    this.orderFormGroup = new FormGroup({
      idOrderControl: new FormControl({value: '', disabled: true}),
      responsibleUserControl: new FormControl('', Validators.required),
      securityManagementControl: new FormControl('', Validators.required),
      interventionDescriptionControl: new FormControl('', [Validators.required, Validators.minLength(15)]),
      equipmentControl: new FormControl('', Validators.required),
      failStartDateControl: new FormControl({value: new Date(), disabled: true}, Validators.required),
      solutionTimeControl: new FormControl('', Validators.required),
      priorityControl: new FormControl({value: '', disabled: true}, Validators.required),
      counterControl: new FormControl({value: '', disabled: true}, Validators.required),
      clasificationControl: new FormControl('', [Validators.required, Validators.maxLength(50)]),
      toolsControl: new FormControl([], Validators.required),
      sparePartsControl: new FormControl([], Validators.required),
      personalControl: new FormControl([], Validators.required),
      activationType: new FormControl({value: 'Manual', disabled: true}, Validators.required),
    });

    this.symptomsDataSource = new MatTableDataSource();
    this.dataSource = new MatTableDataSource();
    this.specialtiesDataSource = new MatTableDataSource();
    this.toolsDataSource = new MatTableDataSource();

    this.responsibleAtentionUserEnabled = true;
    this.workTypesClassificationEnabled = true;
    this.failDateTimeCaptureEnabled = true;
    this.materialReservationEnabled = true;
    this.securityManagementEnabled = true;
  }

  ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe(params => {
      let route = window.location.href;
      let actionArr = route.split('/').reverse()[0].split('?');
      let action = actionArr[0];

      let idOrderEnc = params['idOrder'];
      if(idOrderEnc == null || idOrderEnc == undefined || idOrderEnc == ''){
        this._resourcesService.openSnackBar('No se recibieron parametros.');
        this.goBack(1);
      }else if(action == 'nuevo'){
        this.isNew = true;
        this.action = 'Registrar';
        this.getOrderPriorities();
      }else if(action == 'editar'){
        this.isNew = false;
        this.action = 'Editar';
        this.getWorkOrder(idOrderEnc);
      }
    });

    this.filteredClassifications = this.orderFormGroup.controls['clasificationControl'].valueChanges.pipe(
      startWith(''),
      map(value => this._filterClassifications(value || '')),
    );
    
    this.orderFormGroup.controls['equipmentControl'].valueChanges.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      filter(value => value ? true : false),
      tap(() => this.searchingEquipments = true),
      switchMap(value => this._filterEquipments(value))
    ).subscribe(autoCompleteList => {
      this.autoCompleteEquipments = autoCompleteList;
    });
  }

  async changeEquipmentTable(equipmentCode: string){
    try{
      let equipmentArr = equipmentCode.split(' - ');
      if(equipmentArr.length == 3){
        let idUser = localStorage.getItem('idusuario')!;
        let equipmentCodeEnc = await this._encService.encrypt(equipmentArr[0]);
        let equipment: EquipmentDetailsResponse = await lastValueFrom(this._equipmentsService.equipmentConsultOnly(equipmentCodeEnc, idUser, 1));

        if(equipment.error){
          this._resourcesService.openSnackBar(equipment.msg);
        }else{
          let codeDec = await this._encService.decrypt(equipment.response.CODIGO);
          let equipmentTypeDec = await this._encService.decrypt(equipment.response.TIPO_EQUIPAMIENTO);
          equipment.response.TIPO_EQUIPAMIENTO = `${codeDec} - ${equipmentTypeDec}`;

          let modelDec = await this._encService.decrypt(equipment.response.MODELO);
          let idDec = await this._encService.decrypt(equipment.response.ID_EQUIPAMIENTO);
          equipment.response.MODELO = `${modelDec} (${idDec})`;
      
          this.dataSource = new MatTableDataSource([equipment.response]);
          this.equipmentChange(equipmentCodeEnc)
        }
      }
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_001: Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_002: Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(`ERR_GEOP_NUEV_003: ${error.error.msg}`);
      }
    }
  }

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

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.orderFormGroup.controls['equipmentControl'].setValue(res);
        this.changeEquipmentTable(res);
      }
    });
  }

  private async _filterEquipments(value: string): Promise<string[]>{
    let equipmentsStr: string[] = [];
    let idUser = localStorage.getItem('idusuario')!;
    let equipments: EquipmentsListResponse = await lastValueFrom(this._equipmentsService.equipmentConsultFiltered(value, idUser, 1));

    if(equipments.error){
      this._resourcesService.openSnackBar(equipments.msg);
    }else{
      for(const equipment of equipments.response){
        let codeDec = await this._encService.decrypt(equipment.CODIGO);
        let idDec = await this._encService.decrypt(equipment.ID_EQUIPO);

        equipmentsStr.push(`${codeDec} - ${equipment.TIPO} - ${equipment.MODELO} (${idDec})`);
      }
    }

    this.searchingEquipments = false;
    return equipmentsStr;
  }

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

  async openEquipmentDetails(equipmentCode: string){
    this._dialog.open(EquipmentDetailsDialogComponent, {
      width: '840px',
      maxWidth: '840px',
      data: {
        code: equipmentCode,
      }
    });
  }

  async openEquipmentArborescence(selectedEquipment: string){
    let codeDec = await this._encService.decrypt(selectedEquipment);
    let codeArr = codeDec.split('_');

    if(codeArr.length == 2){
      let pbsArr = codeArr[1].split('.');
      if(pbsArr.length > 3){
        let familyEnc = await this._encService.encrypt(pbsArr[0]);
        let subFamilyEnc = await this._encService.encrypt(pbsArr[1]);
        let arborescence: string[] = [];

        for(let i = 3; i < pbsArr.length; i++){
          let equipmentCode = pbsArr[i];
          let parentIndex = i - 4;

          if(parentIndex >= 0){
            let parent = arborescence[parentIndex];
            let fullCode = `${parent}.${equipmentCode}`;
            arborescence.push(fullCode);
          }else{
            let fullCode = `${codeArr[0]}_${pbsArr[0]}.${pbsArr[1]}.${pbsArr[2]}.${equipmentCode}`;
            arborescence.push(fullCode);
          }
        }

        let arborescenceArr: string[] = [];
        for(const item of arborescence){
          let itemEnc = await this._encService.encrypt(item);
          arborescenceArr.push(itemEnc);
        }

        let arborescenceStr = JSON.stringify(arborescenceArr);
        let arborescenceEnc = window.btoa(arborescenceStr);

        let url = this._router.createUrlTree(['sam/GEEQ'], {
          queryParams: {
            family: familyEnc,
            subfamily: subFamilyEnc,
            arborescence: arborescenceEnc
          }
        });

        if(window.location.href.includes('#')){
          let locationArr = window.location.href.split('#');
          window.open(`${locationArr[0]}#${url.toString()}`);
        }
      }
    }
  }

  async openEquipmentDocuments(equipmentCode: string){
    try{
      this._resourcesService.openSnackBar('Obteniendo lista de documentos...');

      let idUser = localStorage.getItem('idusuario')!;
      let equipment: EquipmentDetailsResponse = await lastValueFrom(this._equipmentsService.equipmentConsultOnly(equipmentCode, idUser, 1));

      if(equipment.error){
        this._resourcesService.openSnackBar(equipment.msg);
      }else{
        equipment.response.CODIGO = await this._encService.decrypt(equipment.response.CODIGO);
        equipment.response.TIPO_EQUIPAMIENTO = await this._encService.decrypt(equipment.response.TIPO_EQUIPAMIENTO);
        equipment.response.MODELO = await this._encService.decrypt(equipment.response.MODELO);
        equipment.response.ID_EQUIPAMIENTO = await this._encService.decrypt(equipment.response.ID_EQUIPAMIENTO);

        this._dialog.open(EquipmentDocumentsComponent, {
          width: '520px',
          maxWidth: '520px',
          data: {
            equipment: `${equipment.response.CODIGO} - ${equipment.response.TIPO_EQUIPAMIENTO} - ${equipment.response.MODELO} (${equipment.response.ID_EQUIPAMIENTO})`,
            documents: JSON.parse(equipment.response.DOCUMENTOS as string)
          }
        });
      }
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_004: Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_005: Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(`ERR_GEOP_NUEV_006: ${error.error.msg}`);
      }
    }
  }

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

  async getWorkOrder(idOrder: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let order: CorrectiveWorkOrderDetailsResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrder(idOrder, idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let idOrderDec = await this._encService.decrypt(order.response.ID_ORDEN);
        order.response.ID_ORDEN = idOrderDec;
        this.orderFormGroup.controls['idOrderControl'].setValue(idOrderDec);
        this.orderFormGroup.controls['interventionDescriptionControl'].setValue(order.response.DESCRIPCION);

        let startDate = new Date(order.response.FECHA_INICIO);
        this.orderFormGroup.controls['failStartDateControl'].setValue(startDate);
        this.orderFormGroup.controls['solutionTimeControl'].setValue(order.response.TIEMPO_ESTIMADO);
        this.orderFormGroup.controls['clasificationControl'].setValue(order.response.CLASIFICACION);

        if(order.response.ID_EQUIPAMIENTO != null){
          let equipmentCodeDec = await this._encService.decrypt(order.response.CODIGO_EQUIPAMIENTO);
          let equipmentIDDEc = await this._encService.decrypt(order.response.ID_EQUIPAMIENTO);
          let equipmentStr = `${equipmentCodeDec} - ${order.response.TIPO_EQUIPAMIENTO} - ${order.response.MODELO_EQUIPAMIENTO} (${equipmentIDDEc})`;

          this.orderFormGroup.controls['equipmentControl'].setValue(equipmentStr);
          this.changeEquipmentTable(equipmentStr);
        }
        
        this.attached = JSON.parse(order.response.DOCUMENTOS_RELACIONADOS);
        this.correctiveWorkOrder = order.response;
        this.getOrderPriorities();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_007: Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_008: Ocurrió un error inesperado.';
      }else{
        this.errorStr = `ERR_GEOP_NUEV_009: ${error.error.msg}`;
      }

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

  async getOrderPriorities(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._sysAdminService.getOrderPriorities(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let prioritiesArr: PriorityInterface[] = [];
        for(const priority of priorities.response.order_priorities){
          let valEnc = await this._encService.encrypt(priority.value);
          let valDec = priority.value;
          priority.label = `${priority.label} (${priority.value})`;
          priority.value = valEnc;

          prioritiesArr.push(priority);
          if(this.correctiveWorkOrder != null){
            let priority = await this._encService.decrypt(this.correctiveWorkOrder.PRIORIDAD);
            if(priority == valDec){
              this.orderFormGroup.controls['priorityControl'].setValue(valEnc);
            }
          }
        }

        this.orderPriorities = prioritiesArr;
        this.getOrderClasifications();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_010: Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_011: Ocurrió un error inesperado.';
      }else{
        this.errorStr = `ERR_GEOP_NUEV_012: ${error.error.msg}`;
      }

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

  async getOrderClasifications(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let clasifications = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrderClasifications(idUser, 1));

      this.hasError = clasifications.error;
      this.errorStr = clasifications.msg;
      
      if(this.hasError){
        this.isLoading = false;
      }else{
        for(const classificationObj of clasifications.response){
          this.classifications.push(classificationObj.CLASIFICACION);
        }

        this.getResponsibleUsers();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_013: Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_014: Ocurrió un error inesperado.';
      }else{
        this.errorStr = `ERR_GEOP_NUEV_015: ${error.error.msg}`;
      }

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

  async getResponsibleUsers(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let responsibleUsers = await lastValueFrom(this._correctiveMaintenanceService.getResponsibleUsers(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let responsibleUsersArr: any[] = [];
        let idDec = await this._encService.decrypt(idUser);

        for(const user of responsibleUsers.response){
          let idUserDec = await this._encService.decrypt(user.ID);
          user.NOMBRE = `${user.NOMBRE} (${idUserDec})`;

          if(this.correctiveWorkOrder != null){
            let idResponsibleArr = this.correctiveWorkOrder.ID_RESPONSABLE.split('(').reverse();
            let idResponsibleStr = idResponsibleArr[0].replace(')', '');

            if(this.correctiveWorkOrder.TIPO_RESPONSABLE == 'Usuario' && idUserDec == idResponsibleStr){
              this.orderFormGroup.controls['responsibleUserControl'].setValue(`${user.ID}|user`);
            }
          }

          if(idDec != idUserDec){
            responsibleUsersArr.push(user);
          }
        }

        this.responsibleUsers = responsibleUsersArr;
        this.getSecurityManagements();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_016: Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_017: Ocurrió un error inesperado.';
      }else{
        this.errorStr = `ERR_GEOP_NUEV_018: ${error.error.msg}`;
      }

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

  async getSecurityManagements(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let securityManagements: SecurityManagementListResponse = await lastValueFrom(this._correctiveMaintenanceService.getSecurityManagements(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let securityManagementsArr: SecurityManagementListItem[] = [];
        for(const management of securityManagements.response){
          let idManagementDec = await this._encService.decrypt(management.ID_GERENCIA_SEGURIDAD);
          if(this.correctiveWorkOrder != null){
            let securityManagementDec = await this._encService.decrypt(this.correctiveWorkOrder.GERENCIA_SEGURIDAD);
            if(securityManagementDec == idManagementDec){
              this.orderFormGroup.controls['securityManagementControl'].setValue(idManagementDec);
            }
          }
          
          management.ID_GERENCIA_SEGURIDAD = idManagementDec;
          if(management.ESTADO == 'Activo'){
            securityManagementsArr.push(management);
          }
        }

        this.securityManagements = securityManagementsArr;
        this.getSubcontratists();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_019: Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_020: Ocurrió un error inesperado.';
      }else{
        this.errorStr = `ERR_GEOP_NUEV_021: ${error.error.msg}`;
      }

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

  async equipmentChange(equipment: string){
    try{
      this.loadingCounters = true;
      this.orderFormGroup.controls['counterControl'].disable();
      this.orderFormGroup.controls['counterControl'].setValue(null);

      let idUser = localStorage.getItem('idusuario')!;
      let counters: CountersByEquipmentListResponse = await lastValueFrom(this._countersActivatorsService.counterConsultByEquipment(
        equipment, 
        idUser, 
        1
      ));

      if(counters.error){
        this._resourcesService.openSnackBar(counters.msg);
      }else{
        let countersArr: CountersByEquipmentListItem[] = [];
        for(const counter of counters.response){
          let idDec = await this._encService.decrypt(counter.ID_CONTADOR);
          counter.ID_CONTADOR = idDec;

          if(counter.ESTADO == 'Activo' && counter.ID_ACTIVADOR != null){
            countersArr.push(counter);
            if(this.correctiveWorkOrder != null && this.isLoading){
              let counterDec = await this._encService.decrypt(this.correctiveWorkOrder.CONTADOR);
              if(counterDec == idDec){
                this.orderFormGroup.controls['counterControl'].setValue(counterDec);
                let measureObj = JSON.parse(this.correctiveWorkOrder.MEDIDAS);
                let idSWDec = await this._encService.decrypt(measureObj.ID_SERVICIO_WEB)
                let measure: CounterLastMeasuresListItem = {
                  ID_MEDIDA: await this._encService.decrypt(measureObj.ID_MEDIDA),
                  CONTADOR: measureObj.CONTADOR,
                  VALOR: measureObj.VALOR,
                  ID_SERVICIO_WEB: measureObj.ID_SERVICIO_WEB,
                  URL_SERVICIO_WEB: `${measureObj.URL_SERVICIO_WEB} (${idSWDec})`,
                  HORA_REGISTRO: this._functionsService.orderDate(measureObj.HORA_REGISTRO)!
                };
                
                this.symptomsDataSource = new MatTableDataSource([measure]);
              }
            }
          }
        }

        this.equipmentCounters = countersArr;
        if(this.equipmentCounters.length > 0){
          this.orderFormGroup.controls['counterControl'].enable();
        }
      }

      this.loadingCounters = false;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_025: Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_026: Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(`ERR_GEOP_NUEV_027: ${error.error.msg}`);
      }

      this.loadingCounters = false;
    }
  }

  async getSubcontratists(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let subcontratists: SubcontratistsResponse = await lastValueFrom(this._subcontratistService.getConsultOfSubcontratists(idUser, 1));

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

      if(this.hasError){
        this.isLoading = true;
      }else{
        let subcontratistsArr: SubcontratistItem[] = [];
        for(const subcontratist of subcontratists.response){
          let idDec = await this._encService.decrypt(subcontratist.ID_SUBCONTRATIST);

          if(this.correctiveWorkOrder != null){
            let idResponsibleArr = this.correctiveWorkOrder.ID_RESPONSABLE.split('(').reverse();
            let idResponsibleStr = idResponsibleArr[0].replace(')', '');

            if(this.correctiveWorkOrder.TIPO_RESPONSABLE == 'Subcontratista' && idDec == idResponsibleStr){
              this.orderFormGroup.controls['responsibleUserControl'].setValue(`${subcontratist.ID_SUBCONTRATIST}|subcontratist`);
            }
          }

          subcontratist.NAME = `${subcontratist.NAME} (${idDec})`;
          if(subcontratist.STATUS == 'Activo'){
            subcontratistsArr.push(subcontratist);
          }
        }

        this.subcontratists = subcontratistsArr;
        this.getSpecialties();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_031: Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_032: Ocurrió un error inesperado.';
      }else{
        this.errorStr = `ERR_GEOP_NUEV_033: ${error.error.msg}`;
      }

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

  async getSpecialties(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let specialties: SpecialtiesListResponse = await lastValueFrom(this._interventionService.getSpecialties(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let specialtiesSelected: string[] = [];
        if(this.correctiveWorkOrder != null){
          let staffArr: any[] = JSON.parse(this.correctiveWorkOrder.PERSONAL);
          for(const item of staffArr){
            let idDec = await this._encService.decrypt(item.ID);
            specialtiesSelected.push(idDec);
          }
        }

        let specialtiesArr: SpecialtiesListItem[] = [];
        for(const specialty of specialties.response){
          let codeDec = await this._encService.decrypt(specialty.CODIGO_ESPECIALIDAD);
          specialty.NOMBRE_ESPECIALIDAD = `${specialty.NOMBRE_ESPECIALIDAD} (${codeDec})`;
          
          if(specialty.ESTADO == 'Activo'){
            specialtiesArr.push(specialty);

            let specialtiesVal = this.orderFormGroup.controls['personalControl'].value;
            if(specialtiesSelected.includes(codeDec)){
              specialtiesVal.push(specialty.CODIGO_ESPECIALIDAD);
            }
          }
        }

        this.specialties = specialtiesArr;
        this._getToolsAndSpare();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_037: Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'ERR_GEOP_NUEV_038: Ocurrió un error inesperado.';
      }else{
        this.errorStr = `ERR_GEOP_NUEV_039: ${error.error.msg}`;
      }

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

  private async _getToolsAndSpare () {
    try{
      const USER: string = this._resourcesService.getUser();
      const LINE: number = this._resourcesService.getLineNumber();

      let responseData: ResponseDataGetToolsAndSpare = await lastValueFrom(this._inventoryManagementService.getToolsAndSpare(USER, LINE));

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

      if(!this.hasError){
        let selectedResources: any[] = [];
        if(this.correctiveWorkOrder != null){
          let resourcesArr = JSON.parse(this.correctiveWorkOrder.RECURSOS);
          for(const item of resourcesArr){
            if(item.ID != 'SH'){
              let idDec = await this._encService.decrypt(item.ID);
              selectedResources.push({ID: idDec, TYPE: item.TYPE, REQ: item.REQ});
            }else{
              if(item.TYPE == 'S'){
                let partsVal = this.orderFormGroup.controls['sparePartsControl'].value;
                partsVal.push('SH');

                this.orderFormGroup.controls['sparePartsControl'].setValue(partsVal);
              }else{
                let toolsVal = this.orderFormGroup.controls['toolsControl'].value;
                toolsVal.push('SH');
    
                this.orderFormGroup.controls['toolsControl'].setValue(toolsVal);
              }
            }
          }
        }

        let toolsArr: ToolsAndSpare[] = [];
        for(const tool of responseData.response.HERRAMIENTAS){
          let idToolDec = await this._encService.decrypt(tool.ID);
          let selectedFilter = selectedResources.filter(item => item.ID == idToolDec && item.TYPE == 'T');

          if(selectedFilter.length > 0){
            let toolsVal = this.orderFormGroup.controls['toolsControl'].value;
            toolsVal.push(tool.ID);

            this.orderFormGroup.controls['toolsControl'].setValue(toolsVal);
            this.toolsConf[tool.ID] = selectedFilter[0].REQ;
          }

          toolsArr.push(tool);
        }

        let sparePartsArr: ToolsAndSpare[] = [];
        for(const part of responseData.response.REFACCIONES){
          let idPartDec = await this._encService.decrypt(part.ID);
          let selectedFilter = selectedResources.filter(item => item.ID == idPartDec && item.TYPE == 'S');

          if(selectedFilter.length > 0){
            let partsVal = this.orderFormGroup.controls['sparePartsControl'].value;
            partsVal.push(part.ID);

            this.orderFormGroup.controls['sparePartsControl'].setValue(partsVal);
            this.partsConf[part.ID] = selectedFilter[0].REQ;
          }

          sparePartsArr.push(part);
        }

        this.tools = toolsArr;
        this.spareParts = sparePartsArr;
      }

      this.isLoading = false;
      this.initTables();
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (9).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (10).';
      }else{
        this.errorStr = error.error.msg;
      }
      
      this.hasError = true;
      this.isLoading = false;
    }
  }

  initTables(){
    setTimeout(() => {
      let specialties = this.orderFormGroup.controls['personalControl'].value;
      this.updateSpecialty(specialties);
      setTimeout(async () => {
        if(this.correctiveWorkOrder != null){
          let specialtiesArr = JSON.parse(this.correctiveWorkOrder.PERSONAL);
          for(const specialty of specialtiesArr){
            specialty.ID = await this._encService.decrypt(specialty.ID);
          }

          for(const item of specialties){
            let input = this._document.getElementById(`cant-req-${item}`) as HTMLInputElement;
            let itemDec = await this._encService.decrypt(item);
            let specialtyFilt = specialtiesArr.filter((item1: any) => item1.ID == itemDec);

            if(specialtyFilt.length > 0){
              input.value = specialtyFilt[0].CANT;
            }else{
              input.value = '1';
            }
          }
        }
      }, 200);
      
      let toolsVal = this.orderFormGroup.controls['toolsControl'].value;
      let partsVal = this.orderFormGroup.controls['sparePartsControl'].value;

      this.toolsChange(toolsVal, partsVal);
      setTimeout(() => {
        let toolsKeys = Object.keys(this.toolsConf);
        for(const key of toolsKeys){
          if(key != 'SH'){
            let input = this._document.getElementById(`cant-req-${key}`) as HTMLInputElement;
            input.value = this.toolsConf[key];
          }
        }

        let partsKeys = Object.keys(this.partsConf);
        for(const key of partsKeys){
          if(key != 'SH'){
            let input = this._document.getElementById(`cant-req-${key}`) as HTMLInputElement;
            input.value = this.partsConf[key];
          }
        }
      }, 200);
    }, 200);
  }

  isPositive(calcDisp: string, id: string): boolean{
    let input = this._document.getElementById(`cant-req-${id}`) as HTMLInputElement;
    let cd = parseInt(calcDisp);
    let cr = parseInt(input.value);
    
    return cd - cr > 0;
  }

  calcRest(calcDisp: string, id: string): string{
    let input = this._document.getElementById(`cant-req-${id}`) as HTMLInputElement;
    let cd = parseInt(calcDisp);
    let cr = parseInt(input.value);
    
    return `${cd - cr}`;
  }

  updateSpecialty(specialties: string[]){
    let specialtiesSel: SpecialtiesListItem[] = [];
    for(const idSpecialty of specialties){
      let specialtyFilt = this.specialties.filter(item => item.CODIGO_ESPECIALIDAD == idSpecialty);
      if(specialtyFilt.length > 0){
        specialtiesSel.push(specialtyFilt[0]);
      }
    }

    this.specialtiesDataSource = new MatTableDataSource(specialtiesSel);
  }

  changeReq(action: string, id: string){
    let input = this._document.getElementById(`cant-req-${id}`) as HTMLInputElement;
    let val = parseInt(input.value);
    if(action == 'add'){
      val++;
      input.value = `${val}`;
    }else if(val > 1){
      val--;
      input.value = `${val}`;
    }else{
      input.value = '1';
    }
  }

  validateCant(value: string, id: string){
    let input = this._document.getElementById(`cant-req-${id}`) as HTMLInputElement;
    if(value == ""){
      input.value = '1';
    }else if(value == '0'){
      input.value = '1';
    }else{
      let validString = "";
      let valueArr = value.split('');
      let numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

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

      input.value = validString;
    }
  }

  toolsChange(toolsValue: string[], partsValue: string[]){
    this.toolsDataSource = new MatTableDataSource();
    this.toolsParts = [];

    let toolsAux: ToolsAndSpare[] = [];
    if(toolsValue != undefined && !toolsValue.includes('SH')){
      toolsValue.forEach(item => {
        let tool = this.tools.filter(item2 => item.toString() == item2.ID.toString())[0];
        toolsAux.push(tool);
      });
    }else if(toolsValue.includes('SH')){
      this.orderFormGroup.controls['toolsControl'].setValue(['SH']);
    }

    let partsAux: ToolsAndSpare[] = [];
    if(partsValue != undefined && !partsValue.includes('SH')){
      partsValue.forEach(item => {
        let part = this.spareParts.filter(item2 => item.toString() == item2.ID.toString())[0];
        partsAux.push(part);
      });
    }else if(partsValue.includes('SH')){
      this.orderFormGroup.controls['sparePartsControl'].setValue(['SH']);
    }

    toolsAux.forEach(item => this.toolsParts.push(item));
    partsAux.forEach(item => this.toolsParts.push(item));

    this.toolsDataSource = new MatTableDataSource(this.toolsParts);
  }

  onResize():void{
    this.screenSize = window.innerWidth;
  }

  validateTime(value: string, action: string){
    let validChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let valueArr = value.split('');
    
    if(action == 'input'){
      let validInputVal = '';
      let pointConter = 0;
      for(const char of valueArr){
        if(pointConter < 1 && char == '.'){
          validInputVal += char;
          pointConter++;
        }else if(validChars.includes(char) && char != '.'){
          validInputVal += char;
        }
      }

      this.orderFormGroup.controls['solutionTimeControl'].setValue(validInputVal);
    }else if(action == 'blur'){
      let floatValue = parseFloat(value);
      if(isNaN(floatValue)){
        this.orderFormGroup.controls['solutionTimeControl'].setValue('0');
      }else{
        this.orderFormGroup.controls['solutionTimeControl'].setValue(`${floatValue}`);
      }
    }
  }

  async counterChange(value: string){
    try{
      this.symptomsDataSource = new MatTableDataSource();
      this.orderFormGroup.controls['priorityControl'].setValue(null);
      this.orderFormGroup.controls['counterControl'].disable();
      this.loadingMeasures = true;

      let counterFilt = this.equipmentCounters.filter(item => item.ID_CONTADOR == value);
      if(counterFilt.length > 0){
        for(const priority of this.orderPriorities){
          let idDec = await this._encService.decrypt(priority.value);
          if(idDec == counterFilt[0].PRIORIDAD){
            this.orderFormGroup.controls['priorityControl'].setValue(priority.value);
          }
        }
      }else{
        this.loadingMeasures = false;
        this._resourcesService.openSnackBar('El contador seleccionado es inválido.');
        return;
      }

      let idCounterEnc = await this._encService.encrypt(value);
      let idUser = localStorage.getItem('idusuario')!;
      let lastMeasure: CounterLastMeasureDetailsResponse = await lastValueFrom(this._countersActivatorsService.counterConsultLastMeasures(
        idCounterEnc, 
        idUser,
        1
      ));

      if(lastMeasure.error){
        this._resourcesService.openSnackBar(lastMeasure.msg);
      }else{
        if(lastMeasure.response.length > 0){
          let measures: CounterLastMeasuresListItem[] = [];
          let idDec = await this._encService.decrypt(lastMeasure.response[0].ID_MEDIDA);
          let idSWDec = await this._encService.decrypt(lastMeasure.response[0].ID_SERVICIO_WEB);
  
          lastMeasure.response[0].ID_MEDIDA = idDec;
          lastMeasure.response[0].URL_SERVICIO_WEB = `${lastMeasure.response[0].URL_SERVICIO_WEB} (${idSWDec})`;
          lastMeasure.response[0].HORA_REGISTRO = this._functionsService.orderDate(lastMeasure.response[0].HORA_REGISTRO)!;
  
          measures.push(lastMeasure.response[0]);
          this.symptomsDataSource = new MatTableDataSource(measures);
        }
      }

      this.loadingMeasures = false;
      this.orderFormGroup.controls['counterControl'].enable();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_040: Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_041: Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(`ERR_GEOP_NUEV_042: ${error.error.msg}`);
      }

      this.loadingMeasures = false;
      this.orderFormGroup.controls['counterControl'].enable();
    }
  }

  async counterDetails(value: string){
    if(value != null && value != undefined && value != ''){
      let counterFilt = this.equipmentCounters.filter(item => item.ID_CONTADOR == value);
      if(counterFilt.length > 0){
        let idCounterEnc = await this._encService.encrypt(value);
        this._dialog.open(CounterDetailsComponent, {
          width: '540px',
          maxWidth: '540px',
          data: {
            idCounter: idCounterEnc,
            includeActivator: true,
            idActivator: counterFilt[0].ID_ACTIVADOR,
          }
        });
      }else{
        this._resourcesService.openSnackBar('El contador seleccionado es inválido.');
      }
    }
  }

  async openMeasuresDialog(mode: string){
    let idCounter = this.orderFormGroup.controls['counterControl'].value;
    let idCounterEnc = await this._encService.encrypt(idCounter);
    
    if(mode == 'history'){
      this._dialog.open(MeasuresHistoryComponent, {
        width: '720px',
        maxWidth: '720px',
        disableClose: true,
        data: {
          idCounter: idCounterEnc,
        }
      })
    }else if(mode == 'graph'){
      this._dialog.open(MeasuresGraphComponent, {
        width: '720px',
        maxWidth: '720px',
        disableClose: true,
        data: {
          idCounter: idCounterEnc,
        }
      })
    }
  }

  changeCantReq(action: string, id: string, cantDisp: number){
    let inputReq = this._document.getElementById(`cant-req-${id}`) as HTMLInputElement;
    let inputRest = this._document.getElementById(`cant-rest-${id}`) as HTMLInputElement;
    let valueInt = parseInt(inputReq.value);
    let valueFn = 1;

    if(action == 'add'){
      let valueTmp = valueInt + 1;
      valueFn = valueTmp;
    }else if(action == 'remove'){
      let valueTmp = valueInt - 1;
      if(valueTmp < 1){
        valueFn = 1;
      }else{
        valueFn = valueTmp;
      }
    }
    
    inputReq.value = `${valueFn}`;
    inputRest.value = `${cantDisp - valueFn}`;
  }

  openSpecificRequiredNumber(id: string, cantDisp: number){
    let dialogRef = this._dialog.open(SpecificValueComponent, {
      width: '420px',
      maxWidth: '420px',
      disableClose: true,
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != undefined && res != null && res != ''){
        let inputReq = this._document.getElementById(`cant-req-${id}`) as HTMLInputElement;
        let inputRest = this._document.getElementById(`cant-rest-${id}`) as HTMLInputElement;
        let requiredParts = parseInt(res);

        if(!isNaN(requiredParts) && requiredParts > 0){
          inputReq.value = `${requiredParts}`;
          inputRest.value = `${cantDisp - requiredParts}`;
        }
      }
    });
  }

  intval(value: string): number{
    return parseInt(value);
  }

  openFileUploader(){
    this.uploader?.nativeElement.click();
  }

  searchExistingFile(){
    let existingFiles = this.attached.filter(item => item.type == 'Existente');
    
    let dialogRef = this._dialog.open(SearchFileDialogComponent, {
      width: '1024px',
      maxWidth: '1024px',
      data: {
        files: existingFiles,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ""){
        let files: FindedFile[] = JSON.parse(res);
        files.forEach(async (item) => {
          let existingFiles: TempFileInfo[] = [];
          for(const file of this.attached){
            let idDec = await this._encService.decrypt(file.id);
            let filt = files.filter(item0 => idDec == `${item0.CODIGO}=${item0.VERSION}=${item.NOMBRE}`);
            if(filt.length > 0){
              existingFiles.push(file)
            }
          }

          let idFile = `${item.CODIGO}=${item.VERSION}=${item.NOMBRE}`;
          let fileEnc = await this._encService.encrypt(idFile);
          let file: TempFileInfo = {
            id: fileEnc,
            name: item.NOMBRE,
            size: `${item.TAMANIO}`,
            type: 'Existente'
          };

          if(existingFiles.length < 1){
            this.attached.push(file);
          }
        });
      }
    });
  }

  async deleteFile(id: string, type: string){
    try{
      if(this.deleteFilesDisabled == false){
        this.deleteFilesDisabled = true;
  
        if(type == 'Nuevo'){
          let idUser = localStorage.getItem('idusuario');
  
          await lastValueFrom(this._gdelService.deleteTempFile({
            'id_user': idUser!,
            'id_file': id,
            'linea': 1,
          }));
        }
  
        let attachedAux: TempFileInfo[] = [];
        this.attached.forEach(item => {
          if(item.id != id){
            attachedAux.push(item);
          }
        });
  
        this.deleteFilesDisabled = false;
        this.attached = attachedAux;
      }
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_043: Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_044: Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(`ERR_GEOP_NUEV_045: ${error.error.msg}`);
      }
    }
  }

  checkFile(event: any){
    let fileTypes = availableFiles;
    let sizes = Object.keys(fileTypes);
    let extensions = Object.values(fileTypes);
    let maxSizeMB = 0;

    let extArr = event.target.files[0].name.split(".").reverse();
    let extStr = extArr[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.attached.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{
          this.uploadTmp(event.target.files[0]);
        }
      }
    }
  }

  async uploadTmp(fileData: any){
    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',
        };

        this.attached.push(uploadedFile);
      }
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_046: Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_047: Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(`ERR_GEOP_NUEV_048: ${error.error.msg}`);
      }
    }
  }

  processCorrectiveOrder(){
    let formValue = this.orderFormGroup.getRawValue();
    let counterLastMeasure = this.symptomsDataSource.data;
    if(this.equipmentCounters.length == 0){
      this._resourcesService.openSnackBar('El equipamiento seleccionado no tiene contadores relacionados, intente con uno distinto.');
    }else if(counterLastMeasure.length == 0){
      this._resourcesService.openSnackBar('El contador seleccionado aún no tiene medidas registradas, intente con uno distinto.');
    }else if(parseInt(formValue.solutionTimeControl) <= 0){
      this._resourcesService.openSnackBar('El tiempo de solución estimado no puede ser menor o igual a cero.');
    }else{
      if(this.attached.length == 0){
        let confirmNoAttached = this._dialog.open(AlertComponent, {
          width: '420px',
          maxWidth: '420px',
          disableClose: true,
          data: {
            title: 'Confirmación',
            icon: 'warning',
            description: 'La orden que desea registrar no tiene nungún documento adjunto.',
            description2: '¿Desea continuar?'
          }
        });

        confirmNoAttached.afterClosed().subscribe(res => {
          if(res == true){
            this.saveCorrectiveWorkOrder(formValue);
          }
        })
      }else{
        this.saveCorrectiveWorkOrder(formValue);
      }
    }
  }

  private async saveCorrectiveWorkOrder(formValue: any){
    try{
      this.savingWorkOrder = true;

      let securityManagementControlEnc = await this._encService.encrypt(formValue.securityManagementControl);
      let responsibleUserArr = formValue.responsibleUserControl.split('|');
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();
      let startDate = formValue.failStartDateControl as Date;
      let startDateTime = `${startDate.getFullYear()}-${startDate.getMonth() + 1}-${startDate.getDate()} ${startDate.getHours()}:${startDate.getMinutes()}:${startDate.getSeconds()}`;
      
      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_responsible', responsibleUserArr[0]);
      formData.append('security_management', securityManagementControlEnc);
      formData.append('type_responsible', responsibleUserArr[1].charAt(0).toUpperCase());
      formData.append('description', formValue.interventionDescriptionControl);
        
      let equipmentArr = formValue.equipmentControl.split(' - ');
      if(equipmentArr.length != 3){
        this._resourcesService.openSnackBar('El formato del equipamiento seleccionado es inválido.');
        return;
      }
        
      let equipment = await this._encService.encrypt(equipmentArr[0]);
      formData.append('equipment', equipment);
      formData.append('start_date_time', startDateTime);
      formData.append('solution_time', formValue.solutionTimeControl);
      formData.append('priority', formValue.priorityControl);

      let idCounterEnc = await this._encService.encrypt(formValue.counterControl);
      let idLastMeasureEnc = await this._encService.encrypt(this.symptomsDataSource.data[0].ID_MEDIDA);

      formData.append('id_counter', idCounterEnc);
      formData.append('id_last_measure', idLastMeasureEnc);
      formData.append('clasification', formValue.clasificationControl);

      let specialtiesArr: any[] = [];
      for(const specialty of formValue.personalControl){
        let specialtyFilt = this.specialties.filter(item => item.CODIGO_ESPECIALIDAD == specialty);
        if(specialtyFilt.length > 0){
          let input = this._document.getElementById(`cant-req-${specialty}`) as HTMLInputElement;
          if(input == null){
            this._resourcesService.openSnackBar(`No se pudo encontrar la configuración de la especialidad ${specialtyFilt[0].NOMBRE_ESPECIALIDAD}.`);
            return;
          }

          let valStr = input.value;
          let valNum = parseInt(valStr);
          if(valNum <= 0){
            this._resourcesService.openSnackBar(`La cantidad de operarios para la especialidad ${specialtyFilt[0].NOMBRE_ESPECIALIDAD} no puede ser igual o menor a cero.`);
            return;
          }

          specialtiesArr.push({
            SPECIALTY: specialty,
            CANT: valNum,
          });
        }
      }
      
      let staffStr = JSON.stringify(specialtiesArr);
      formData.append('staff', staffStr);
      formData.append('activation_type', formValue.activationType);

      let resourcesConf: any[] = [];
      for(const tool of formValue.toolsControl){
        if(tool == 'SH'){
          resourcesConf.push({
            ID: 'SH',
            REQ: '-',
            TYPE: 'T'
          });
        }else{
          let toolFilt = this.tools.filter(item => item.ID == tool);
          if(toolFilt.length > 0){
            let input = this._document.getElementById(`cant-req-${tool}`) as HTMLInputElement;
            if(input == null){
              this._resourcesService.openSnackBar(`No se pudo encontrar la configuración de la herramienta ${toolFilt[0].NOMB}.`);
              return;
            }

            let valStr = input.value;
            let valNum = parseInt(valStr);
            if(valNum <= 0){
              this._resourcesService.openSnackBar(`La cantidad configurada para la herramienta ${toolFilt[0].NOMB} no puede ser igual o menor a cero.`);
              return;
            }

            resourcesConf.push({
              ID: tool,
              REQ: valNum,
              TYPE: 'T'
            });
          }
        }
      }

      for(const sparePart of formValue.sparePartsControl){
        if(sparePart == 'SH'){
          resourcesConf.push({
            ID: 'SH',
            REQ: '-',
            TYPE: 'S'
          });
        }else{
          let partFilt = this.spareParts.filter(item => item.ID == sparePart);
          if(partFilt.length > 0){
            let input = this._document.getElementById(`cant-req-${sparePart}`) as HTMLInputElement;
            if(input == null){
              this._resourcesService.openSnackBar(`No se pudo encontrar la configuración de la refacción ${partFilt[0].NOMB}.`);
              return;
            }

            let valStr = input.value;
            let valNum = parseInt(valStr);
            if(valNum <= 0){
              this._resourcesService.openSnackBar(`La cantidad configurada para la refacción ${partFilt[0].NOMB} no puede ser igual o menor a cero.`);
              return;
            }

            resourcesConf.push({
              ID: sparePart,
              REQ: valNum,
              TYPE: 'S'
            });
          }
        }
      }

      formData.append('resources', JSON.stringify(resourcesConf));
      formData.append('attached', JSON.stringify(this.attached));
      
      if(this.isNew){
        await lastValueFrom(this._correctiveMaintenanceService.registerWorkOrder(formData));
        this._resourcesService.openSnackBar('La orden de mantenimiento correctivo se registró correctamente.');
        this.goBack(1);
      }else{
        let idOrder = this.orderFormGroup.controls['idOrderControl'].value;
        let idOrderEnc = await this._encService.encrypt(idOrder);

        formData.append('id_order', idOrderEnc);

        await lastValueFrom(this._correctiveMaintenanceService.updateWorkOrder(formData));
        this._resourcesService.openSnackBar('La orden de mantenimiento correctivo se actualizó correctamente.');
        this.goBack(1);
      }

      this.savingWorkOrder = false;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_049: Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('ERR_GEOP_NUEV_050: Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(`ERR_GEOP_NUEV_051: ${error.error.msg}`);
      }

      this.savingWorkOrder = false;
    }
  }
}
