import { Component, DoCheck, OnInit, ViewChild } from '@angular/core';
import { ProcessesService } from 'src/app/services/processes.service';
import { ModalController } from '@ionic/angular';
import { ActivatedRoute, NavigationEnd, NavigationExtras, Router } from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';
import { LoginUserRespose } from 'src/app/models/user.model';
import { ExpedientsPage } from 'src/app/shared/gabinete-digital/expedients/expedients.page';
import { PendentesPage } from 'src/app/shared/gabinete-digital/pendentes/pendentes.page';
import { EventsToApprovePage } from 'src/app/shared/gabinete-digital/events-to-approve/events-to-approve.page';
import { DespachoStore } from 'src/app/store/despacho-store.service';
import { EventoAprovacaoStore } from 'src/app/store/eventoaprovacao-store.service';
import { ExpedienteGdStore } from 'src/app/store/expedientegd-store.service';
import { PendentesStore } from 'src/app/store/pendestes-store.service';
import { PedidosStore } from 'src/app/store/pedidos-store.service';
import { DespachosprStore } from 'src/app/store/despachospr-store.service';

import { removeDuplicate } from 'src/plugin/removeDuplicate.js'
import { WaitForDomService } from 'src/app/services/dom/wait-for-dom.service';
import { TotalDocumentStore } from 'src/app/store/total-document.service';
import { DeplomasStore } from 'src/app/store/deplomas.service';
import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe';
//import { NotificationsService } from 'src/app/services/notifications.service';
import { DespachoService } from 'src/app/Rules/despacho.service';
import { ChangeProfileService } from 'src/app/services/change-profile.service';
import { PermissionService } from 'src/app/services/worker/permission.service';
import { ThemeService } from 'src/app/services/theme.service'


import { SqliteService } from '../../services/sqlite.service';
import { Platform } from '@ionic/angular';
import { BackgroundService } from 'src/app/services/background.service';
import { SortService } from 'src/app/services/functions/sort.service';
import { DataService } from 'src/app/services/data.service';

@Component({
  selector: 'app-gabinete-digital',
  templateUrl: './gabinete-digital.page.html',
  styleUrls: ['./gabinete-digital.page.scss'],
})

export class GabineteDigitalPage implements OnInit, DoCheck {

  segment: string;
  segmentVista: string;
  showLoader: boolean;
  public profile: string;

  allProcessesList: any = new Array();
  skeletonLoader: boolean;

  count_exp_dailywork = 0;
  count_exp_pr = 0
  count_desp_dailywork = 0;
  count_desp_pending = 0;
  count_par_dailywork = 0;
  count_par_pending = 0;
  count_def_dailywork = 0;
  count_def_pending = 0;
  count_exp_pp: string;
  count_exp_pd: string;
  count_dip_apr: string;
  count_dip_as_pr = 0
  count_dip_pv = 0;
  count_dip_as = 0;
  count_de_pr = 0;
  count_ev_apr = 0;
  count_ev_md = 0;
  count_total_pending = 0;
  count_desp_pr_active = 0;
  count_all_processes = 0;

  selectedElement = "";

  desktopComponent: any = {
    showEventList: false,
    showExpediente: false,
  }

  showAllProcesses = false;
  showEventsToApprove = false;
  showEmptyContainer = false;
  showExpedients = false;
  showExpedientesPr = false;
  showPedidos = false;
  showDespachos = false;
  showDespachosPr = false;
  showPendentes = false;
  showDiplomas = false;
  showDiplomasAssinar = false;
  showExpedientDetail = false;
  showSignedDiploma = false;
  emptyTextDescription = 'Sem opção selecionada';

  serialNumber: string;

  loggeduser: LoginUserRespose;
  mdgpr = "MDGPR";
  pr = "PR";

  hideRefreshBtn = true;
  hideInMobile = true;

  expedientegbstore = ExpedienteGdStore;
  pendentesstore = PendentesStore;
  despachoStore = DespachoStore;
  eventoaprovacaostore = EventoAprovacaoStore;
  pedidosstore = PedidosStore;
  // expedienteprstore = ExpedienteprStore;
  despachoprstore = DespachosprStore;
  totalDocumentStore = TotalDocumentStore
  deplomasStore = DeplomasStore
  //
  // pipe

