import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { ActivatedRoute, NavigationStart, Router } from '@angular/router';
import { CalendarComponent } from 'ionic2-calendar';
import { customTask, DailyWorkTask } from '../../../models/dailyworktask.model';
import { ProcessesService } from 'src/app/services/processes.service';
import { ModalController, NavParams, Platform } from '@ionic/angular';
import { AlertService } from 'src/app/services/alert.service';
import { PedidosStore } from 'src/app/store/pedidos-store.service';
import { ModalService } from 'src/app/services/modal.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-pedidos',
  templateUrl: './pedidos.page.html',
  styleUrls: ['./pedidos.page.scss'],
})
export class PedidosPage implements OnInit {

  @ViewChild(CalendarComponent) myCal: CalendarComponent;

  taskslist: DailyWorkTask[] = [];
  parecerList: any[] = [];
  listToPresentparecerList: any[] = [];
  listToPresentdeferimentoList: any[] = [];
  fulltask: any;

  parecerListResult: customTask[] = [];
  deferimentoListResult: customTask[] = [];

  deferimentoList: any[] = [];
  taskType: string;
  serialNumber: string;
  skeletonLoader = true
  pedidosstorage = PedidosStore;

  segment: string;
  @Output() openExpedientDetail: EventEmitter<any> = new EventEmitter<any>();

  constructor(
    private router: Router,
    private processes: ProcessesService,
    private modalController: ModalController,
    private alertService: AlertService,
    private activatedRoute: ActivatedRoute,
    private modalService: ModalService,
    private sqliteservice: SqliteService,
    private sortService: SortService,
    private backgroundservice: BackgroundService,
    private platform: Platform,
    public ThemeService: ThemeService
  ) {
    //Inicializar segment
    this.segment = 'parecer';

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


    const modal = this.modalService.BookMeetingModalPage({ task: '' }, {})

  }

  ngOnInit() {

    this.LoadList()

    this.router.events.forEach((event) => {
      if (event instanceof NavigationStart && '/home/gabinete-digital/pedidos?parecer=true'.startsWith(event.url) ||
        event instanceof NavigationStart && '/home/gabinete-digital/pedidos?deferimento=true'.startsWith(event.url)
      ) {

        if (window.location.pathname.split('/').length >= 4 && window.location.pathname.startsWith('/home/gabinete-digital')) {
          this.refreshing()
        } else {
          this.LoadList()
        }
      }
    });

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

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

  /* segmentChanged(ev: any) {

    let navigationExtras: NavigationExtras;

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

    this.router.navigate(['/home/gabinete-digital/pedidos'], navigationExtras);

    // this.LoadList();
  } */

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

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

  openExpedientDetailPage(data) {
    console.log(data);
    this.openExpedientDetail.emit(data);
  }

  async LoadList() {

    //Retirar esta chamada posteriormente - Eudes
    this.processes.GetTasksList("Pedido de Parecer", false).subscribe(async res => {

      this.skeletonLoader = true

      if (this.segment == 'parecer') {
        this.taskType = "Pedido de Parecer";

        let parecer = await this.processes.GetTasksList("Pedido de Parecer", false).toPromise();
        let parecerPr = await this.processes.GetTasksList("Pedido de Parecer do Presidente", false).toPromise();

        console.log(parecerPr);

        this.skeletonLoader = false

        let allParecer = parecer.concat(parecerPr).reverse().filter(data => data.workflowInstanceDataFields.Status == "Active")

        this.parecerList = [];

        allParecer.filter(data => data.workflowInstanceDataFields.Status == "Active").forEach(element => {

          let date = new Date(element.taskStartDate);
          const dateMonth = date.getMonth() + 1;
          let month = date.getMonth() + 1;
          let taskDate = date.getFullYear() + "-" + month + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

          let task = {
            "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,
          }
          this.parecerList.push(task);
        });
        this.addPedidoToDb(this.parecerList);

        this.listToPresentparecerList = this.sortService.sortDate(this.parecerList, 'CreateDate')
        this.pedidosstorage.resetparecer(this.listToPresentparecerList);

      }
      else if (this.segment == 'deferimento') {
        this.taskType = "Pedido de Deferimento";
        this.processes.GetTasksList("Pedido de Deferimento", false).subscribe(result => {

          this.skeletonLoader = false

          console.log(result);

          this.deferimentoList = [];

          let res = result.filter(data => data.workflowInstanceDataFields.Status == "Active")
          res = res.reverse()

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

            let task = {
              "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,
            }

            if (element.workflowInstanceDataFields.Status == "Active") {
              this.deferimentoList.push(task);
            }
          });
        });
        this.addPedidoToDb(this.deferimentoList);
        this.listToPresentdeferimentoList = this.sortService.sortDate(this.deferimentoList, 'CreateDate')
        this.pedidosstorage.resetdeferimento(this.listToPresentdeferimentoList);

      }


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

  }

  addPedidoToDb(pedido) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
    this.sqliteservice.addProcess(pedido);
  }
  }

  getFromDb() {

    let parecerlist = [];
    let deferimentolist = []
    this.sqliteservice.getprocessByworkflowpedido("Pedido de Parecer", "Pedido de Parecer do Presidente").then((process: any[]) => {

      process.forEach((element) => {
        if (JSON.parse(element.workflowInstanceDataFields).Status == "Active") {
          let date = new Date(element.taskStartDate);
          //date.setMonth(date.getMonth() + 1);
          let month = date.getMonth() + 1;
          let taskDate = date.getFullYear() + "-" + month + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

          let task = {
            "SerialNumber": element.serialNumber,
            "Folio": JSON.parse(element.workflowInstanceDataFields).Subject,
            "Senders": JSON.parse(element.workflowInstanceDataFields).Sender,
            "CreateDate": taskDate,
            "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,
          }
          parecerlist.push(task)
        }
      })
      this.listToPresentparecerList = this.sortService.sortArrayISODate(parecerlist);
      console.log('parecer', process)
    })

    this.sqliteservice.getprocessByworkflow("Pedido de Deferimento").then((process: any[]) => {
      process.forEach((element) => {
        if (JSON.parse(element.workflowInstanceDataFields).Status == "Active") {
          let date = new Date(element.taskStartDate);
          //date.setMonth(date.getMonth() + 1);
          let month = date.getMonth() + 1;
          let taskDate = date.getFullYear() + "-" + month + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

          let task = {
            "SerialNumber": element.serialNumber,
            "Folio": JSON.parse(element.workflowInstanceDataFields).Subject,
            "Senders": JSON.parse(element.workflowInstanceDataFields).Sender,
            "CreateDate": taskDate,
            "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,
          }
          deferimentolist.push(task)
        }
      })
      this.listToPresentdeferimentoList = this.sortService.sortArrayISODate(deferimentolist);
      console.log('deferimento', process)
    })
  }

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

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

  doRefresh(event) {
    this.LoadList();
    setTimeout(() => {
      event.target.complete();
    }, 2000);
  }

}
