import { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute } from '@angular/router';
import { Observable, lastValueFrom, map, startWith } from 'rxjs';
import { CounterDetailsComponent } from 'src/app/components/counters-activators/counters-management/counter-details/counter-details.component';
import { SearchFileDialogComponent } from 'src/app/components/gdel/search-file-dialog/search-file-dialog.component';
import { PriorityInterface } from 'src/app/components/system-admin/system-params/system-params.component';
import { CounterLastMeasureDetailsResponse, CounterLastMeasuresListItem, CountersByEquipmentListItem, CountersByEquipmentListResponse } from 'src/app/interfaces/counters-activators.interface';
import { EquipmentsListItem, EquipmentsListResponse } from 'src/app/interfaces/equipment-management.interface';
import { FindedFile } from 'src/app/interfaces/finded-files.interface';
import { EmployeesListItem, EmployeesListResponse } from 'src/app/interfaces/personal-managment/employee.interface';
import { SubcontratistItem, SubcontratistsResponse } from 'src/app/interfaces/personal-managment/subcontratists.interface';
import { TempFileInfo } from 'src/app/interfaces/temp-file-info.interface';
import { CountersActivatorsService } from 'src/app/services/counters-activators.service';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { EquipmentManagementService } from 'src/app/services/equipment-management.service';
import { DynamicFormService } from 'src/app/services/forms-management/dynamic-form.service';
import { FunctionsService } from 'src/app/services/functions.service';
import { EmployeeService } from 'src/app/services/personal-management/employee.service';
import { SubcontratistService } from 'src/app/services/personal-management/subcontratist.service';
import { WorkTeamService } from 'src/app/services/personal-management/work-team.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { availableFiles } from 'src/environments/environment.prod';
import { MeasuresHistoryComponent } from './measures-history/measures-history.component';
import { MeasuresGraphComponent } from './measures-graph/measures-graph.component';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { DOCUMENT } from '@angular/common';
import { SpecificValueComponent } from 'src/app/components/resources/dialogs/specific-value/specific-value.component';
import { CorrectiveMaintenanceService } from 'src/app/services/corrective-maintenance.service';
import { CorrectiveWorkOrderDetails, CorrectiveWorkOrderDetailsResponse, SecurityManagementListItem, SecurityManagementListResponse } from 'src/app/interfaces/corrective-maintenance.interface';