  customTaskPipe = new CustomTaskPipe()

  @ViewChild(ExpedientsPage) expedientesPage: ExpedientsPage;
  @ViewChild(PendentesPage) pendentesListPage: PendentesPage;
  @ViewChild(EventsToApprovePage) eventsToApprove: EventsToApprovePage;

  constructor(
    private processesbackend: ProcessesService,
    private modalController: ModalController,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    authService: AuthService,
    public p: PermissionService,
    public waitForDomService: WaitForDomService,
    //private notificationsService: NotificationsService,
    private despachoRule: DespachoService,
    private sqliteservice: SqliteService,
    private platform: Platform,
    private changeProfileService: ChangeProfileService,
    private backgroundservice: BackgroundService,
    public ThemeService: ThemeService,
    private sortService: SortService,
    private dataService: DataService,
  ) {

    this.loggeduser = authService.ValidatedUser;
    window.onresize = (event) => {
      // if not mobile remove all component
      if (window.innerWidth < 701) {
        this.modalController.dismiss();
        this.segmentVista = "listview";
      }
      else {
        this.segmentVista = "boxview";
      }
    };
    this.checkRoutes();

  }

  ngDoCheck(): void {
    /* if( window.innerWidth < 701) {
      this.segmentVista = "listview";
    }
    else{
      this.segmentVista = "boxview";
    } */
  }

  closeAllDesktopComponent() {
    this.desktopComponent = {
      showEventList: false,
      showExpediente: false
    }
  }


  ngOnInit() {

    if (window.innerWidth < 701) {
      this.segmentVista = "listview";
    }
    else {
      this.segmentVista = "boxview"
    }

    const pathname = window.location.pathname
    this.router.events.forEach((event) => {
      if (event instanceof NavigationEnd && event.url == pathname) {

        this.waitForDomService.selector({
          selector: 'app-gabinete-digital ion-content .aside-wrapper',
          callback: () => {
            this.checkRoutes();
            this.LoadCounts();
          }
        })
      }
    });

    this.hideRefreshButton();

    this.waitForDomService.selector({
      selector: 'app-gabinete-digital ion-content .aside-wrapper',
      callback: () => {
        this.loadAllProcesses();
      }
    })

    this.backgroundservice.registerBackService('Online', () => {
      this.loadAllProcesses();
    });


  }

  async loadAllProcesses() {
    this.LoadCounts();
  }

  addProcessToDB(data) {
    this.platform.ready().then(() => {
      if (this.platform.is('desktop') || this.platform.is('mobileweb')) {

      } else {
        data.forEach(element => {

          let process = {
            "serialNumber": element.serialNumber,
            "workflowInstanceFolio": element.workflowInstanceFolio,
            "Documents": element.Documents,
            "actions": element.actions,
            "activityInstanceName": element.activityInstanceName,
            "formURL": element.formURL,
            "originator": element.originator,
            "taskStartDate": element.taskStartDate,
            "totalDocuments": element.totalDocuments,
            "workflowDisplayName": element.workflowDisplayName,
            "workflowID": element.workflowID,
            "workflowInstanceDataFields": element.workflowInstanceDataFields,
            "workflowInstanceID": element.workflowInstanceID,
            "workflowName": element.workflowName
          }

          this.sqliteservice.addProcess(process);
        });
      }
    });
  }

