import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { ActivatedRoute, NavigationEnd, NavigationExtras, NavigationStart, Router } from '@angular/router';
import { DailyWorkTask } from '../../../models/dailyworktask.model';
import { ProcessesService } from 'src/app/services/processes.service';
import { ModalController, NavParams } from '@ionic/angular';
import { AlertService } from 'src/app/services/alert.service';
import { removeDuplicate } from 'src/plugin/removeDuplicate.js'
import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe';
import { DeplomasStore } from 'src/app/store/deplomas.service';
import { ThemeService } from 'src/app/services/theme.service'
import { SortService } from 'src/app/services/functions/sort.service';

@Component({
  selector: 'app-diplomas',
  templateUrl: './diplomas.page.html',
  styleUrls: ['./diplomas.page.scss'],
})
export class DiplomasPage implements OnInit {
//profile:string;
diplomasList:DailyWorkTask[] = [];
diplomasAssinadoList:DailyWorkTask[] = [];
showLoader: boolean;
serialNumber:string;
skeletonLoader = false

@Input() segment:string;


deplomasStore = DeplomasStore
customTaskPipe = new CustomTaskPipe()

constructor(
  private processes:ProcessesService,
  private modalController: ModalController,
  private alertService: AlertService,
  private router: Router,
  private activatedRoute: ActivatedRoute,
  public ThemeService: ThemeService,
  private sortService: SortService,
  ) {}

  ngOnInit() {
    // update list
    this.LoadList()
    
    this.router.events.forEach((event) => {
      if (event instanceof NavigationStart && '/home/gabinete-digital?diplomas=true'.startsWith(event.url)) {
        if(window.location.pathname.split('/').length >= 4 && window.location.pathname.startsWith('/home/gabinete-digital')) {
          this.refreshing()
        } else {
          this.LoadList()
        }
      }
    });

    
  }

  segmentChanged(ev: any) {
    this.LoadList();
  }

  goToDiploma(serialNumber:any){
    this.router.navigate(['/home/gabinete-digital/diplomas', serialNumber, 'gabinete-digital']);
  }

  notImplemented(){
    this.alertService.presentAlert('Funcionalidade em desenvolvimento');
  }

  async LoadList() {
    
    let diplomas = await this.processes.GetTasksList("Despacho do Presidente da República", false).toPromise();

    this.diplomasList = [];
    let diplomasList = [];

    let diplomasValidar = diplomas.filter(data => data.activityInstanceName == "Revisar Diploma");
    diplomasValidar.forEach(element => {

      let task = this.pipeTask(element)
      diplomasList.push(task);
    });

    this.diplomasList = this.sortService.sortDate(diplomasList, 'CreateDate')
    this.deplomasStore.resetDiplomasList(this.diplomasList)

    let diplomasAssinadoList = []
    let diplomasAssinados = diplomas.reverse().filter(data => data.activityInstanceName == "Diploma Assinado");
    diplomasAssinados.forEach(async element => {

      let task = this.pipeTask(element)
      diplomasAssinadoList.push(task);
    });

    this.diplomasAssinadoList =  this.sortService.sortDate(diplomasAssinadoList, 'CreateDate')
    this.deplomasStore.resetDiplomasAssinadoList(this.diplomasAssinadoList)

    this.showLoader = false;
    this.skeletonLoader = false
  }

  pipeTask(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();
    return {
      "SerialNumber": element.serialNumber,
      "Folio": element.workflowInstanceDataFields.Subject,
      "Senders": element.workflowInstanceDataFields.Sender,
      "CreateDate": taskDate,
      "DocumentURL": element.workflowInstanceDataFields.ViewerRequest,
      "Remetente": element.workflowInstanceDataFields.Remetente,
      "DocumentsQty": element.totalDocuments,
      "DocId": element.workflowInstanceDataFields.DocIdDiferimento,
      "WorkflowName": element.workflowDisplayName,
      "activityInstanceName": element.activityInstanceName,
      "Status": element.workflowInstanceDataFields.Status,
    }
  }

  async refreshing() {
    setTimeout(() => {
      this.LoadList();
    }, 1000);
  }

  doRefresh() {
    this.LoadList();
  }

}
