import { CountersActivatorsService } from 'src/app/services/counters-activators.service';
import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { lastValueFrom } from 'rxjs';
import { PreventiveWorkOrder } from 'src/app/interfaces/preventive-work-order.interface';
import { PreventiveWorkOrderResponse } from 'src/app/interfaces/preventive-work-order.interface';
import { AdvicesService } from 'src/app/services/advices.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { PreventiveMaintenanceService } from 'src/app/services/preventive-maintenance.service';
import { Activator, ActivatorResponse } from 'src/app/interfaces/activator.interface';
import { FunctionsService } from 'src/app/services/functions.service';
import { SystemAdminService } from 'src/app/services/system-admin.service';
import { PriorityInterface } from 'src/app/components/system-admin/system-params/system-params.component';
import { DocumentManagementService } from 'src/app/services/document-management/document-management.service';

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'},
];
interface Magnitudes{
  MAGNITUDE: string;
  LABEL: string;
  UNITS: Units[];
}
interface Units{
  UNIT: string,
  LABEL: string,
}
const MAGNITUDES: Magnitudes[] = [
  {MAGNITUDE: 'TEM', LABEL: 'Temperatura', UNITS: [
    {UNIT: 'K', LABEL: '°K - Kelvin'},
    {UNIT: 'C', LABEL: '°C - Celsius'},
    {UNIT: 'F', LABEL: '°F - Fahrenheit'},
  ]},
  {MAGNITUDE: 'TEN', LABEL: 'Tensión', UNITS: [
    {UNIT: 'V', LABEL: 'V - Volts'},
  ]},
  {MAGNITUDE: 'COR', LABEL: 'Corriente', UNITS: [
    {UNIT: 'A', LABEL: 'A - Amperios'},
  ]},
  {MAGNITUDE: 'POT', LABEL: 'Potencia', UNITS: [
    {UNIT: 'W', LABEL: 'W - Watts'},
    {UNIT: 'HP', LABEL: 'HP - Caballos de fuerza'}
  ]},
  {MAGNITUDE: 'FRE', LABEL: 'Frecuencia', UNITS: [
    {UNIT: 'Hz', LABEL: 'Hz - Hertz'},
    {UNIT: 'RPM', LABEL: 'RPM - Revoluciones por minuto'},
  ]},
  {MAGNITUDE: 'VEL', LABEL: 'Velocidad', UNITS: [
    {UNIT: 'm/s', LABEL: 'm/s - Metros por segundo'},
    {UNIT: 'm/h', LABEL: 'm/h - Metros por hora'},
    {UNIT: 'km/h', LABEL: 'km/h - Kilometros por hora'},
  ]},
  {MAGNITUDE: 'DIS', LABEL: 'Distancia', UNITS: [
    {UNIT: 'cm', LABEL: 'cm - Centímetros'},
    {UNIT: 'm', LABEL: 'm - Metros'},
    {UNIT: 'km', LABEL: 'km - Kilometros'},
    {UNIT: 'in', LABEL: 'in - Pulgada'},
    {UNIT: 'ft', LABEL: 'ft - Pies'},
    {UNIT: 'yd', LABEL: 'yd - Yarda'},
  ]}
];
@Component({
  selector: 'app-order-details',
  templateUrl: './order-details.component.html',
  styleUrls: ['./order-details.component.css']
})
export class OrderDetailsComponent implements OnInit {
  idOrder: number;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  workOrder: PreventiveWorkOrder | null;
  activator: Activator | null;