  getAllProcessFromDB() {

    this.hideRefreshButton();

    this.sqliteservice.getAllProcess().then((allprocess: any[]) => {
      allprocess.forEach(element => {
        let date = new Date(element.taskStartDate);
        date.setMonth(date.getMonth() + 1);
        let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

        var workflowInstanceDataFields = JSON.parse(element.workflowInstanceDataFields);

        let task = {
          "SerialNumber": element.serialNumber,
          "Folio": workflowInstanceDataFields.Subject,
          "Senders": workflowInstanceDataFields.Sender,
          "CreateDate": taskDate,
          "DocumentURL": workflowInstanceDataFields.ViewerRequest,
          "Remetente": workflowInstanceDataFields.Remetente,
          "DocumentsQty": element.totalDocuments,
          "DocId": workflowInstanceDataFields.DispatchDocId,
          "FolderID": workflowInstanceDataFields.FolderID,
          "WorkflowName": element.workflowDisplayName,
          "activityInstanceName": element.activityInstanceName,
          "Status": workflowInstanceDataFields.Status,
          "Agenda": workflowInstanceDataFields.Agenda,
          "customDate": this.setFormatDate(new Date(workflowInstanceDataFields.StartDate), new Date(workflowInstanceDataFields.EndDate), workflowInstanceDataFields.IsAllDayEvent),
        }

        this.allProcessesList.push(task);
        this.allProcessesList = removeDuplicate(this.allProcessesList)
        this.allProcessesList = this.sortService.sortDate(this.allProcessesList, 'CreateDate')

      });
      console.log("All process from db ", allprocess)
    })
  }

  sortArrayISODate(myArray: any) {
    return myArray.sort(function (a, b) {
      return (a.CreateDate < b.CreateDate) ? -1 : ((a.CreateDate > b.CreateDate) ? 1 : 0);
    });
  }

  setFormatDate(start: any, end: any, allday: boolean) {
    let customDate;

    const totalSeconds = Math.floor((end - (start)) / 1000);;
    const totalMinutes = Math.floor(totalSeconds / 60);
    const totalHours = Math.floor(totalMinutes / 60);
    const totalDays = Math.floor(totalHours / 24);

    //const hours = totalHours - (totalDays * 24);
    //const minutes = totalMinutes - (totalDays * 24 * 60) - (hours * 60);
    // const seconds = totalSeconds - (totalDays * 24 * 60 * 60) - (hours * 60 * 60) - (minutes * 60);

    // let diffDays = totalDays;
    // let diffMinutes = minutes;

    if (totalDays == 0) {
      if (allday) {
        customDate = this.getCustomDate(start) + ", " + this.getCustomHours(start) + " (todo dia)";
        console.log(customDate);
        return customDate;
      }
      else {
        //customDate = this.getCustomDate(start)+","+this.getCustomHours(start)+" ("+minutes+" mins)";
        customDate = this.getCustomDate(start) + ", " + this.getCustomHours(start) + " | " + this.getCustomHours(end);
        return customDate;
      }
    }
    else {
      customDate = this.getCustomDate(start) + "," + this.getCustomHours(start) +
        " (termina:" + this.getCustomDate(end) + "," + this.getCustomHours(end) + ")";
      return customDate;
    }
  }

  getCustomDate(thedate: Date) {
    return thedate.getDate() + "/" +
      (thedate.getMonth() + 1) + "/" +
      thedate.getFullYear();
  }

  getCustomHours(thedate: Date) {
    return thedate.getHours() + ":" +
      thedate.getMinutes();
  }

  goToProcess(serialNumber: string, workflowName: string, activityName: string) {
    if (workflowName == 'Despacho') {
      if (activityName == 'Tarefa de Despacho' || activityName == 'Concluir Despacho') {
        this.router.navigate(['/home/gabinete-digital/despachos', serialNumber, 'gabinete-digital']);
      }
    }
    else if (workflowName == 'Despacho do Presidente da República') {
      if (activityName == 'Tarefa de Despacho' || activityName == 'Concluir Despacho') {
        this.router.navigate(['/home/gabinete-digital/despachos-pr', serialNumber, 'gabinete-digital']);
      }
      else if (activityName == 'Revisar Diploma' || activityName == 'Assinar Diploma') {
        this.router.navigate(['/home/gabinete-digital/diplomas', serialNumber, 'gabinete-digital']);
      }
      else if (activityName == 'Diploma Assinado') {
        this.router.navigate(['/home/gabinete-digital/diplomas-assinar', serialNumber, 'gabinete-digital']);
      }
    }
    else if (workflowName == 'Pedido de Parecer' || workflowName == 'Pedido de Deferimento') {
      this.router.navigate(['/home/gabinete-digital/pedidos', serialNumber, 'gabinete-digital']);
    }
    else if (workflowName == 'Expediente') {
      this.router.navigate(['/home/gabinete-digital/expediente', serialNumber, 'gabinete-digital']);
    }
    else if (workflowName == 'Expediente' && this.loggeduser.Profile == 'PR') {
      this.router.navigate(['/home/gabinete-digital/expedientes-pr', serialNumber, 'gabinete-digital']);
    }
    else if (workflowName == "Pedido de Parecer do Presidente") {
      this.router.navigate(['/home/gabinete-digital/pedidos', serialNumber, 'gabinete-digital']);
    }
    /* else if (workflowName == "Expediente") {
      this.router.navigate(['/home/gabinete-digital/pedidos',serialNumber,'gabinete-digital']);
    } */
    else if (workflowName == 'Agenda Pessoal PR' || workflowName == 'Agenda Oficial PR' || workflowName == 'Agenda Oficial MDGPR' || workflowName == 'Agenda Pessoal MDGPR') {
      this.router.navigate(['/home/gabinete-digital/event-list/approve-event', serialNumber, 'gabinete-digital']);
    }
    else {
      console.log('cant find page for this task')
    }
  }

