import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, NavigationError, NavigationExtras, NavigationStart, Router } from '@angular/router';
import { DailyWorkTask } from '../../../models/dailyworktask.model';
import { ProcessesService } from 'src/app/services/processes.service';

import { SqliteService } from 'src/app/services/sqlite.service';
import { BackgroundService } from 'src/app/services/background.service';
import { SortService } from 'src/app/services/functions/sort.service';
import { ThemeService } from 'src/app/services/theme.service'


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

  segment: string;

  skeletonLoader = true

  constructor(
    private processes: ProcessesService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private sqliteservice: SqliteService,
    private backgroundservice: BackgroundService,
    private sortService: SortService,
    public ThemeService: ThemeService
  ) {
    //Inicializar segment

    this.activatedRoute.queryParams.subscribe(params => {
      if (params['validar'] == 'true') {
        this.segment = 'validar';
      } else if (params['assinados'] == 'true') {
        this.segment = 'assinados';
      }
    });
  }

  ngOnInit() {

    //this.segment = 'validar';
    this.activatedRoute.queryParams.subscribe(params => {

      if (params['segment'] == 'validar') {
        this.segment = 'validar';
      } else if (params['segment'] == 'assinados') {
        this.segment = 'assinados';
      }
    });

    const location = window.location
    const pathname = location.pathname + location.search

    this.LoadList()

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

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

  }

  /* async loadDiplomas(){
    console.log('Load');

    this.activatedRoute.data.subscribe(data => {
      console.log(data['diplomas']);

      switch (this.segment) {
        case 'validar':

          let diplomasValidar = data['diplomas'].filter(data => data.activityInstanceName == "Revisar Diploma");
          diplomasValidar.forEach(async element => {
            let DocId = element.workflowInstanceDataFields.FolderID;
            let ApplicationId = element.workflowInstanceDataFields.ApplicationId;

            let res = await this.processes.GetDocumentDetails(DocId, '361').toPromise();

            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,
                "DocumentURL": element.workflowInstanceDataFields.ViewerRequest,
                "Remetente": element.workflowInstanceDataFields.Remetente,
                "DocumentsQty": res.DocumentsTotal,
                "DocId": element.workflowInstanceDataFields.DocIdDiferimento,
                "WorkflowName": element.workflowDisplayName,
                "activityInstanceName": element.activityInstanceName,
            }
            this.diplomasList.push(task);
            this.diplomasList = removeDuplicate( this.diplomasList)

          });
          this.showLoader = false;
          break;

        case 'assinados':
          //this.diplomasList = new Array();
          let diplomasAssinados = data.diplomas.reverse().filter(data => data.activityInstanceName == "Diploma Assinado");
          diplomasAssinados.forEach(async element => {
            let DocId = element.workflowInstanceDataFields.FolderID;
            let ApplicationId = element.workflowInstanceDataFields.ApplicationId;

            let res = await this.processes.GetDocumentDetails(DocId, '361').toPromise();

            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,
                "DocumentURL": element.workflowInstanceDataFields.ViewerRequest,
                "Remetente": element.workflowInstanceDataFields.Remetente,
                "DocumentsQty": this.totalDocs,
                "DocId": element.workflowInstanceDataFields.DocIdDiferimento,
                "WorkflowName": element.workflowDisplayName,
                "activityInstanceName": element.activityInstanceName,
            }
            this.diplomasList.push(task);
            this.diplomasList = removeDuplicate( this.diplomasList)

          });
          this.showLoader = false;
          break;
      }
    });
  } */

  async getTotalDocs(DocId: any) {
    let res = await this.processes.GetDocumentDetails(DocId, '361').toPromise();
    console.log(res.DocumentsTotal);
    return res.DocumentsTotal;
  }

  ngOnDestroy(): void {
    console.log('8. on destroy called');
  }

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

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

  async LoadList() {

    this.processes.GetTasksList("Despacho do Presidente da República", false).subscribe(async res => {

      this.skeletonLoader = true

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

      this.skeletonLoader = false
      this.showLoader = false;

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

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

      });
      
      this.diplomasList = this.sortService.sortDate(diplomasList, 'CreateDate');

      let diplomasAssinados = diplomas.filter(data => data.activityInstanceName == "Diploma Assinado");
      let diplomasAssinadoList = [];

      diplomasAssinados.forEach(async element => {

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

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

    }, (error) => {
      this.getFromDb()
    })

  }

  getFromDb() {

    this.sqliteservice.getprocessByworkflow("Despacho do Presidente da República").then((process: any[]) => {

      let diplomasValidar = process.filter(data => data.activityInstanceName == "Revisar Diploma");
      let diplomasList = [];
      diplomasValidar.forEach(async element => {

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

      console.log(diplomasList);
      this.diplomasList = this.sortService.sortDate(diplomasList, 'taskStartDate');

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

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

      console.log('diplomasAssinados', diplomasAssinados)
      this.diplomasAssinadoList = this.sortService.sortDate(diplomasAssinadoList, 'taskStartDate')

    })
  }

  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": new Date(element.taskStartDate),
      "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,
    }
  }

  pipeTaskOffline(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": JSON.parse(element.workflowInstanceDataFields).Subject,
      "Senders": JSON.parse(element.workflowInstanceDataFields).Sender,
      "CreateDate": new Date(element.taskStartDate),
      "DocumentURL": JSON.parse(element.workflowInstanceDataFields).ViewerRequest,
      "Remetente": JSON.parse(element.workflowInstanceDataFields).Remetente,
      "DocumentsQty": element.totalDocuments,
      "DocId": JSON.parse(element.workflowInstanceDataFields).DocIdDiferimento,
      "WorkflowName": element.workflowDisplayName,
      "activityInstanceName": element.activityInstanceName,
      "Status": JSON.parse(element.workflowInstanceDataFields).Status,
    }
  }



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


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

  goBack() {
    this.router.navigate(['/home/gabinete-digital']);
    // window.history.back()
  }

}
