import { Component, OnInit, ViewChild } from '@angular/core';
import { CalendarComponent } from 'ionic2-calendar';

import { customFullTask, customTask, 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 { ExpedientTaskModalPage } from 'src/app/pages/gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page';
import { BookMeetingModalPage } from 'src/app/pages/gabinete-digital/expediente/book-meeting-modal/book-meeting-modal.page';
import { DiscartExpedientModalPage } from 'src/app/pages/gabinete-digital/discart-expedient-modal/discart-expedient-modal.page';

import { AuthService } from 'src/app/services/auth.service';
import { DespachoPage } from 'src/app/pages/gabinete-digital/despachos/despacho/despacho.page';
import { LoginUserRespose } from 'src/app/models/user.model';
import { NavigationEnd, NavigationExtras, NavigationStart, Router } from '@angular/router';
import { __awaiter } from 'tslib';
import { DespachosprStore } from 'src/app/store/despachospr-store.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-despachos-pr',
  templateUrl: './despachos-pr.page.html',
  styleUrls: ['./despachos-pr.page.scss'],
})
export class DespachosPrPage implements OnInit {

  @ViewChild(CalendarComponent) myCal: CalendarComponent;

  taskslist: DailyWorkTask[] = [];
  despachoList: any[] = [];
  deferimentoList: DailyWorkTask[] = [];

  taskList: customTask[] = [];

  taskType: string;
  serialNumber: string;
  totalDocs: any;

  profile: string;
  segment: string;

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

  loadedAttachments: any;
  dicIndex = 0;
  inicial = false

  loggeduser: LoginUserRespose;
  skeletonLoader = true
  despachoprstore = DespachosprStore
  listToPresent = [];

  constructor(
    private processes: ProcessesService,
    private modalController: ModalController,
    private alertService: AlertService,
    private authService: AuthService,
    private router: Router,
    private sqliteservice: SqliteService,
    private backgroundservice: BackgroundService,
    private sortService: SortService,
    public ThemeService: ThemeService
  ) {

    this.loggeduser = authService.ValidatedUser;
    this.profile = 'mdgpr';

  }

  ngOnInit() {
    //Inicializar segment
    this.segment = "despachos";

    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.doRefresh()
        } else {
          this.LoadList()
        }
      }
    });

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

  segmentChanged(ev: any) {

    this.LoadList();
  }

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

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

  openExpedientDetailPage(data) {
    console.log(data);
  }

  async LoadList() {

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

      let result = await this.processes.GetTasksList("Despacho do Presidente da República", false).toPromise();
      this.despachoList = [];
      this.skeletonLoader = false;
      console.log(result);

      let despachosPr;
      let despachos = this.sortService.sortArrayByDate(result);
      switch (this.loggeduser.Profile) {
        case 'MDGPR':
          despachosPr = await despachos.reverse().filter(data => data.activityInstanceName == "Tarefa de Despacho");
          break;
        case 'PR':
          despachosPr = await despachos.reverse().filter(data => data.activityInstanceName == "Concluir Despacho");
          break;
      }

      console.log(despachosPr);
      despachosPr = despachosPr.filter(data => data.workflowInstanceDataFields.Status == "Active");

      despachosPr.forEach((element, index) => {

        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": 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.despachoList.push(task);
      });

      this.despachoList = this.sortService.sortDate(this.despachoList, 'CreateDate')
      this.listToPresent = this.despachoList

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

  }

  getFromDB() {

    this.sqliteservice.getAllProcess().then((all) => {
      console.log('DESPACHO PR ALL', all)
    })
    this.sqliteservice.getprocessByworkflow('Despacho do Presidente da República').then(async (process: any[]) => {
      console.log('DESPACHO PR', process)

      let despachosPr;
      switch (this.loggeduser.Profile) {
        case 'MDGPR':
          despachosPr = await process.reverse().filter(data => data.activityInstanceName == "Tarefa de Despacho");
          break;
        case 'PR':
          console.log(process);

          despachosPr = await process.reverse().filter(data => data.activityInstanceName == "Concluir Despacho");
          break;
      }

      despachosPr = despachosPr.filter(data => JSON.parse(data.workflowInstanceDataFields).Status == "Active");
      despachosPr.forEach((element, index) => {

        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": 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,
        }

        this.despachoList.push(task);
        console.log(this.despachoList);
      });
      this.listToPresent = this.despachoList;

    })
  }

  doRefresh() {

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

  }

  async viewExpedientDetail(serialNumber: any) {
    console.log(this.profile);

    let classs;
    if (window.innerWidth <= 800) {
      classs = 'modal modal-desktop'
    } else {
      classs = 'modal modal-desktop'
    }

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


  async openBookMeetingModal(task: customFullTask) {

    const doc = this.loadedAttachments[this.dicIndex];

    task = {
      serialNumber: doc.SourceId,
      taskStartDate: doc.CreateDate,
      isEvent: true,
      workflowInstanceDataFields: {
        FsId: doc.ApplicationId,
        FolderID: null,
        DocId: doc.SourceId,
        Subject: doc.SourceName
      },
    }

    let classs;
    if (window.innerWidth <= 800) {
      classs = 'book-meeting-modal modal modal-desktop'
    } else {
      classs = 'modal modal-desktop showAsideOptions'
    }
    const modal = await this.modalController.create({
      component: BookMeetingModalPage,
      componentProps: {
        task: task,
      },
      cssClass: classs,
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss();
  }


  // async distartExpedientModal() {

  //   const modal = await this.modalController.create({
  //     component: DiscartExpedientModalPage,
  //     componentProps: {
  //       action: 'complete',
  //     },
  //     cssClass: 'discart-expedient-modal',
  //     backdropDismiss: false
  //   });

  //   await modal.present();
  //   modal.onDidDismiss().then(res=>{
  //     if(res['data']=='close'){

  //     }

  //   });
  // }

  docIndex(index: number) {
    this.dicIndex = index;
  }

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

}
