import { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { PreventiveOrderSimulation, PreventiveOrderSimulationResponse } from '../../../../interfaces/preventive-order-simulation.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DOCUMENT } from '@angular/common';
import { EncService } from '../../../../services/enc.service';
import { PreventiveMaintenanceService } from '../../../../services/preventive-maintenance.service';
import { DocumentManagementService } from '../../../../services/document-management.service';
import { lastValueFrom } from 'rxjs';
import { ResourcesService } from '../../../../services/resources.service';
import { apiTemp } from '../../../../../environments/environment.prod';

interface ToolInfo{
  ID: string;
  NOMB: string;
  MODE: string;
  CANTDISP: number;
  TYPE: string;
  UNIT: string;
}
interface ExecutionStep{
  id: number;
  icon: string;
  label: string;
  isMain: boolean;
}
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-simulation-dialog',
    templateUrl: './simulation-dialog.component.html',
    styleUrl: './simulation-dialog.component.css',
    standalone: false
})
export class SimulationDialogComponent implements OnInit {
  idOrder: number;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  orderSimulation: PreventiveOrderSimulation | null;

  tools: ToolInfo[];
  spareParts: ToolInfo[];

  starting: boolean;
  eventIcon: string;
  collectResources: boolean;
  steps: ExecutionStep[];
  simulating: boolean;
  includeCharge: boolean;
  hasBeenSimulated: boolean;