  onSegmentVistaChange() {

  }

  checkUser() {
    this.selectedElement = 'allProcessesTag';
    this.showAllProcesses = true;
    /* switch(this.loggeduser.Profile){
      case 'MDGPR':
        this.showExpedients = true;
        break;
      case 'PR':
        this.showExpedientesPr = true;
        break;
    } */
  }

  hideRefreshButton() {
    window.onresize = (event) => {
      if (window.innerWidth < 701) {
        this.hideRefreshBtn = false;
        this.hideInMobile = false;
        this.segmentVista = "listview";
      }
      else {
        this.hideRefreshBtn = true;
        this.hideInMobile = true;
        this.segmentVista = "boxview";
      }
    }
    if (window.innerWidth < 701) {
      this.hideRefreshBtn = false;
      this.hideInMobile = false;
      this.segmentVista = "listview";
    }
    else {
      this.hideRefreshBtn = true;
      this.hideInMobile = true;
      this.segmentVista = "boxview";
    }
  }

  checkRoutes() {
    this.closeAllDesktopComponents();
    if (this.router.url == '/home/gabinete-digital?processes=true') {
      this.openAllProcessesPage();
      this.selectedElement = 'allProcessesTag';
    }
    if (this.router.url == '/home/gabinete-digital?eventos=true') {
      this.openEventsToApprovePage();
      this.selectedElement = 'approval';
    }
    else if (this.router.url == '/home/gabinete-digital?expedientes=true') {
      this.openExpedientListPage();
      if (this.loggeduser.Profile == 'MDGPR') {
        this.selectedElement = 'Correspondence';
      }
      else {
        this.selectedElement = 'Expediente Presidente'
      }
    }
    else if (this.router.url == '/home/gabinete-digital?pendentes=true') {
      this.openPendentesPage('');
      this.selectedElement = 'Pending';
    }
    else if (this.router.url == '/home/gabinete-digital?despachos=true') {
      this.openDespachosPage('');
      this.selectedElement = 'Dispatches';
    }
    else if (this.router.url == '/home/gabinete-digital?pedidos=true') {
      this.openPedidosPage('parecer');
      this.selectedElement = 'RequestsForOpinion';
    }
    else if (this.router.url == '/home/gabinete-digital?expedientespr=true') {
      this.openExpedientesPrPage();
      this.selectedElement = 'Expediente Presidente'
    }
    else if (this.router.url == '/home/gabinete-digital?despachospr=true') {
      this.openDespachosPrPage('');
      this.selectedElement = 'DispatchesPr'
    }
    else if (this.router.url == '/home/gabinete-digital?diplomas=true') {
      this.openDiplomasPage('validar');
      this.selectedElement = 'DiplomasPorValidar';
    }
    else if (this.router.url == '/home/gabinete-digital?diplomasassinar=true') {
      this.openDiplomasAssinarPage();
      this.selectedElement = 'DiplomasAssinar';
    }
    else if (this.router.url == '/home/gabinete-digital?parecer=true') {
      this.openPedidosPage('parecer')
    }
    else if (this.router.url == '/home/gabinete-digital?deferimento=true') {
      this.openPedidosPage('deferimento')
    }
    else {
      this.checkUser();
    }
  }