  MONTHS = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
  dayNames = ['Domingos', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábados'];
  tools = TOOLS_TMP;
  spareParts = SPARE_PARTS_TMP;
  magnitudes: Magnitudes[];
  orderPriorities: PriorityInterface[];
  staffArr: any[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    @Inject(DOCUMENT) private _document: Document,
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _snackBar: MatSnackBar,
    private _advicesService: AdvicesService,
    private _countActiService: CountersActivatorsService,
    private _funcService: FunctionsService,
    private _sysAdminService: SystemAdminService,
    private _docMangeService: DocumentManagementService,
  ) { 
    this.idOrder = 0;
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.workOrder = null;
    this.activator = null;
    this.magnitudes = MAGNITUDES;
    this.orderPriorities = [];
    this.staffArr = [];
  }

  ngOnInit(): void {
    this.idOrder = parseInt(this._data.idOrder);
    this.getOrderPriorities();
  }

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

      if(priorities.error){
        this.errorStr = priorities.msg;
        this.hasError = true;
        this.isLoading = false;
      }else{
        this.orderPriorities = priorities.response.order_priorities;
        this.getPreventiveOrder();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }
    }
  }

  async getPreventiveOrder(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idOrderEnc = await this._encService.encrypt(`${this.idOrder}`);
      let order: PreventiveWorkOrderResponse = await lastValueFrom(this._prevMaintService.getWorkOrder(
        idOrderEnc,
        idUser,
        1
      ));

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

      if(!this.hasError){
        this.workOrder = order.response;
        this.getActivator(this.workOrder.ACTIVADOR!);
      }else{
        this.isLoading = false;
      }
    }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 getActivator(idActivator: number){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idActEnc = await this._encService.encrypt(`${idActivator}`)!;

      let activator: ActivatorResponse = await lastValueFrom(this._countActiService.getActivator(
        idActEnc,
        idUser,
        1
      ));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        this.activator = activator.response;
        this.initStaffObj(this.workOrder!.OPERARIOS);
      }
    }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;
    }
  }

  getInstructionsArr(instructionsStr: string): string[]{
    let instructions = JSON.parse(instructionsStr);
    let instructionsArr: string[] = [];

    instructions.forEach((item: any) => {
      instructionsArr.push(item.INSTRUCCION)
    });
    
    return instructionsArr;
  }

  getDateText(date: string): string{
    let dateArr = date.split('-');
    return `${parseInt(dateArr[2])} de ${this.MONTHS[parseInt(dateArr[1]) - 1]} del ${dateArr[0]}`;
  }

  async initStaffObj(staffStr: string){
    let staffArr = JSON.parse(staffStr);
    let employeesFilt = staffArr.filter((item: any) => item.TYPE == 'EM');
    let teamsFilt = staffArr.filter((item: any) => item.TYPE == 'EQ');
    let subcontratistsFilt = staffArr.filter((item: any) => item.TYPE == 'SU');
    let objTmp: any[] = [];
    let employeesDec: number[] = [];

    for(const team of teamsFilt){
      let teamObj = {
        TYPE: '',
        NAME: '',
        SPEC: '',
        PERS: [] as any[],
      };

      let idDec = await this._encService.decrypt(team.ID);
      if(team.INFO == 'Desconocido'){
        teamObj.TYPE = 'EQUIPO DE TRABAJO';
        teamObj.NAME = `Desconocido (${idDec})`;
        teamObj.SPEC = 'Desconocido';
      }else{
        teamObj.TYPE = 'EQUIPO DE TRABAJO';
        teamObj.NAME = `${team.INFO.NOMBREEQUIPO} (${idDec})`;
        teamObj.SPEC = `${team.INFO.ESPECIALIDAD}`;

        let persArr: any[] = [];
        for(const item of team.INFO.PERSONAL){
          let idUsrDec = await this._encService.decrypt(item.IDUSUARIO);
          let idEmpDec = await this._encService.decrypt(item.IDEMPLEADO);
          employeesDec.push(parseInt(idEmpDec));

          persArr.push({
            NAME: `${item.NOMBREEMPLEADO} (${idUsrDec}) (${idEmpDec})`,
            ESPE: `${item.ESPECIALIDAD}`
          });
        }

        teamObj.PERS = persArr;
      }

      objTmp.push(teamObj);
    }

    for(const subcontratist of subcontratistsFilt){
      let subcontratistObj = {
        TYPE: '',
        NAME: '',
        SPEC: '',
        PERS: [] as any[],
      };

      let idDec = await this._encService.decrypt(subcontratist.ID);
      if(subcontratist.INFO == 'Desconocido'){
        subcontratistObj.TYPE = 'SUBCONTRATISTA';
        subcontratistObj.NAME = `Desconocido (${idDec})`;
        subcontratistObj.SPEC = 'Desconocido';
      }else{
        subcontratistObj.TYPE = 'SUBCONTRATISTA';
        subcontratistObj.NAME = `${subcontratist.INFO.RAZONSOCIAL} (${subcontratist.INFO.REGIMENFISCAL}) (${idDec})`;
        subcontratistObj.SPEC = `${subcontratist.INFO.ESPECIALIDAD}`;

        let persArr: any[] = [];
        for(const item of subcontratist.INFO.PERSONAL){
          let idUsrDec = await this._encService.decrypt(item.IDUSUARIO);
          let idEmpDec = await this._encService.decrypt(item.IDEMPLEADO);

          if(!employeesDec.includes(parseInt(idEmpDec))){
            employeesDec.push(parseInt(idEmpDec));
            persArr.push({
              NAME: `${item.NOMBREEMPLEADO} (${idUsrDec}) (${idEmpDec})`,
              ESPE: `${item.ESPECIALIDAD}`
            });
          }
        }

        subcontratistObj.PERS = persArr;
      }

      objTmp.push(subcontratistObj);
    }

    for(const employee of employeesFilt){
      let idDec = await this._encService.decrypt(employee.ID);
      if(!employeesDec.includes(parseInt(idDec))){
        objTmp.push({
          TYPE: 'EMPLEADO',
          NAME: `${employee.INFO.NOMBREEMPLEADO} (${idDec})`,
          SPEC: `${employee.INFO.ESPECIALIDAD}`,
        });
      }
    }
    
    this.staffArr = objTmp;
    this.isLoading = false;
  }

  getResourcesArr(resources: string): string[]{
    let resourcesArr = JSON.parse(resources);
    let arr: string[] = [];

    resourcesArr.forEach((item: any) => {
      if(item.TYPE == 'T' && item.ID != 'SH'){
        let tool = this.tools.filter(item2 => item2.ID == item.ID)[0];
        let strT = `${tool.NOMB}, ${item.REQ} ${tool.UNIT}(s) requerida(s).`;
        arr.push(strT);
      }else if(item.TYPE == 'S' && item.ID != 'SH'){
        let part = this.spareParts.filter(item2 => item2.ID == item.ID)[0];
        let strP = `${part.NOMB}, ${item.REQ} ${part.UNIT}(s) requerida(s).`;
        arr.push(strP);
      }
    });
    
    return arr;
  }

  getDocumentsArr(documentsStr: string): any[]{
    let documentsArr = JSON.parse(documentsStr);
    let docsArr: any[] = [];

    documentsArr.forEach((item: any) => {
      docsArr.push(item);
    });
    
    return docsArr;
  }

  async downloadDoc(doc: any){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let download = this._document.getElementById('download') as HTMLAnchorElement;

      let downloadToken = await lastValueFrom(this._advicesService.getDownloadToken(doc.id, idUser, 1));
      
      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = "";
      download.click();
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar(error.error.msg);
      }
    }
  }

  openSnackBar(msg: string){
    this._snackBar.open(msg, undefined, {
      duration: 2500,
    });
  }

  getTypeStr(type: string): string{
    if(type == 'CA'){
      return "Calendario";
    }else if(type == 'SI'){
      return "Síntoma";
    }else if(type == 'ME'){
      return "Medida";
    }else if(type == 'VA'){
      return "Valor";
    }
    
    return "";
  }

  getActivatorConfigStr(): string{
    let type = this.activator?.TIPOACTIVADOR == 'Calendario' ? 'CA' : '';
    type = this.activator?.TIPOACTIVADOR == 'Sintoma' ? 'SI' : type;
    type = this.activator?.TIPOACTIVADOR == 'Medida' ? 'ME' : type;
    type = this.activator?.TIPOACTIVADOR == 'Valor' ? 'VA' : type;
    
    let conditionsObj = JSON.parse(this.activator?.CONDICIONES! as string);
    let configStr = "";

    if(type == 'CA' || type == 'SI'){
      switch(conditionsObj.repeat){
        case "NR": 
          configStr += "La orden no se repite"; 
        break;
        case "AN":
          let repeatDateAn= new Date(conditionsObj.startDate);
          configStr += `La orden se repite anualmente el día ${repeatDateAn.getDate()} de ${this.MONTHS[repeatDateAn.getMonth()]}`;
        break;
        case "ME":
          let repeatDateMe = new Date(conditionsObj.startDate);
          configStr += `La orden se repite mensualmente los días ${repeatDateMe.getDate()}`;
        break;
        case "SE":
          let repeatDateSe = new Date(conditionsObj.startDate);
          configStr += `La orden se repite semanalmente los días ${this.dayNames[repeatDateSe.getDay()]}`;
        break;
        case "TD":
          let repeatDateTd = new Date(conditionsObj.startDate);
          configStr += `La orden se repite todos los días desde el ${repeatDateTd.getDate()} de ${this.MONTHS[repeatDateTd.getMonth()]} del ${repeatDateTd.getFullYear()}`;
        break;
        case "PE":
          let repeatDatePe = new Date(conditionsObj.startDate);
          let customRepeat = JSON.parse(conditionsObj.customRepeat);
          let repeatEvery = customRepeat.repeatEvery.split('|');

          switch(repeatEvery[1]){
            case "0":
              let intervalA = parseInt(repeatEvery[0]);
              if(intervalA > 1){
                configStr += `La orden se repite cada ${intervalA} días `;
              }else{
                configStr += `La orden se repite cada día `;
              }
            break;
            case "1":
              let intervalB = parseInt(repeatEvery[0]);
              if(intervalB > 1){
                configStr += `La orden se repite cada ${intervalB} semanas `;
              }else{
                configStr += `La orden se repite cada semana `;
              }
              
              let repeatOnVals = Object.values(customRepeat.repeatOn);
              let ind = 0;
              let cont = 0;
              let daysStr = "";

              repeatOnVals.forEach(val => {
                if(val){
                  daysStr += `${this.dayNames[ind]}, `;
                  cont++;
                }

                ind++;
              });

              daysStr = daysStr.substring(0, daysStr.length - 2);
              if(cont > 1){
                configStr += `los días ${daysStr} `;
              }else{
                configStr += `el día ${daysStr} `;
              }
            break;
            case "2":
              let intervalC = parseInt(repeatEvery[0]);
              if(intervalC > 1){
                configStr += `La orden se repite cada ${intervalC} meses `;
              }else{
                configStr += `La orden se repite cada mes `;
              }
            break;
            case "3":
              let intervalD = parseInt(repeatEvery[0]);
              if(intervalD > 1){
                configStr += `La orden se repite cada ${intervalD} años `;
              }else{
                configStr += `La orden se repite cada año `;
              }
            break;
          }

          configStr += `a partir del ${repeatDatePe.getDate()} de ${this.MONTHS[repeatDatePe.getMonth()]} del ${repeatDatePe.getFullYear()}, `;
          let endsAt = customRepeat.endsAt.split('|');
          if(endsAt[0] == 'N'){
            configStr += `sin parámetros de finalización.`;
          }else if(endsAt[0] == 'O'){
            let dateArr = endsAt[1].split('-');
            let dateObj = new Date(parseInt(dateArr[0]), parseInt(dateArr[1]), parseInt(dateArr[2]));
            configStr += `finaliza el día ${dateObj.getDate()} de ${this.MONTHS[dateObj.getMonth()]} del ${dateObj.getFullYear()}.`;
          }else if(endsAt[0] == 'A'){
            configStr += `finaliza después de ${endsAt[2]} repetici${parseInt(endsAt[2]) > 1 ? 'ones' : 'ón'}.`;
          }
        break;
      }
    }else{
      if(conditionsObj.customUnit != null){
        configStr += `Magnitud medida: ${conditionsObj.customMagnitude}. `;
        configStr += `Unidad configurada: ${conditionsObj.customUnit}. `;
      }else{
        let magnitude = this.magnitudes.filter(item => item.MAGNITUDE == conditionsObj.magnitude)[0];
        let unit = magnitude.UNITS.filter(item => item.UNIT == conditionsObj.unit)[0];

        configStr += `Magnitud medida: ${magnitude.LABEL}. `;
        configStr += `Unidad configurada: ${unit.LABEL}. `;
      }

      if(type == 'ME'){
        configStr += `Valor mínimo: ${this.formatNumbers(conditionsObj.minValue)}. `;
        configStr += `Valor máximo: ${this.formatNumbers(conditionsObj.maxValue)}`;
      }else{
        configStr += `Valor límite: ${this.formatNumbers(conditionsObj.limitValue)}. `;
        if(conditionsObj.comparison == 'AC'){
          configStr += "Comparación con el valor acumulado.";
        }else{
          configStr += "Comparación con el último valor reportado.";
        }
      }
    }
    
    return configStr;
  }

  formatNumbers(number: string | number): string{
    let numberStr = `${number}`;
    let numberArr = numberStr.split('').reverse();

    let num = "";
    for(let i = 0; i < numberArr.length - 1; i++){
      let res = i % 3;
      if(res == 2){
        num += `${numberArr[i]},`;
      }else{
        num += `${numberArr[i]}`;
      }
    }

    num += `${numberArr[numberArr.length - 1]}`;
    let numFn = num.split('').reverse().join('');
    
    return numFn;
  }

  orderDate(date: string): string{
    return this._funcService.orderDate(date)!;
  }

  getAnalysisStr(analysisStr: string): Array<Array<string>>{
    let analysisObj = JSON.parse(analysisStr);
    let teamsConf = analysisObj.teamsConf;
    let teamsKeys = Object.keys(teamsConf);
    let arrFn: Array<Array<string>> = [];

    /*teamsKeys.forEach(key => {
      let team = this.teams.filter(item => item.ID == key)[0];
      let teamConf = teamsConf[key];
      let arrTmp: Array<string> = [];
      let cont = 1;

      teamConf.forEach((item: any) => {
        arrTmp.push(`Usuario ${cont} del equipo ${team.NOMB} - ${team.ESP}, requerido ${item.HOURS} hora(s). Costo por hora: $${item.COST}.`);
        cont++;
      });

      arrFn.push(arrTmp);
    });

    let toolsTmp: Array<string> = [];
    analysisObj.toolsConf.forEach((tool: any) => {
      toolsTmp.push(`${tool.NOM}, ${tool.REQ} ${tool.UNIT}(s) requerida(s) - Costo unitario: $${tool.COSTUNIT.toFixed(2)}, Costo total: $${tool.COSTTOTAL.toFixed(2)}.`);
    });*/

    arrFn.push([]);
    let sparePartsTmp: Array<string> = [];
    /*analysisObj.sparePartsConf.forEach((part: any) => {
      toolsTmp.push(`${part.NOM}, ${part.REQ} ${part.UNIT}(s) requerida(s) - Costo unitario: $${part.COSTUNIT.toFixed(2)}, Costo total: $${part.COSTTOTAL.toFixed(2)}.`);
    });*/

    arrFn.push(sparePartsTmp);
    return arrFn;
  }

  getPriorityStr(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "-";
    
    let priority = priorityFiltered[0];
    return priority.label;
  }

  getFontColor(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "rgb(0, 0, 0)";
    
    let priority = priorityFiltered[0];
    return priority.color;
  }

  async printOrderDetails(){
    try{
      this.openSnackBar('Generando PDF...');

      let idUser = localStorage.getItem('idusuario')!;
      let idOrderEnc = await this._encService.encrypt(`${this.idOrder}`);

      let orderDetails = await lastValueFrom(this._prevMaintService.printOrderDetails(
        idOrderEnc,
        idUser,
        1
      ));

      let idFileEnc = await this._encService.encrypt(orderDetails.response.fileID);
      let download = this._document.getElementById(`download`) as HTMLAnchorElement;

      let downloadToken = await lastValueFrom(this._docMangeService.getDownloadToken(
        idFileEnc,
        idUser,
        1
      ));

      download.href = `http://git.ittec.mx/sam/public/api/download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = orderDetails.response.fileID;
      download.click();
    }catch(error: any){
      if(error.error == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this.openSnackBar('Ocurrió un error inesperado.');
      }
    }
  }
}
