import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { 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 } from '@ionic/angular';
import { AlertService } from 'src/app/services/alert.service';
import { PedidoPage } from 'src/app/pages/gabinete-digital/pedidos/pedido/pedido.page';
import { PedidosStore } from 'src/app/store/pedidos-store.service';
import { CustomTaskPipe } from 'src/app/pipes/custom-task.pipe';
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 {

  //profile:string;

  @ViewChild(CalendarComponent) myCal: CalendarComponent;

  parecerList:any[] = [];
  fulltask:any;

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

  deferimentoList:any[] = [];
  taskType: string;

  @Input() serialNumber:string;

  @Input() profile:string;
  @Input() segment:string;
  @Output() openPedido:EventEmitter<any> = new EventEmitter<any>();
  skeletonLoader = true
  pedidosstore = PedidosStore;
  customTaskPipe = new CustomTaskPipe()

  constructor(
    private router: Router,
    private processes:ProcessesService,
    private modalController: ModalController,
    private alertService: AlertService,
    private sortService: SortService,
    public ThemeService: ThemeService
    ) {
      this.profile = 'mdgpr';
  }

  ngOnInit() {

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

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

      }
    });

  }

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

  async LoadList() {

    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();

      this.skeletonLoader = false

      let allParecer = parecer.concat(parecerPr).reverse();

      this.parecerList = new Array();

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

        let task: customTask = this.customTaskPipe.transform(element);
        this.parecerList.push(task);

      });

      this.pedidosstore.resetparecer(this.sortService.sortDate(this.parecerList, 'CreateDate'));

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

        this.skeletonLoader = false

        this.deferimentoList = new Array();
        let res = result.reverse().filter(data => data.workflowInstanceDataFields.Status == "Active")

        res.forEach(element => {
          let task: customTask = this.customTaskPipe.transform(element);
          this.deferimentoList.push(task);
        });


        this.pedidosstore.resetdeferimento(this.sortService.sortDate(this.deferimentoList, 'CreateDate'));

      });
    }
  }

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

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

  async viewPedidoDetail(serialNumber:any) {

    const modal = await this.modalController.create({
      component: PedidoPage,
      componentProps:{
        enterAnimation: "",
        serialNumber: serialNumber,
        profile: this.profile,
      },
      cssClass: 'modal modal-desktop',
    });
    await modal.present();
    modal.onDidDismiss().then((res)=>{
      console.log('refresh list');
      this.LoadList();
    });
  }


}