  closeAllDesktopComponents() {
    this.showEmptyContainer = false;
    this.showAllProcesses = false;
    this.showEventsToApprove = false;
    this.showExpedients = false;
    this.showPedidos = false;
    this.showDespachos = false;
    this.showDespachosPr = false;
    this.showPendentes = false;
    this.showDiplomas = false;
    this.showDiplomasAssinar = false;
    this.showExpedientesPr = false;
    this.showExpedientDetail = false;
    this.showSignedDiploma = false
  }

  async LoadCounts() {

    this.showLoader = true;

    let allPreocesses_ = await this.processesbackend.GetTasksList("", false).toPromise();
    let allProcessesList = allPreocesses_;

    allProcessesList = allProcessesList.filter(element => element.activityInstanceName != 'Conhecimento')

    if (!this.p.userRole(['PR'])) {
      allProcessesList = allProcessesList.filter(element => element.activityInstanceName != 'Assinar Diplomas')
    } else if (this.p.userRole(['PR'])) {
      allProcessesList = allProcessesList.filter(element => element.activityInstanceName != 'Diploma Assinado')
    }

    this.addProcessToDB(allProcessesList)
    this.skeletonLoader = true;

    this.allProcessesList = [];

    allProcessesList.forEach(element => {
      let date = new Date(element.taskStartDate);
      date.setMonth(date.getMonth() + 1);
      let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

      let task = {
        "SerialNumber": element.serialNumber,
        "Folio": element.workflowInstanceDataFields.Subject,
        "Senders": element.workflowInstanceDataFields.Sender,
        //"CreateDate": taskDate,
        "CreateDate": new Date(element.taskStartDate),
        "DocumentURL": element.workflowInstanceDataFields.ViewerRequest,
        "Remetente": element.workflowInstanceDataFields.Remetente,
        "DocumentsQty": element.totalDocuments,
        "DocId": element.workflowInstanceDataFields.DispatchDocId,
        "FolderID": element.workflowInstanceDataFields.FolderID,
        "WorkflowName": element.workflowDisplayName,
        "activityInstanceName": element.activityInstanceName,
        "Status": element.workflowInstanceDataFields.Status,
        "Agenda": element.workflowInstanceDataFields.Agenda,
        "customDate": this.setFormatDate(new Date(element.workflowInstanceDataFields.StartDate), new Date(element.workflowInstanceDataFields.EndDate), element.workflowInstanceDataFields.IsAllDayEvent),
      }

      this.allProcessesList.push(task);
      this.allProcessesList = removeDuplicate(this.allProcessesList);
      this.allProcessesList = this.sortService.sortDate(this.allProcessesList, 'CreateDate')

    });

    let expedientes = await this.processesbackend.GetTaskListExpediente(false).toPromise();
    expedientes = expedientes.filter(data => data.workflowInstanceDataFields.Status == "Active")
    this.expedientegbstore.count = expedientes.length


    let despachos = await this.despachoRule.getList({ updateStore: true })
    if (despachos) {
      this.despachoStore.reset(despachos)
    }


    let pareceres = await this.processesbackend.GetTasksList("Pedido de Parecer", false).toPromise();
    let pareceresPr = await this.processesbackend.GetTasksList("Pedido de Parecer do Presidente", false).toPromise();

    let allParecer = pareceres.concat(pareceresPr);
    this.count_par_dailywork = Object.keys(allParecer.filter(data => data.workflowInstanceDataFields.Status == "Active")).length;
    this.pedidosstore.countparecer = this.count_par_dailywork;

    let deferimentos = await this.processesbackend.GetTasksList("Pedido de Deferimento", false).toPromise();
    this.count_def_dailywork = Object.keys(deferimentos.filter(data => data.workflowInstanceDataFields.Status == "Active")).length;
    this.pedidosstore.countdeferimento = this.count_def_dailywork;

    let pendentes = await this.processesbackend.GetPendingTasks(false).toPromise();
    this.count_total_pending = Object.keys(pendentes).length;
    this.pendentesstore.count = this.count_total_pending;

    let despachospr = await this.processesbackend.GetTasksList("Despacho do Presidente da República", false).toPromise();
    let despachosPr;

    switch (this.loggeduser.Profile) {
      case 'MDGPR':
        despachosPr = despachospr.filter(data => data.activityInstanceName == "Tarefa de Despacho").filter(data => data.workflowInstanceDataFields.Status == "Active");
        this.count_de_pr = Object.keys(despachosPr).length;
        this.despachoprstore.count = this.count_de_pr;
        break;
      case 'PR':
        despachosPr = despachospr.filter(data => data.activityInstanceName == "Concluir Despacho").filter(data => data.workflowInstanceDataFields.Status == "Active")
        this.count_de_pr = Object.keys(despachosPr).length;
        this.despachoprstore.count = this.count_de_pr;
        break;
    }

    let mdEventsOficial = await this.processesbackend.GetTasksList('Agenda Oficial MDGPR', false).toPromise();
    let mdEventsPessoal = await this.processesbackend.GetTasksList('Agenda Pessoal MDGPR', false).toPromise();
    const eventsMDGPRList = mdEventsOficial.concat(mdEventsPessoal);
    this.eventoaprovacaostore.countMd = eventsMDGPRList.length
    this.eventoaprovacaostore.resetmd(eventsMDGPRList);

    let prEventsOficial = await this.processesbackend.GetTasksList('Agenda Oficial PR', false).toPromise();
    let prEventsPessoal = await this.processesbackend.GetTasksList('Agenda Pessoal PR', false).toPromise();
    const eventsPRList = prEventsOficial.concat(prEventsPessoal);
    this.eventoaprovacaostore.countPr = eventsPRList.length
    this.eventoaprovacaostore.resetpr(eventsPRList);

    let diplomasValidar = despachospr.filter(data => data.activityInstanceName == "Revisar Diploma");
    this.count_dip_pv = Object.keys(diplomasValidar).length;
    this.deplomasStore.resetDiplomasReview(diplomasValidar)
    this.deplomasStore.deplomasReviewCount = this.count_dip_pv

    let diplomasAssinar = despachospr.filter(data => data.activityInstanceName == "Assinar Diploma");
    this.count_dip_as = Object.keys(diplomasAssinar).length;

    this.deplomasStore.resetDiplomasList(diplomasAssinar)

    let diplomasAssinados = despachospr.filter(data => data.activityInstanceName == "Diploma Assinado");
    this.count_dip_as_pr = Object.keys(diplomasAssinados).length;
    this.deplomasStore.resetDiplomasAssinadoList(diplomasAssinados)

    this.processesbackend.GetToApprovedEvents('Agenda', 'true').subscribe(res => {
      this.count_ev_apr = res;
    });

    this.showLoader = false;

    this.count_exp_pp = "-";
    this.count_exp_pd = "-";
    this.count_dip_apr = "-";

  }

