import { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { MaintenancePlanDetails, MaintenancePlanDetailsResponse } from '../../../../interfaces/corrective-maintenance.interface';
import { EquipmentsListItem, EquipmentsListResponse } from '../../../../interfaces/equipment-management.interface';
import { PriorityInterface } from '../../../system-admin/system-params/system-params.component';
import { SCADA, SCADAList } from '../../../../interfaces/scada-list.interface';
import { ActiveSymptomsListItem, ActiveSymptomsListResponse } from '../../../../interfaces/failure-analysis/symptom.interface';
import { MatTableDataSource } from '@angular/material/table';
import { TempFileInfo } from '../../../../interfaces/temp-file-info.interface';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { lastValueFrom, map, Observable, startWith } from 'rxjs';
import { DOCUMENT } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { EquipmentManagementService } from '../../../../services/equipment-management.service';
import { EncService } from '../../../../services/enc.service';
import { ResourcesService } from '../../../../services/resources.service';
import { InterventionService } from '../../../../services/personal-management/intervention.service';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { MatDialog } from '@angular/material/dialog';
import { GdelService } from '../../../../services/gdel.service';
import { FailureAnalysisService } from '../../../../services/failure-analysis/failure-analysis.service';
import { FunctionsService } from '../../../../services/functions.service';
import { OtherSpecialtiesDialogComponent } from './other-specialties-dialog/other-specialties-dialog.component';
import { ActiveSymptomDetailsComponent } from './active-symptom-details/active-symptom-details.component';
import { SpecificValueComponent } from '../../../resources/dialogs/specific-value/specific-value.component';
import { availableFiles } from '../../../../../environments/environment.prod';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { SpecialtiesListItem, SpecialtiesListResponse } from '../../../../interfaces/specialties.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-plan-register',
    templateUrl: './plan-register.component.html',
    styleUrl: './plan-register.component.css',
    standalone: false
})
export class PlanRegisterComponent implements OnInit {
  screenSize: number;
  action: string;
  isNew: boolean;
  idPlain: string | null;

  maintenancePlan: MaintenancePlanDetails | null;
  activatorLabel: string;
  counterLabel: string;

  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  searchingLRU: boolean;
  processingSpecialties: boolean;
  customSpecialties: string;
  isUploading: boolean;
  deleteFilesDisabled: boolean;

  equipmentsStr: string[];
  equipments: EquipmentsListItem[];
  equipmentsLRUStr: string[];
  equipmentsLRU: EquipmentsListItem[];
  specialties: SpecialtiesListItem[];
  priorities: PriorityInterface[];
  classifications: string[];
  tools: ToolInfo[];
  spareParts: ToolInfo[];
  scadas: SCADA[];
  symptoms: ActiveSymptomsListItem[];

  specialtiesDataSource: MatTableDataSource<any>;
  specialtiesDisplayedColumns = ['ESPE', 'OPERARIOS'];

  relatedDocumentsDataSource: MatTableDataSource<TempFileInfo>;
  relatedDocumentsDisplayedColumns = ['NOMBRE', 'TIPO', 'PESO', 'ACCIONES'];
  
  resourcesDataSource: MatTableDataSource<ToolInfo>;
  resourcesDisplayedColumns = ['ID', 'NOMB', 'MODE', 'TYPE', 'CANTDISP', 'CANTREC', 'CANTREST'];

  plainFormGroup: FormGroup;

  filteredEquipments?: Observable<string[]>;
  filteredLRU?: Observable<string[]>;
  filteredClassifications?: Observable<string[]>;