interface ToolInfo{
  ID: string;
  NOMB: string;
  MODE: string;
  CANTDISP: number;
  TYPE: string;
  UNIT: string;
}
const TOOLS_TMP: ToolInfo[] = [
  {ID: 'H1', NOMB: 'Pinzas eléctricas', MODE: 'PE-862', CANTDISP: 35, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H2', NOMB: 'Pinzas mecánicas', MODE: 'M985', CANTDISP: 27, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H3', NOMB: 'Pinzas de presión', MODE: 'RG-12', CANTDISP: 30, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H4', NOMB: 'Juego de llaves Allen', MODE: 'ALL88', CANTDISP: 75, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H5', NOMB: 'Extractor de rodamientos', MODE: 'EX-ROD-1500', CANTDISP: 3, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H6', NOMB: 'Kit llaves inglesas', MODE: '5530S', CANTDISP: 7, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H7', NOMB: 'Kit llaves españolas', MODE: '964F', CANTDISP: 8, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H8', NOMB: 'Juego de llaves Torx', MODE: 'TORX3423W', CANTDISP: 42, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H9', NOMB: 'Cautín de lápiz 33W', MODE: '33WCL', CANTDISP: 15, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H10', NOMB: 'Juego de dados milimétricos', MODE: 'DMM450', CANTDISP: 6, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H11', NOMB: 'Juego de dados pulgadas', MODE: 'DIN865', CANTDISP: 9, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H12', NOMB: 'Probador de corriente', MODE: '569', CANTDISP: 33, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H13', NOMB: 'Multímetro', MODE: 'TGH885', CANTDISP: 17, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H14', NOMB: 'Planta generadora para soldadura', MODE: 'PLAGEN-589', CANTDISP: 1, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H15', NOMB: 'Amperímetro de gancho', MODE: 'A0032', CANTDISP: 4, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H16', NOMB: 'Rotomartillo', MODE: '551', CANTDISP: 2, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H17', NOMB: 'Kit taladro inalámbrico', MODE: 'FP581', CANTDISP: 12, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H18', NOMB: 'Kit taládro alámbrico', MODE: 'HG862', CANTDISP: 10, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H19', NOMB: 'Juego de desarmadores', MODE: '8913-KSOA', CANTDISP: 5, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H20', NOMB: 'Martillo', MODE: 'TS438', CANTDISP: 23, TYPE: 'Herramienta', UNIT: 'Pieza'},
];
const SPARE_PARTS_TMP: ToolInfo[] = [
  {ID: 'S1', NOMB: 'Neumático para NM-16', MODE: 'NM16NEU235', CANTDISP: 45, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S2', NOMB: 'Neumático para NM-22', MODE: 'NM22NEU652', CANTDISP: 51, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S3', NOMB: 'Rodamiento cónico', MODE: 'RC-4265', CANTDISP: 84, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S4', NOMB: 'Rodamiento axial', MODE: 'RA-5130', CANTDISP: 96, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S5', NOMB: 'Rodamiento angular', MODE: 'RN-3541', CANTDISP: 79, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S6', NOMB: 'Grasa 1-310', MODE: 'G1.310', CANTDISP: 9, TYPE: 'Refaccción', UNIT: 'Kilogramo'},
  {ID: 'S7', NOMB: 'Aceite 10W-40', MODE: 'A10W40', CANTDISP: 16, TYPE: 'Refaccción', UNIT: 'Litro'},
  {ID: 'S8', NOMB: 'Soldadura de estaño', MODE: 'LDA-913', CANTDISP: 39, TYPE: 'Refaccción', UNIT: 'Metro'},
  {ID: 'S9', NOMB: 'Soldadura de plata', MODE: 'BDA-516', CANTDISP: 21, TYPE: 'Refaccción', UNIT: 'Metro'},
  {ID: 'S10', NOMB: 'Pastilla de frenado', MODE: '754SSV', CANTDISP: 25, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S11', NOMB: 'Cable de cobre calibre 0', MODE: 'CC0-884', CANTDISP: 120, TYPE: 'Refaccción', UNIT: 'Metro'},
  {ID: 'S12', NOMB: 'Rosetas de cable Ethernet', MODE: '165-BFS', CANTDISP: 12, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S13', NOMB: 'Pintura', MODE: '53469', CANTDISP: 250, TYPE: 'Refaccción', UNIT: 'Litro'},
  {ID: 'S14', NOMB: 'Solvente de pintura', MODE: '2516', CANTDISP: 310, TYPE: 'Refaccción', UNIT: 'Litro'},
  {ID: 'S15', NOMB: 'Lámina galvanizada', MODE: 'SFAS-320', CANTDISP: 38, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S16', NOMB: 'Botón de freno de emergencia', MODE: 'B-51321', CANTDISP: 14, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S17', NOMB: 'Disco duro de estado sólido 512GB', MODE: 'SSD-512', CANTDISP: 22, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S18', NOMB: 'Mouse óptico', MODE: 'MO1165', CANTDISP: 26, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S19', NOMB: 'Teclado para PC', MODE: '5413', CANTDISP: 24, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S20', NOMB: 'Cable HDMI 2m', MODE: 'ASD-181', CANTDISP: 6, TYPE: 'Refaccción', UNIT: 'Pieza'},
];
@Component({
  selector: 'app-corrective-order-form',
  templateUrl: './corrective-order-form.component.html',
  styleUrls: ['./corrective-order-form.component.css']
})
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;
  
  orderPriorities: PriorityInterface[];
  equipments: EquipmentsListItem[];
  employees: EmployeesListItem[];
  subcontratists: SubcontratistItem[];
  workTeams: any[];
  attached: TempFileInfo[];
  equipmentCounters: CountersByEquipmentListItem[];
  tools: ToolInfo[];
  spareParts: ToolInfo[];
  classifications: string[];
  responsibleUsers: any[];
  securityManagements: SecurityManagementListItem[];

  orderFormGroup: FormGroup;
  symptomsDataSource: MatTableDataSource<CounterLastMeasuresListItem>;
  symptomsDisplayedColumns = ['ID', 'VALOR', 'WEBSERVICE', 'FECREG', 'ACCIONES'];
  resourcesDataSource: MatTableDataSource<ToolInfo>;
  resourcesDisplayedColumns = ['ID', 'NOMB', 'MODE', 'TYPE', 'CANTDISP', 'CANTREC', 'CANTREST'];

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

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _formsService: DynamicFormService,
    private _activatedRoute: ActivatedRoute,
    private _resourcesService: ResourcesService,
    private _sysAdminService: SystemAdminService,
    private _encService: EncService,
    private _equipmentsService: EquipmentManagementService,
    private _employeeService: EmployeeService,
    private _subcontratistService: SubcontratistService,
    private _workTeamsService: WorkTeamService,
    private _dialog: MatDialog,
    private _gdelService: GdelService,
    private _countersActivatorsService: CountersActivatorsService,
    private _functionsService: FunctionsService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
  ) {
    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.orderPriorities = [];
    this.equipments = [];
    this.employees = [];
    this.subcontratists = [];
    this.workTeams = [];
    this.attached = [];
    this.equipmentCounters = [];
    this.tools = TOOLS_TMP;
    this.spareParts = SPARE_PARTS_TMP;
    this.classifications = [];
    this.responsibleUsers = [];
    this.securityManagements = [];

    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)]),
      resourcesControl: new FormControl([], Validators.required),
      personalControl: new FormControl([], Validators.required),
      activationType: new FormControl({value: 'Manual', disabled: true}, Validators.required),
    });

    this.symptomsDataSource = new MatTableDataSource();
    this.resourcesDataSource = new MatTableDataSource();
  }

  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 || '')),
    );
  }

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

  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);

        let resourcesArr = JSON.parse(order.response.RECURSOS);
        let resourcesVal: string[] = [];
        for(const resource of resourcesArr){
          let toolFilt = this.tools.filter(tool => tool.ID == resource.ID);
          let sparePartFilt = this.spareParts.filter(sparePart => sparePart.ID == resource.ID);

          if(toolFilt.length > 0){
            resourcesVal.push(`${resource.ID}-H`);
          }

          if(sparePartFilt.length > 0){
            resourcesVal.push(`${resource.ID}-R`);
          }
        }
        
        if(resourcesArr.length == 0){
          this.orderFormGroup.controls['resourcesControl'].setValue(['N']);
        }else{
          this.orderFormGroup.controls['resourcesControl'].setValue(resourcesVal);
        }
        
        this.attached = JSON.parse(order.response.DOCUMENTOS_RELACIONADOS);

        let equipmentCodeDec = await this._encService.decrypt(order.response.CODIGO_EQUIPAMIENTO);
        order.response.TIPO_EQUIPAMIENTO = `${equipmentCodeDec} - ${order.response.TIPO_EQUIPAMIENTO}`;

        let idEquipmentDec = await this._encService.decrypt(order.response.ID_EQUIPAMIENTO);
        order.response.MODELO_EQUIPAMIENTO = `${order.response.MODELO_EQUIPAMIENTO} (${idEquipmentDec})`;

        this.correctiveWorkOrder = order.response;
        this.getOrderPriorities();
      }
    }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;
    }
  }

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

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

  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 = '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 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 = '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 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 = '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 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.getEquipments();
      }
    }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 getEquipments(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let equipments: EquipmentsListResponse = await lastValueFrom(this._equipmentsService.equipmentConsult(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let equipmentsArr: EquipmentsListItem[] = [];
        for(const equipment of equipments.response){
          let codeDec = await this._encService.decrypt(equipment.CODIGO);
          let idDec = await this._encService.decrypt(equipment.ID_EQUIPO);

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

          equipmentsArr.push(equipment);
          if(this.correctiveWorkOrder != null){
            let orderEquipment = await this._encService.decrypt(this.correctiveWorkOrder.CODIGO_EQUIPAMIENTO);
            if(orderEquipment == codeDec){
              this.orderFormGroup.controls['equipmentControl'].setValue(equipment.CODIGO);
              await this.equipmentChange(equipment.CODIGO);
            }
          }
        }

        this.equipments = equipmentsArr;
        this.getEmployees();
      }
    }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 getEmployees(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let employees: EmployeesListResponse = await lastValueFrom(this._employeeService.getConsultOfEmployees(idUser));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let employeesArr: EmployeesListItem[] = [];
        for(const employee of employees.response){
          let idEnc = await this._encService.encrypt(`${employee.ID_EMPLOYEE}`);

          employee.NAME = `${employee.NAME} (${employee.ID_EMPLOYEE})`;
          employee.ID_EMPLOYEE = idEnc;

          if(employee.STATUS == 'Activo'){
            employeesArr.push(employee);
          }
        }
        
        this.employees = employeesArr;
        this.getSubcontratists();
      }
    }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 getSubcontratists(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let subcontratists: SubcontratistsResponse = await lastValueFrom(this._subcontratistService.getConsultOfSubcontratists(idUser));

      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 idEnc = await this._encService.encrypt(`${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' && subcontratist.ID_SUBCONTRATIST == idResponsibleStr){
              this.orderFormGroup.controls['responsibleUserControl'].setValue(`${idEnc}|subcontratist`);
            }
          }

          subcontratist.NAME = `${subcontratist.NAME} (${subcontratist.ID_SUBCONTRATIST})`;
          subcontratist.ID_SUBCONTRATIST = idEnc;

          if(subcontratist.STATUS == 'Activo'){
            subcontratistsArr.push(subcontratist);
          }
        }

        this.subcontratists = subcontratistsArr;
        this.getWorkTeams();
      }
    }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 getWorkTeams(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let workTeams = await lastValueFrom(this._workTeamsService.getConsultOfWorkteams(idUser));

      this.hasError = workTeams.error;
      this.errorStr = workTeams.msg;
      
      if(!this.hasError){
        let workTeamsArr: any[] = [];
        for(const workTeam of workTeams.response){
          let idEnc = await this._encService.encrypt(`${workTeam.WORKTEAM_ID}`);

          workTeam.NAME = `${workTeam.NAME} (${workTeam.WORKTEAM_ID})`;
          workTeam.WORKTEAM_ID = idEnc;

          if(workTeam.STATUS == 'Activo'){
            workTeamsArr.push(workTeam);
          }
        }

        this.workTeams = workTeamsArr;

        if(this.correctiveWorkOrder != null){
          let staffArr = JSON.parse(this.correctiveWorkOrder.PERSONAL);
          let staffArrDec: any[] = [];

          for(const staffObj of staffArr){
            let idDec = await this._encService.decrypt(staffObj.ID);
            staffObj.ID = idDec;

            staffArrDec.push(staffObj);
          }

          let staffVal: string[] = [];
          for(const workTeam of this.workTeams){
            let idDec = await this._encService.decrypt(workTeam.WORKTEAM_ID);
            let workTeamFilt = staffArrDec.filter(item => item.ID == idDec && item.TYPE == 'EQ');
            if(workTeamFilt.length > 0){
              staffVal.push(`${workTeam.WORKTEAM_ID}-EQ`);
            }
          }

          for(const subcontratist of this.subcontratists){
            let idDec = await this._encService.decrypt(subcontratist.ID_SUBCONTRATIST as string);
            let subcontratistFilt = staffArrDec.filter(item => item.ID == idDec && item.TYPE == 'SU');
            if(subcontratistFilt.length > 0){
              staffVal.push(`${subcontratist.ID_SUBCONTRATIST}-SU`);
            }
          }

          for(const employee of this.employees){
            let idDec = await this._encService.decrypt(employee.ID_EMPLOYEE as string);
            let employeeFilt = staffArrDec.filter(item => item.ID == idDec && item.TYPE == 'EM');
            if(employeeFilt.length > 0){
              staffVal.push(`${employee.ID_EMPLOYEE}-EM`);
            }
          }
          
          this.orderFormGroup.controls['personalControl'].setValue(staffVal);
        }
      }

      this.isLoading = false;
      if(this.correctiveWorkOrder != null){
        let resourcesVal = this.orderFormGroup.controls['resourcesControl'].value;
        this.spareAndToolsChange(resourcesVal);
      }
    }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;
    }
  }

  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}`);
      }
    }
  }

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

  searchExistingFile(){
    let existingFiles = this.attached.filter(item => item.type == 'Existente');
    
    let dialogRef = this._dialog.open(SearchFileDialogComponent, {
      width: '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);
          }
        });
      }
    });
  }

  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 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('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  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('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  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('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.loadingCounters = false;
    }
  }

  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',
          data: {
            idCounter: idCounterEnc,
            includeActivator: true,
            idActivator: counterFilt[0].ID_ACTIVADOR,
          }
        });
      }else{
        this._resourcesService.openSnackBar('El contador seleccionado es inválido.');
      }
    }
  }

  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('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.loadingMeasures = false;
      this.orderFormGroup.controls['counterControl'].enable();
    }
  }

  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',
        disableClose: true,
        data: {
          idCounter: idCounterEnc,
        }
      })
    }else if(mode == 'graph'){
      this._dialog.open(MeasuresGraphComponent, {
        width: '720px',
        disableClose: true,
        data: {
          idCounter: idCounterEnc,
        }
      })
    }
  }

  spareAndToolsChange(value: string[]){
    //PENDIENTE INTERFAZ CON STOCK
    if(!value.includes('N')){
      let resourcesArr: ToolInfo[] = [];
      for(const resource of value){
        let resourceArr = resource.split('-');
        if(resourceArr[1] == 'R'){
          let sparePart = this.spareParts.filter(part => part.ID == resourceArr[0]);
          if(sparePart.length > 0){
            resourcesArr.push(sparePart[0]);
          }
        }else if(resourceArr[1] == 'H'){
          let tool = this.tools.filter(tool => tool.ID == resourceArr[0]);
          if(tool.length > 0){
            resourcesArr.push(tool[0]);
          }
        }
      }

      this.resourcesDataSource = new MatTableDataSource(resourcesArr);
      setTimeout(() => {
        for(const resourceObj of resourcesArr){
          let inputRes = this._document.getElementById(`cant-rest-${resourceObj.ID}`) as HTMLInputElement;
          inputRes.value = `${resourceObj.CANTDISP - 1}`;
        }
      }, 100);
    }else{
      this.orderFormGroup.controls['resourcesControl'].setValue(['N']);
      this.resourcesDataSource = new MatTableDataSource();
    }
  }

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

  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',
      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}`;
        }
      }
    });
  }

  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',
          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);
      formData.append('equipment', formValue.equipmentControl);
      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);
      formData.append('staff', JSON.stringify(formValue.personalControl));
      formData.append('activation_type', formValue.activationType);

      let resourcesArr: any[] = [];
      if(!formValue.resourcesControl.includes('N')){
        for(const resource of formValue.resourcesControl){
          let resourceArr = resource.split('-');
          let reqInput = this._document.getElementById(`cant-req-${resourceArr[0]}`) as HTMLInputElement;
  
          resourcesArr.push({
            ID: resourceArr[0],
            REQ: reqInput.value
          });
        }
      }

      formData.append('resources', JSON.stringify(resourcesArr));
      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){
      console.log(error);
      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.savingWorkOrder = false;
    }
  }
}