  doRefresh(event) {
    console.log(event);

     this.LoadCounts();

    if (event) {
      setTimeout(() => {
        event.target.complete();
      }, 2000);
    }
    else {
      console.log('null');

    }
  }

  selectedElementF(element: string) {
    if (window.innerWidth > 701) {
      return element == this.selectedElement
    }
    return false;
  }

  openAllProcessesPage() {
    this.closeAllDesktopComponents();
    let navigationExtras: NavigationExtras = { queryParams: { "processes": true, } };
    if (window.innerWidth < 701) {
      this.router.navigate(['/home/gabinete-digital']);
    }
    else {
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      this.showAllProcesses = true;
      this.selectedElement = "allProcessesTag";
    }
  }

  openEventsToApprovePage() {
    this.closeAllDesktopComponents();
    let navigationExtras: NavigationExtras = { queryParams: { "eventos": true, } };
    if (window.innerWidth < 701) {
      //this.openEventsToApproveList(profile);
      this.router.navigate(['/home/gabinete-digital/event-list']);
    }
    else {
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      this.showEventsToApprove = true;
      //this.eventsToApprove.doRefresh();
    }
  }

  openExpedientListPage() {
    this.closeAllDesktopComponents();
    switch (this.loggeduser.Profile) {
      case 'MDGPR':
        if (window.innerWidth < 701) {
          //this.openExpedientList();
          this.router.navigate(['/home/gabinete-digital/expediente']);
        }
        else {
          this.selectedElement = 'Correspondence'
          let navigationExtras: NavigationExtras = { queryParams: { "expedientes": true, } };
          this.router.navigate(['/home/gabinete-digital'], navigationExtras);
          this.showExpedients = true;
        }
        break;
      case 'PR':
        if (window.innerWidth < 701) {
          this.router.navigate(['/home/gabinete-digital/expedientes-pr']);
        }
        else {
          this.selectedElement = 'ExpedientesPr'
          let navigationExtras: NavigationExtras = { queryParams: { "expedientes": true, } };
          this.router.navigate(['/home/gabinete-digital'], navigationExtras);
          this.showExpedientesPr = true;
        }
        break;
    }

  }