  @ViewChild('simulationContainer', {static: false}) simulationContainer?: ElementRef;
  private scrollContainer: any;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    @Inject(DOCUMENT) private _document: Document,
    private _encService: EncService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _docMangeService: DocumentManagementService,
    private _resourcesServices: ResourcesService,
  ){
    this.idOrder = 0;
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.orderSimulation = null;
    this.tools = TOOLS_TMP;
    this.spareParts = SPARE_PARTS_TMP;
    this.starting = false;
    this.eventIcon = "";
    this.collectResources = false;
    this.steps = [];
    this.simulating = false;
    this.includeCharge = false;
    this.hasBeenSimulated = false;

    this.scrollContainer = this.simulationContainer?.nativeElement;
  }

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

  async getOrderSimulation(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idOrderEnc = await this._encService.encrypt(`${this.idOrder}`);
      let simulation: PreventiveOrderSimulationResponse = await lastValueFrom(this._prevMaintService.getMaintenanceSimulation(
        idOrderEnc,
        idUser,
        1
      ));

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

      if(!this.hasError){
        this.orderSimulation = simulation.response;
      }
      
      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;
    }
  }

  startSimulation(){
    this.steps = [];
    this.makeSimulation();
  }

  async makeSimulation(){
    this.hasBeenSimulated = false;
    this.simulating = true;
    this.starting = true;
    await this.timeout(2500);
    this.starting = false;
    let idStep = 1;

    if(this.orderSimulation?.TIPOACTIVADOR == 'Calendario'){
      let step: ExecutionStep = {
        id: idStep,
        icon: 'event',
        label: ` Activación de la ejecución de la órden #${this.idOrder}`,
        isMain: true
      };

      this.steps.push(step);
    }else if(this.orderSimulation?.TIPOACTIVADOR == 'Sintoma'){
      let step: ExecutionStep = {
        id: idStep,
        icon: 'sensors',
        label: ` Activación de la ejecución de la órden #${this.idOrder}`,
        isMain: true
      };

      this.steps.push(step);
    }else if(this.orderSimulation?.TIPOACTIVADOR == 'Medida'){
      let step: ExecutionStep = {
        id: idStep,
        icon: 'device_thermostat',
        label: ` Activación de la ejecución de la órden #${this.idOrder}`,
        isMain: true
      };

      this.steps.push(step);
    }else if(this.orderSimulation?.TIPOACTIVADOR == 'Valor'){
      let step: ExecutionStep = {
        id: idStep,
        icon: 'speed',
        label: ` Activación de la ejecución de la órden #${this.idOrder}`,
        isMain: true
      };

      this.steps.push(step);
    }

    await this.timeout(750);
    this.scrollToBottom();
    this.collectResources = true;
    idStep++;

    let stepTwo: ExecutionStep = {
      id: idStep,
      icon: 'fact_check',
      label: 'Recolección de los materiales necesarios',
      isMain: true
    }

    this.steps.push(stepTwo);
    this.scrollToBottom();
    await this.timeout(750);
    idStep++;
    
    let resources = JSON.parse(this.orderSimulation?.RECURSOS!);
    let noResources = 0;
    let cont = 1;
    
    for(const resource of resources){
      let id = resource.ID;
      if(id == 'SH'){
        noResources++;
      }else{
        let type = resource.TYPE;
        if(type == 'S'){
          let part = this.spareParts.filter(item2 => item2.ID == id);
          if(part.length > 0){
            let subStep: ExecutionStep = {
              id: idStep,
              icon: 'remove',
              label: `${part[0].NOMB}, ${resource.REQ} ${part[0].UNIT}(s) requerida(s).`,
              isMain: false
            };
  
            this.steps.push(subStep);
          }else{
            let subStep: ExecutionStep = {
              id: idStep,
              icon: 'remove',
              label: `1 Repuesto requerido.`,
              isMain: false
            };
  
            this.steps.push(subStep);
          }
        }else{
          let tool = this.tools.filter(item2 => item2.ID == id);
          if(tool.length > 0){
            //REVISAR PENDIENTE
            let subStep: ExecutionStep = {
              id: idStep,
              icon: 'remove',
              label: `${tool[0].NOMB}, ${resource.REQ} ${tool[0].UNIT}(s) requerida(s).`,
              isMain: false
            };
  
            this.steps.push(subStep);
          }else{
            let subStep: ExecutionStep = {
              id: idStep,
              icon: 'remove',
              label: `1 Herramienta requerida.`,
              isMain: false
            };
  
            this.steps.push(subStep);
          }
        }

        this.scrollToBottom();
        idStep++;

        if(cont == resources.length){
          await this.timeout(750);
        }else{
          await this.timeout(500);
        }
      }

      cont++;
    }

    if(noResources > 1){
      let resStep: ExecutionStep = {
        id: idStep,
        icon: 'remove',
        label: 'No se requieren materiales',
        isMain: false
      };

      this.steps.push(resStep);
      this.scrollToBottom();
      await this.timeout(750);
      idStep++;
    }

    let startArr = this.orderSimulation?.FECHAINICIO.split(' ')!;
    let startHourArr = startArr[1].split(':');
    let startHour = parseInt(startHourArr[0]);
    let startPeriod = startHour < 12 ? 'AM' : 'PM';
    
    startHour = startHour > 12 ? startHour - 12 : startHour;
    
    let stepThree: ExecutionStep = {
      id: idStep,
      icon: 'play_arrow',
      label: `Inicio de las actividades de mantenimiento, ${startHour}:${startHourArr[1]} ${startPeriod}`,
      isMain: true
    } 

    this.steps.push(stepThree);
    this.scrollToBottom();
    await this.timeout(750);
    idStep++;

    let instructions = JSON.parse(this.orderSimulation?.INSTRUCCIONES!);
    cont = 1;
    for(const instruction of instructions){
      let insStep: ExecutionStep = {
        id: idStep,
        icon: 'remove',
        label: instruction.INSTRUCCION,
        isMain: false
      };

      this.steps.push(insStep);
      this.scrollToBottom();

      if(cont == instructions.length){
        await this.timeout(750);
      }else{
        await this.timeout(500);
      }
      
      cont++;
      idStep++;
    }
    
    let intHourTot = Math.trunc(this.orderSimulation?.TIETOTEST!);
    let floatMinutes = this.orderSimulation?.TIETOTEST! - intHourTot;
    let calcMinutes = floatMinutes * 60;
    let minutesInt = Math.round(calcMinutes);

    let endHour = startHour + intHourTot;
    let startMinutesInt = parseInt(startHourArr[1]);
    let endMinutes = minutesInt + startMinutesInt;
    let extraHours = Math.trunc(endMinutes / 60);
    let minutesTot = endMinutes - (extraHours * 60);
    
    let endPeriod = startPeriod;
    let endMinutesStr = minutesTot < 10 ? `0${minutesTot}` : `${minutesTot}`;
    endHour += extraHours;

    let extraDays = Math.trunc(endHour / 24);
    endHour = endHour - (extraDays * 24);

    if(endHour >= 12 && endPeriod == 'PM'){
      if(endHour == 12){
        endHour = 0;
      }else{
        endHour = endHour - 12;
      }

      endPeriod = 'AM';
      extraDays++;
    }else if(endHour >= 12 && endPeriod == 'AM'){
      if(endHour > 12){
        endHour = endHour - 12;
      }

      endPeriod = 'PM';
    }
    
    let fourLabel = `Fin de las actividades de mantenimiento, ${endHour}:${endMinutesStr} ${endPeriod}`;
    if(extraDays > 0){
      fourLabel += `, ${extraDays} día(s) después`;
    }

    let stepFour: ExecutionStep = {
      id: idStep,
      icon: 'stop',
      label: fourLabel,
      isMain: true
    } 

    this.steps.push(stepFour);
    this.scrollToBottom();
    await this.timeout(750);
    idStep++;

    if(this.includeCharge){
      let stepFive: ExecutionStep = {
        id: idStep,
        icon: 'attach_money',
        label: 'Resultado del costo de los operadores de mantenimiento',
        isMain: true
      }
  
      this.steps.push(stepFive);
      this.scrollToBottom();
      await this.timeout(750);
      idStep++;

      let analisisObj = JSON.parse(this.orderSimulation?.ANALISIS!);
      let teamsConf = analisisObj.teamsConf;
      let keys = Object.keys(teamsConf);
      let personalTotalCost = 0;
  
      for(const key of keys){
        let item = teamsConf[key];
        let idDec = await this._encService.decrypt(item.ID);

        let itemLabel = `${item.NAME} (${idDec}), ${item.CANT} operarios requeridos, costo por hora: $${item.PREC}, horas requeridas: ${item.HORA}, costo total por operador: $${item.TOTA}`;
        let usrStep: ExecutionStep = {
          id: idStep,
          icon: 'remove',
          label: itemLabel,
          isMain: false
        };
  
        this.steps.push(usrStep);
        this.scrollToBottom();
        await this.timeout(500);
        idStep++;

        personalTotalCost += item.TOTA * item.CANT;
      }
  
      let stepSix: ExecutionStep = {
        id: idStep,
        icon: 'payments',
        label: `Costo total de los operadores: $${personalTotalCost}`,
        isMain: true
      };
  
      this.steps.push(stepSix);
      this.scrollToBottom();
      await this.timeout(750);
      idStep++;

      console.log(analisisObj);
      //PENDIETE REVISAR
  
      /*let stepSeven: ExecutionStep = {
        id: idStep,
        icon: 'attach_money',
        label: `Resultado del costo de las herramientas y refacciones`,
        isMain: true
      };
  
      this.steps.push(stepSeven);
      this.scrollToBottom();
      await this.timeout(750);
      idStep++;
      
      let toolsConf = analisisObj.toolsConf;
      let toolsTotalCost = 0;

      for(const tool of toolsConf){
        let toolLabel = `${tool.NOM} - ${tool.REQ} ${tool.UNIT}(s) requerida(s), costo unitario: $${tool.COSTUNIT}, costo total: $${tool.COSTTOTAL}`;
        let toolStep: ExecutionStep = {
          id: idStep,
          icon: 'remove',
          label: toolLabel,
          isMain: false
        };
  
        toolsTotalCost += tool.COSTTOTAL;
  
        this.steps.push(toolStep);
        this.scrollToBottom();
        await this.timeout(500);
        idStep++;
      }

      let sparePartsConf = analisisObj.sparePartsConf;

      for(const part of sparePartsConf){
        let partLabel = `${part.NOM} - ${part.REQ} ${part.UNIT}(s) requerida(s), costo unitario: $${part.COSTUNIT}, costo total: $${part.COSTTOTAL}`;
        let partStep: ExecutionStep = {
          id: idStep,
          icon: 'remove',
          label: partLabel,
          isMain: false
        };
  
        toolsTotalCost += part.COSTTOTAL;
  
        this.steps.push(partStep);
        this.scrollToBottom();
        await this.timeout(500);
        idStep++;
      }
  
      let stepEight: ExecutionStep = {
        id: idStep,
        icon: 'payments',
        label: `Costo total de las herramientas y refacciones: $${toolsTotalCost}`,
        isMain: true
      };
  
      this.steps.push(stepEight);
      this.scrollToBottom();
      await this.timeout(750);
      idStep++;
  
      let stepNine: ExecutionStep = {
        id: idStep,
        icon: 'payments',
        label: `Costo total de la operación: $${personalTotalCost + toolsTotalCost}`,
        isMain: true
      };
  
      this.steps.push(stepNine);
      this.scrollToBottom();*/
    }else{
      /*********************************************************************** */
      let stepFive: ExecutionStep = {
        id: idStep,
        icon: 'engineering',
        label: 'Operadores de mantenimiento',
        isMain: true
      }

      this.steps.push(stepFive);
      this.scrollToBottom();
      await this.timeout(750);

      let analisisObj = JSON.parse(this.orderSimulation?.ANALISIS!);
      let teamsConf = analisisObj.teamsConf;
      let keys = Object.keys(teamsConf);

      for(const key of keys){
        let item = teamsConf[key];
        let idDec = await this._encService.decrypt(item.ID);

        let itemLabel = `${item.NAME} (${idDec}), ${item.CANT} operadores requeridos.`;
        let usrStep: ExecutionStep = {
          id: idStep,
          icon: 'remove',
          label: itemLabel,
          isMain: false
        };
  
        this.steps.push(usrStep);
        this.scrollToBottom();
        await this.timeout(500);
        idStep++;

        if(item.ITEMS != null){
          for(const user of item.ITEMS){
            let usrLabel = `${user.NAME} (${user.ID}) - Subcontratista`;
            let usrStep: ExecutionStep = {
              id: idStep,
              icon: '',
              label: usrLabel,
              isMain: false
            };
  
            this.steps.push(usrStep);
            this.scrollToBottom();
            await this.timeout(500);
            idStep++;
          }
        }
      }
    }

    this.simulating = false;
    this.hasBeenSimulated = true;

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

      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('id_order', idOrderEnc);
      formData.append('content', JSON.stringify(this.steps));

      await lastValueFrom(this._prevMaintService.saveOrderSimulation(formData));
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesServices.openSnackBar(error.error.msg);
      }
    }
  }

  async timeout(ms: number): Promise<void>{
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  private scrollToBottom(): void {
    setTimeout(() => {
      let scrollContainer = this.simulationContainer?.nativeElement as HTMLElement;
      
      scrollContainer.scroll({
        top: scrollContainer.scrollHeight,
        left: 0,
        behavior: 'smooth'
      });
    }, 1);
  }

  async printPDF(){
    try{
      this._resourcesServices.openSnackBar('Generando PDF...');
      let idUser = localStorage.getItem('idusuario')!;
      let idOrderEnc = await this._encService.encrypt(`${this.idOrder}`);
      let orderSimulation = await lastValueFrom(this._prevMaintService.printOrderSimulation(
        idOrderEnc,
        idUser,
        1
      ))

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

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

      download.href = `${apiTemp}download-file/${downloadToken.response.TOKEN}/${idUser}/1`;
      download.download = orderSimulation.response.fileID;
      download.click();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesServices.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesServices.openSnackBar(error.error.msg);
      }
    }
  }
}