  @ViewChild('file') private uploader?: ElementRef;

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _activatedRoute: ActivatedRoute,
    private _equipmentManagementService: EquipmentManagementService,
    private _encService: EncService,
    private _resourcesService: ResourcesService,
    private _interventionService: InterventionService,
    private _sysAdminService: SystemAdminService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _dialog: MatDialog,
    private _gdelService: GdelService,
    private _failureAnalysisService: FailureAnalysisService,
    private _functionsService: FunctionsService,
  ) {
    this.screenSize = window.innerWidth;
    this.action = "";
    this.isNew = false;
    this.idPlain = null;

    this.maintenancePlan = null;
    this.activatorLabel = '';
    this.counterLabel = '';

    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.searchingLRU = false;
    this.processingSpecialties = false;
    this.customSpecialties = '';
    this.isUploading = false;
    this.deleteFilesDisabled = false;

    this.equipmentsStr = [];
    this.equipments = [];
    this.equipmentsLRUStr = [];
    this.equipmentsLRU = [];
    this.specialties = [];
    this.priorities = [];
    this.classifications = [];
    this.tools = TOOLS_TMP;
    this.spareParts = SPARE_PARTS_TMP;
    this.scadas = [];
    this.symptoms = [];

    this.specialtiesDataSource = new MatTableDataSource();
    this.relatedDocumentsDataSource = new MatTableDataSource();
    this.resourcesDataSource = new MatTableDataSource();

    this.plainFormGroup = new FormGroup({
      idPlanControl: new FormControl({value: '', disabled: true}),
      equipmentControl: new FormControl('', Validators.required),
      lruControl: new FormControl({value: '', disabled: true}),
      equipmentStatusControl: new FormControl('', Validators.required),
      lruStatusControl: new FormControl({value: '', disabled: true}),
      descriptionControl: new FormControl('', [Validators.required, Validators.minLength(15)]),
      inmTimeControl: new FormControl('', Validators.required),
      priorityControl: new FormControl('', Validators.required),
      totalDurationControl: new FormControl('', Validators.required),
      classificationControl: new FormControl('', Validators.required),
      specialtiesControl: new FormControl([], Validators.required),
      commentsControl: new FormControl('', Validators.minLength(15)),
      extraDetailsControl: new FormControl('', Validators.minLength(15)),
      resourcesControl: new FormControl([], Validators.required),
      symptomControl: new FormControl('', Validators.required),
      scadaControl: new FormControl('', Validators.required),
    });
  }

  ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe(res => {
      let params = res['data'];
      if(params == undefined){
        this.isNew = true;
        this.action = 'Registrar';
        this.idPlain = null;

        this.getEquipments();
      }else{
        this.isNew = false;
        this.action = 'Editar';
        this.idPlain = params;

        this.getMaintenancePlan(params);
      }
    });

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

    this.filteredLRU = this.plainFormGroup.controls['lruControl'].valueChanges.pipe(
      startWith(''),
      map(value => this._filterLRU(value || '')),
    );

    this.filteredClassifications = this.plainFormGroup.controls['classificationControl'].valueChanges.pipe(
      startWith(''),
      map(value => this._filterClassifications(value || '')),
    );
  }

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

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

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

  async getMaintenancePlan(idPlan: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let maintenancePlan: MaintenancePlanDetailsResponse = await lastValueFrom(this._correctiveMaintenanceService.getMaintenancePlan(
        idPlan, 
        idUser, 
        1
      ));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let idPlanDec = await this._encService.decrypt(maintenancePlan.response.ID_PLAN);

        this.plainFormGroup.controls['idPlanControl'].setValue(idPlanDec);
        this.plainFormGroup.controls['descriptionControl'].setValue(maintenancePlan.response.DESCRIPCION);
        this.plainFormGroup.controls['inmTimeControl'].setValue(maintenancePlan.response.TIEMPO_INMOVILIZACION_ESTIMADO);
        this.plainFormGroup.controls['totalDurationControl'].setValue(maintenancePlan.response.DURACION_TOTAL);
        this.plainFormGroup.controls['classificationControl'].setValue(maintenancePlan.response.CLASIFICACION);
        this.plainFormGroup.controls['commentsControl'].setValue(maintenancePlan.response.COMENTARIOS);
        this.plainFormGroup.controls['resourcesControl'].setValue(['N']);
        this.plainFormGroup.controls['extraDetailsControl'].setValue(maintenancePlan.response.DETALLES_ADICIONALES);

        this.plainFormGroup.controls['priorityControl'].disable();
        this.plainFormGroup.controls['scadaControl'].disable();
        this.plainFormGroup.controls['symptomControl'].disable();

        let idActivator = await this._encService.decrypt(maintenancePlan.response.ACTIVADOR);
        let idCounter = await this._encService.decrypt(maintenancePlan.response.CONTADOR);

        this.activatorLabel = `Parámetro modificable en el activador #${idActivator}`;
        this.counterLabel = `Parámetro modificable en el contador #${idCounter}`;

        let documentsArr: TempFileInfo[] = JSON.parse(maintenancePlan.response.DOCUMENTOS_RELACIONADOS);
        let documentsArrFn: TempFileInfo[] = [];
        
        for(const document of documentsArr){
          document.isFinalFile = true;
          document.size = this._functionsService.formatBytes(parseInt(document.size));
          documentsArrFn.push(document);
        }
        
        this.relatedDocumentsDataSource = new MatTableDataSource(documentsArrFn);
        this.maintenancePlan = maintenancePlan.response;
        this.getEquipments();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (1).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (2).';
      }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._equipmentManagementService.equipmentConsult(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let equipmentsArr: EquipmentsListItem[] = [];
        let equipmentsStr: string[] = [];

        for(const equipment of equipments.response){
          let planEquipment: string | null = null;
          if(this.maintenancePlan != null){
            let equipmentCodeDec = await this._encService.decrypt(this.maintenancePlan.EQUIPAMIENTO);
            planEquipment = equipmentCodeDec;
          }

          let equipmentCode = await this._encService.decrypt(equipment.CODIGO);
          equipment.TIPO = `${equipmentCode} - ${equipment.TIPO}`;

          let equipmentID = await this._encService.decrypt(equipment.ID_EQUIPO);
          equipment.ID_EQUIPO = `${equipment.MODELO} (${equipmentID})`;
          
          equipmentsArr.push(equipment);
          equipmentsStr.push(`${equipment.TIPO} - ${equipment.ID_EQUIPO}`);

          if(planEquipment != null && `${equipment.TIPO} - ${equipment.ID_EQUIPO}` == planEquipment){
            this.plainFormGroup.controls['equipmentControl'].setValue(planEquipment);
            this.plainFormGroup.controls['equipmentStatusControl'].setValue(this.maintenancePlan!.ESTADO_FUNCIONAMIENTO_EQUIPAMIENTO);

            if(this.maintenancePlan!.LRU != null){
              this.plainFormGroup.controls['equipmentControl'].disable();
              this.plainFormGroup.controls['equipmentStatusControl'].disable();
              this.plainFormGroup.controls['lruControl'].enable();
              this.plainFormGroup.controls['lruStatusControl'].enable();
              
              await this.getEquipmentLRU(equipment.CODIGO);

              let lruDec = await this._encService.decrypt(this.maintenancePlan!.LRU);
              for(const lru of this.equipmentsLRUStr){
                if(lru == lruDec){
                  this.plainFormGroup.controls['lruControl'].setValue(lru);
                  this.plainFormGroup.controls['lruStatusControl'].setValue(this.maintenancePlan!.ESTADO_FUNCIONAMIENTO_LRU);
                }
              }
            }
          }
        }

        this.equipments = equipmentsArr;
        this.equipmentsStr = equipmentsStr;

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

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

  async getEquipmentLRU(equipmentCode: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let equipmentLRU: EquipmentsListResponse = await lastValueFrom(this._equipmentManagementService.equipmentConsultByParent(
        equipmentCode, 
        idUser, 
        1
      ));

      if(equipmentLRU.error){
        this._resourcesService.openSnackBar(equipmentLRU.msg);
        this.searchingLRU = false;
      }else{
        let equipmentsArr: EquipmentsListItem[] = [];
        let equipmentsStr: string[] = [];

        for(const equipment of equipmentLRU.response){
          let equipmentCodeDec = await this._encService.decrypt(equipment.CODIGO);
          let equipmentIDDec = await this._encService.decrypt(equipment.ID_EQUIPO);

          equipmentsArr.push(equipment);
          equipmentsStr.push(`${equipmentCodeDec} - ${equipment.TIPO} - ${equipment.MODELO} (${equipmentIDDec})`);
        }

        this.equipmentsLRUStr = equipmentsStr;
        this.equipmentsLRU = equipmentsArr;

        this.searchingLRU = false;
        if(this.equipmentsLRUStr.length > 0){
          this.plainFormGroup.controls['lruControl'].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.searchingLRU = false;
    }
  }

  async getRegisteredSpecialties(){
    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 specialtiesArr: SpecialtiesListItem[] = [];
        for(const specialty of specialties.response){
          let specialtyDec = await this._encService.decrypt(specialty.CODIGO_ESPECIALIDAD);
          specialty.NOMBRE_ESPECIALIDAD = `${specialty.NOMBRE_ESPECIALIDAD} (${specialtyDec})`;
          
          specialtiesArr.push(specialty);
        }
        
        if(this.maintenancePlan != null){
          let specialtiesUsed = JSON.parse(this.maintenancePlan.ESPECIALIDADES_REQUERIDAS);
          let notRegisteredSpecialties = "";
          let registeredSpecialties: string[] = [];
          console.log(specialtiesUsed);
          
          /*for(const specialty of specialtiesUsed){
            let specialtyFilt = specialtiesArr.filter(item => item.label == specialty);
            if(specialtyFilt.length > 0){
              registeredSpecialties.push(specialtyFilt[0].value);
            }else{
              notRegisteredSpecialties += `${specialty}, `;
            }
          }*/

          notRegisteredSpecialties = notRegisteredSpecialties.substring(0, notRegisteredSpecialties.length - 2);
          
          this.plainFormGroup.controls['specialtiesControl'].setValue(registeredSpecialties);
          this.customSpecialties = notRegisteredSpecialties;
        }

        this.specialties = specialtiesArr;
        this.getOrderPriorities();
      }
    }catch(error: any){
      console.log(error);
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (5).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (6).';
      }else{
        this.errorStr = 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 as PriorityInterface[]){
          let valueEnc = await this._encService.encrypt(priority.value);
          if(this.maintenancePlan != null){
            let priorityDec = await this._encService.decrypt(this.maintenancePlan.PRIORIDAD);
            
            if(priorityDec == priority.value){
              this.plainFormGroup.controls['priorityControl'].setValue(valueEnc);
            }
          }

          priority.label = `${priority.label} (${priority.value})`;
          priority.value = valueEnc;

          prioritiesArr.push(priority);
        }

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

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

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

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

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

        this.getWebServices();
      }
    }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;
    }
  }

  async getWebServices(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let scadas: SCADAList = await lastValueFrom(this._sysAdminService.getSCADAList(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let scadasArr: SCADA[] = [];
        for(const scada of scadas.response){
          if(scada.ESTATUS == 'Activo'){
            let idSCADAEnc = await this._encService.encrypt(`${scada.IDSCADA}`);
            if(this.maintenancePlan != null){
              let scadaDec = await this._encService.decrypt(this.maintenancePlan.SCADA);
              if(scadaDec == scada.IDSCADA){
                this.plainFormGroup.controls['scadaControl'].setValue(idSCADAEnc);
              }
            }

            scada.NOMBRESCADA = `${scada.NOMBRESCADA} (${scada.IDSCADA})`;
            scada.IDSCADA = idSCADAEnc;

            scadasArr.push(scada);
          }
        }

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

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

  async getSymptoms(){
    try{
      const user: string = this._resourcesService.getUser();
      const line: number = this._resourcesService.getLineNumber();
      let symptoms: ActiveSymptomsListResponse = await lastValueFrom(this._failureAnalysisService.getSymptomsActives(user, line));

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

      if(!this.hasError){
        let symptomsArr: ActiveSymptomsListItem[] = [];
        for(const symptom of symptoms.response){
          console.log(symptom);
          
          //let idDec = await this._encService.decrypt(symptom.ID_SINTOMA);
          if(this.maintenancePlan != null){
            let symptomDec = await this._encService.decrypt(this.maintenancePlan.SINTOMA);
            if(symptomDec == symptom.ID_SINTOMA){
              this.plainFormGroup.controls['symptomControl'].setValue(symptom.ID_SINTOMA);
            }
          }

          symptom.NOMBRE_SINTOMA = `${symptom.NOMBRE_SINTOMA} (${symptom.ID_SINTOMA})`;
          symptomsArr.push(symptom);
        }

        this.symptoms = symptomsArr;
      }

      this.isLoading = false;
      this.initTables();
    }catch(error: any){
      console.log(error);
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (13).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (14).';
      }else{
        this.errorStr = error.error.msg;
      }

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

  initTables(){
    if(this.maintenancePlan != null){
      setTimeout(async () => {
        let specialties = this.plainFormGroup.controls['specialtiesControl'].value;

        this.updateSpecialtiesTable(specialties);

        let customSpecialtiesArr = this.customSpecialties.split(', ');
        let customSpecialtiesStr = JSON.stringify(customSpecialtiesArr);
        let customSpecialtiesEnc = await this._encService.encrypt(customSpecialtiesStr);

        await this.addCustomSpecialities(customSpecialtiesEnc);

        setTimeout(() => {
          let specialtiesConf = JSON.parse(this.maintenancePlan!.CONFIGURACION_OPERARIOS);
          let specialtiesKeys = Object.keys(specialtiesConf);
  
          for(const key of specialtiesKeys){
            let specialtyInput = this._document.getElementById(`${key}-OPER`) as HTMLInputElement;
            let specialtyValue = specialtiesConf[key];
            
            specialtyInput.value = specialtyValue;
          }
        }, 100);
      }, 100);
    }
  }

  updateSpecialtiesTable(value: string[]){
    console.log(value);
    
    /*let specialtiesArr: string[] = [];
    let shouldOpenOther = value.includes('OTR');

    for(const specialty of value){
      if(specialty != 'OTR'){
        let specialtyFilt = this.specialties.filter(item => item.value == specialty);
        if(specialtyFilt.length > 0){
          let specialtyObj = specialtyFilt[0];
          specialtiesArr.push(specialtyObj.label);
        }
      }
    }

    this.specialtiesDataSource = new MatTableDataSource(specialtiesArr);
    
    if(shouldOpenOther && this.customSpecialties == ''){
      let dialogRef = this._dialog.open(OtherSpecialtiesDialogComponent, {
        width: '480px',
        maxWidth: '480px',
        disableClose: true
      });
  
      dialogRef.afterClosed().subscribe(res => {
        if(res != null && res != undefined && res != ''){
          this.addCustomSpecialities(res);
        }else{
          let specialtiesAux: string[] = [];
          for(const specialtyStr of value){
            if(specialtyStr != 'OTR'){
              specialtiesAux.push(specialtyStr);
            }
          }

          this.plainFormGroup.controls['specialtiesControl'].setValue(specialtiesAux);
          this.updateSpecialtiesTable(specialtiesAux);
        }
      });
    }else if(!shouldOpenOther){
      this.customSpecialties = '';
    }*/
  }

  async addCustomSpecialities(specialtiesEnc: string){
    let specialtiesDec = await this._encService.decrypt(specialtiesEnc);
    let specialtiesArr = JSON.parse(specialtiesDec);
    let specialtiesStr = '';
    let specialties = this.specialtiesDataSource.data;

    for(const specialty of specialtiesArr){
      if(specialty != ''){
        specialtiesStr += `${specialty}, `;
        specialties.push(specialty);
      }
    }

    specialtiesStr = specialtiesStr.substring(0, specialtiesStr.length - 2);
    this.customSpecialties = specialtiesStr;
    this.specialtiesDataSource = new MatTableDataSource(specialties);
  }

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

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

  async validateEquipment(value: any, type: string){
    this.plainFormGroup.controls['equipmentStatusControl'].setValue(null);
    this.plainFormGroup.controls['equipmentStatusControl'].enable();
    this.plainFormGroup.controls['lruStatusControl'].setValue(null);
    this.plainFormGroup.controls['lruStatusControl'].disable();
    this.plainFormGroup.controls['lruStatusControl'].setValidators(null);

    let valueFn = '';
    if(type == 'SEL'){
      valueFn = value.source.value;
    }else{
      valueFn = value;
    }

    if(valueFn != '' && !this.searchingLRU){
      let valueArr = valueFn.split(' - ');
      if(valueArr.length != 3){
        this._resourcesService.openSnackBar('El equipamiento seleccionado es inválido.');
        return;
      }

      let equipmentCode = valueArr[0];
      let equipment: EquipmentsListItem | null = null;
      for(const equipmentObj of this.equipments){
        let codeDec = await this._encService.decrypt(equipmentObj.CODIGO);
        if(codeDec == equipmentCode){
          equipment = equipmentObj;
        }
      }

      if(equipment == null){
        this._resourcesService.openSnackBar('El equipamiento seleccionado no existe.');
        return;
      }

      let equipmentCodeEnc = await this._encService.encrypt(equipmentCode);
      
      this.searchingLRU = true;
      this.plainFormGroup.controls['lruControl'].setValue(null);
      this.plainFormGroup.controls['lruControl'].disable();
      this.getEquipmentLRU(equipmentCodeEnc);
    }
  }

  async verifyLRU(value: any, type: string){
    this.plainFormGroup.controls['equipmentStatusControl'].setValue(null);
    this.plainFormGroup.controls['equipmentStatusControl'].enable();
    this.plainFormGroup.controls['lruStatusControl'].setValue(null);
    this.plainFormGroup.controls['lruStatusControl'].disable();
    this.plainFormGroup.controls['lruStatusControl'].setValidators(null);

    let valueFn = '';
    if(type == 'SEL'){
      valueFn = value.source.value;
    }else{
      valueFn = value;
    }

    if(valueFn != ''){
      let valueArr = valueFn.split(' - ');
      if(valueArr.length != 3){
        this._resourcesService.openSnackBar('El LRU seleccionado es inválido.');
        return;
      }

      let equipmentCode = valueArr[0];
      let equipment: EquipmentsListItem | null = null;
      for(const equipmentObj of this.equipments){
        let codeDec = await this._encService.decrypt(equipmentObj.CODIGO);
        if(codeDec == equipmentCode){
          equipment = equipmentObj;
        }
      }

      if(equipment == null){
        this._resourcesService.openSnackBar('El equipamiento seleccionado no existe.');
        return;
      }
      
      this.plainFormGroup.controls['equipmentStatusControl'].setValue(null);
      this.plainFormGroup.controls['equipmentStatusControl'].disable();
      this.plainFormGroup.controls['lruStatusControl'].setValue(null);
      this.plainFormGroup.controls['lruStatusControl'].enable();
      this.plainFormGroup.controls['lruStatusControl'].setValidators(Validators.required);
    }
  }

  lruStatusChange(event: any){
    let value = event.value;
    if(value == 'DE'){
      this.plainFormGroup.controls['equipmentStatusControl'].setValue('DP');
    }else if(value == 'EF'){
      this.plainFormGroup.controls['equipmentStatusControl'].setValue('EF');
    }
  }

  validateNumber(value: string, type: string, control: string){
    let validChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let valueArr = value.split('');
    let pointsCounter = 0;
    let validVal = '';

    valueArr.forEach(char => {
      if(char == '.' && pointsCounter < 1){
        validVal += '.';
        pointsCounter++;
      }else if(validChars.includes(char)){
        validVal += char;
      }
    });

    if(type == 'INP'){
      this.plainFormGroup.controls[control].markAsTouched();
      this.plainFormGroup.controls[control].setValue(validVal);
    }else if(type == 'BLU'){
      let valueFn = validVal.charAt(0) == '.' ? `0${validVal}`: validVal;
      
      this.plainFormGroup.controls[control].markAsTouched();
      this.plainFormGroup.controls[control].setValue(valueFn);
    }
  }

  async openSymptomDetails(symptom: string){
    let symptomFilt = this.symptoms.filter(item => item.ID_SINTOMA == symptom);
    if(symptomFilt.length > 0){
      symptomFilt[0].ID_SINTOMA = await this._encService.decrypt(symptomFilt[0].ID_SINTOMA);
      symptomFilt[0].ID_MEDIDA = await this._encService.decrypt(symptomFilt[0].ID_MEDIDA);
      symptomFilt[0].FECHA_REGISTRA = this._functionsService.orderDate(symptomFilt[0].FECHA_REGISTRA);

      if(symptomFilt[0].FECHA_MODIFICA){
        symptomFilt[0].FECHA_MODIFICA = this._functionsService.orderDate(symptomFilt[0].FECHA_MODIFICA);
      }

      this._dialog.open(ActiveSymptomDetailsComponent, {
        width: '480px',
        maxWidth: '480px',
        data: {
          symptom: symptomFilt[0],
        },
      });
    }
  }

  changeOperators(action: string, specialty: string){
    let specialtyInput = this._document.getElementById(`${specialty}-OPER`) as HTMLInputElement;
    if(action == 'add' && specialtyInput != undefined){
      let operatorsValue = parseInt(specialtyInput.value);
      specialtyInput.value = `${operatorsValue + 1}`;
    }else if(action == 'remove' && specialtyInput != undefined){
      let operatorsValue = parseInt(specialtyInput.value);
      let valueTmp = operatorsValue - 1;
      if(valueTmp < 0){
        specialtyInput.value = '0';
      }else{
        specialtyInput.value = `${operatorsValue - 1}`;
      }
    }
  }

  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.plainFormGroup.controls['resourcesControl'].setValue(['N']);
      this.resourcesDataSource = new MatTableDataSource();
    }
  }

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

  checkFile(event: any, type: string){
    let typeLimit = 0;

    switch(type){
      case "FSPQ": typeLimit = 1; break;
      case "FITE": typeLimit = 1; break;
      case "FODI": typeLimit = 5; break;
      case "DAPR": typeLimit = 1; break;
      case "MAOP": typeLimit = 1; break;
      case "MMCO": typeLimit = 1; break;
      case "DOAD": typeLimit = 3; break;
    }

    let typeStr = this.getTypeText(type);
    let alreadyAttachedByType = this.relatedDocumentsDataSource.data.filter(item => item.type == typeStr);
    if(alreadyAttachedByType.length >= typeLimit){
      this._resourcesService.openSnackBar(`El límite de documentos por tipo es de ${typeLimit} archivo(s).`);
      return;
    }
    
    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{
        for(const file of this.relatedDocumentsDataSource.data){
          if(file.name == event.target.files[0].name && file.size == this._resourcesService.formatBytes(event.target.files[0].size)){
            this._resourcesService.openSnackBar("El archivo seleccionado ya fue adjuntado.");
            return;
          }
        }

        this.uploadTmp(event.target.files[0], type);
      }
    }
  }

  getTypeText(type: string): string{
    switch(type){
      case "FSPQ": return "Ficha de seguridad de productos químicos"; break;
      case "FITE": return "Ficha técnica"; break;
      case "FODI": return "Fotografías o diagramas"; break;
      case "DAPR": return "Datos del proveedor"; break;
      case "MAOP": return "Manual de operación"; break;
      case "MMCO": return "Manual de mantenimiento correctivo"; break;
      case "DOAD": return "Dcoumentos adicionales"; break;
      default: return ""; break;
    }
  }

  async uploadTmp(fileData: any, type: string){
    try{
      this.isUploading = true;

      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: this.getTypeText(type),
          isFinalFile: false,
        };

        let attachedFiles = this.relatedDocumentsDataSource.data;
        attachedFiles.push(uploadedFile);

        this.relatedDocumentsDataSource = new MatTableDataSource(attachedFiles);
      }

      this.isUploading = 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.isUploading = false;
    }
  }

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

  async downloadFile(idFile: string){
    try{
      this.deleteFilesDisabled = true;
      this._resourcesService.openSnackBar('Descargando documento...');

      let idUser = localStorage.getItem('idusuario')!;
      let download = this._document.getElementById('download') as HTMLAnchorElement;
      let downloadToken = await lastValueFrom(this._gdelService.getDownloadToken(idFile, idUser, 1));
      let idFileDec = await this._encService.decrypt(idFile);
  
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = idFileDec;
      download.click();

      this._resourcesService.openSnackBar('Descarga realizada.');
      this.deleteFilesDisabled = 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.deleteFilesDisabled = false;
    }
  }

  openDeleteFileAlert(idFile: string){
    let fileFilt = this.relatedDocumentsDataSource.data.filter(item => item.id == idFile);
    if(fileFilt.length > 0){
      let dialogRef = this._dialog.open(AlertComponent, {
        width: '420px',
        maxWidth: '420px',
        disableClose: true,
        data: {
          title: '¡Cuidado!',
          icon: 'warning',
          description: `¿Está seguro de eliminar el documento ${fileFilt[0].name}?`,
          description2: 'Esta acción no se puede deshacer.'
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res == true){
          this.deleteFile(idFile);
        }
      });
    }
  }

  async deleteFile(id: string){
    try{
      if(this.deleteFilesDisabled == false){
        this.deleteFilesDisabled = true;

        let attachedFiles = this.relatedDocumentsDataSource.data;
        let idUser = localStorage.getItem('idusuario')!;

        let fileFilt = attachedFiles.filter(file => file.id == id);
        if(fileFilt.length > 0){
          let attachedAux: TempFileInfo[] = [];
          for(const file of attachedFiles){
            if(file.id != id){
              attachedAux.push(file);
            }
          }

          if(fileFilt[0].isFinalFile){
            await lastValueFrom(this._gdelService.deleteFile({
              'id_user': idUser!,
              'id_file': id,
              'linea': 1,
            }));
          }else{
            await lastValueFrom(this._gdelService.deleteTempFile({
              'id_user': idUser!,
              'id_file': id,
              'linea': 1,
            }));
          }

          this.relatedDocumentsDataSource = new MatTableDataSource(attachedAux);
          this.deleteFilesDisabled = 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.deleteFilesDisabled = false;
    }
  }

  async saveMaintenancePlan(){
    try{
      if(this.plainFormGroup.invalid){
        this._resourcesService.openSnackBar('Aún no ha completado todos los campos del formulario.');
        this.plainFormGroup.markAllAsTouched();
        return;
      }

      let dataSheetFiles = this.relatedDocumentsDataSource.data.filter(item => item.type == 'Ficha técnica');
      if(dataSheetFiles.length <= 0){
        this._resourcesService.openSnackBar('Para continuar debe adjuntar un archivo de ficha técnica.');
        return;
      }

      let photosDiagramas = this.relatedDocumentsDataSource.data.filter(item => item.type == 'Fotografías o diagramas');
      if(photosDiagramas.length < 3){
        this._resourcesService.openSnackBar('Para continuar debe adjuntar al menos 3 fotografías o diagramas.');
        return;
      }

      let providerData = this.relatedDocumentsDataSource.data.filter(item => item.type == 'Datos del proveedor');
      if(providerData.length <= 0){
        this._resourcesService.openSnackBar('Para continuar debe adjuntar un archivo de datos del proveedor.');
        return;
      }

      let operationGuide = this.relatedDocumentsDataSource.data.filter(item => item.type == 'Manual de operación');
      if(operationGuide.length <= 0){
        this._resourcesService.openSnackBar('Para continuar debe adjuntar al menos 1 manual de operación.');
        return;
      }

      let correctiveMaintenanceGuide = this.relatedDocumentsDataSource.data.filter(item => item.type == 'Manual de mantenimiento correctivo');
      if(correctiveMaintenanceGuide.length <= 0){
        this._resourcesService.openSnackBar('Para continuar debe adjuntar al menos 1 manual de mantenimiento correctivo.');
        return;
      }

      let idUser = localStorage.getItem('idusuario')!;
      let formValue = this.plainFormGroup.getRawValue();
      let attached = JSON.stringify(this.relatedDocumentsDataSource.data);
      let formData = new FormData();
      let equipmentArr = formValue.equipmentControl.split(' - ');

      formData.append('id_user', idUser);
      formData.append('linea', '1');

      if(equipmentArr.length < 3){
        this._resourcesService.openSnackBar(`El equipamiento ${formValue.equipmentControl} es inválido.`);
        return;
      }
      
      let equipmentEnc = await this._encService.encrypt(equipmentArr[0]);
      formData.append('equipment', equipmentEnc);
      if(formValue.lruControl != null){
        let lruArr = formValue.lruControl.split(' - ');

        if(lruArr.length < 3){
          this._resourcesService.openSnackBar(`El LRU ${formValue.equipmentControl} es inválido.`);
          return;
        }

        let lruEnc = await this._encService.encrypt(lruArr[0]);
        formData.append('lru', lruEnc);
      }

      formData.append('equipment_status', formValue.equipmentStatusControl);
      if(formValue.lruStatusControl != null){
        formData.append('lru_status', formValue.lruStatusControl);
      }

      formData.append('description', formValue.descriptionControl);
      formData.append('inm_time', formValue.inmTimeControl);
      formData.append('priority', formValue.priorityControl);
      formData.append('total_duration', formValue.totalDurationControl);
      formData.append('classification', formValue.classificationControl);
      formData.append('symptom', formValue.symptomControl);
      formData.append('scada', formValue.scadaControl);
      formData.append('specialties', JSON.stringify(formValue.specialtiesControl));

      let specialtiesObj = {};
      for(const specialty of formValue.specialtiesControl){
        let specialtyDec = await this._encService.decrypt(specialty);
        let specialtyInput = this._document.getElementById(`${specialtyDec}-OPER`) as HTMLInputElement;

        if(specialtyInput.value == '0'){
          this._resourcesService.openSnackBar(`Aún no se han configurado operarios para la especialidad ${specialtyDec}`);
          return;
        }

        specialtiesObj[specialtyDec as never] = specialtyInput.value as never;
      }

      formData.append('specialties_conf', JSON.stringify(specialtiesObj));
      if(formValue.commentsControl != ""){
        formData.append('comments', formValue.commentsControl);
      }

      //PENDIENTE REVISAR HERRAMIENTAS EN STOCK
      formData.append('resources', '[]');
      if(formValue.extraDetailsControl != ""){
        formData.append('extra_details', formValue.extraDetailsControl);
      }

      formData.append('attached', attached);

      if(this.isNew){
        let response = await lastValueFrom(this._correctiveMaintenanceService.registerMaintenancePlan(formData));
  
        if(response.error){
          this._resourcesService.openSnackBar(response.msg)
        }else{
          let idActiDec = await this._encService.decrypt(response.response.ACTIVADOR);
          let idContDec = await this._encService.decrypt(response.response.CONTADOR);
          let idPlanDec = await this._encService.decrypt(response.response.PLAN);
  
          this._resourcesService.openSnackBar(`El plan #${idPlanDec} fue generado correctamente, se crearon y asociaron el contador #${idContDec} y el activador #${idActiDec}`);
          this.goBack(1);
        }
      }else{
        formData.append('id_plan', this.idPlain!);
        await lastValueFrom(this._correctiveMaintenanceService.updateMaintenancePlan(formData));
        
        let idPlanDec = await this._encService.decrypt(`${this.idPlain}`);
        this._resourcesService.openSnackBar(`El plan #${idPlanDec} se actualizó correctamente.`);
        this.goBack(1);
      }

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