  openPedidosPage(segment: string) {
    this.closeAllDesktopComponents();

    let navigationExtras: NavigationExtras;

    if (segment == 'deferimento') {
      navigationExtras = { queryParams: { "deferimento": true, } };
      this.segment = 'deferimento'
    } else if (segment == 'parecer') {
      navigationExtras = { queryParams: { "parecer": true, } };
      this.segment = 'parecer'
    }

    if (window.innerWidth < 701) {
      this.router.navigate(['/home/gabinete-digital/pedidos'], navigationExtras);
    }
    else {
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      this.showPedidos = true;
      this.selectedElement = 'RequestForApproval'
      if (segment == 'deferimento') {
        this.selectedElement = 'RequestForApproval'
      } else if (segment == 'parecer') {
        this.selectedElement = 'RequestsForOpinion'
      }
    }
  }

  openDespachosPage(segment?: string) {
    this.closeAllDesktopComponents();
    if (window.innerWidth < 701) {
      this.router.navigate(['/home/gabinete-digital/despachos']);
    }
    else {
      let navigationExtras: NavigationExtras = { queryParams: { "despachos": true, } };
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      this.showDespachos = true;
    }
  }

  openDespachosPrPage(segment?: string) {
    this.closeAllDesktopComponents();
    if (window.innerWidth < 701) {
      this.router.navigate(['/home/gabinete-digital/despachos-pr']);
    }
    else {
      let navigationExtras: NavigationExtras = { queryParams: { "despachospr": true, } };
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      this.showDespachosPr = true;
    }
  }

  openPendentesPage(segment?: string) {
    this.closeAllDesktopComponents();
    if (window.innerWidth < 701) {
      this.router.navigate(['/home/gabinete-digital/pendentes']);
    }
    else {
      let navigationExtras: NavigationExtras = { queryParams: { "pendentes": true, } };
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      this.showPendentes = true;
    }
  }

  openExpedientesPrPage(segment?: string) {
    this.closeAllDesktopComponents();
    if (window.innerWidth < 701) {
      this.router.navigate(['/home/gabinete-digital/expedientes-pr']);
    }
    else {
      this.selectedElement = 'ExpedientesPr'
      let navigationExtras: NavigationExtras = { queryParams: { "expedientespr": true, } };
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      this.showExpedientesPr = true;
    }
  }

  openDiplomasPage(segment: string) {
    let navigationExtras: NavigationExtras;

    if (segment == 'validar') {
      navigationExtras = { queryParams: { "validar": true, } };
    } else if (segment == 'assinados') {
      navigationExtras = { queryParams: { "assinados": true, } };
    }

    this.segment = segment;

    if (window.innerWidth < 701) {
      this.router.navigate(['/home/gabinete-digital/diplomas'], navigationExtras);
    }
    else {
      this.closeAllDesktopComponents();
      this.segment = segment;
      let navigationExtras: NavigationExtras = { queryParams: { "diplomas": true, } };
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      this.showDiplomas = true;
    }
  }

  openDiplomasAssinarPage() {
    this.closeAllDesktopComponents();
    if (window.innerWidth < 701) {
      this.router.navigate(['/home/gabinete-digital/diplomas-assinar']);
    }
    else {
      let navigationExtras: NavigationExtras = { queryParams: { "diplomasassinar": true, } };
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      this.showDiplomasAssinar = true;
    }
  }

}
