import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { NavigationExtras, Router } from '@angular/router';
import { ModalController, PopoverController } from '@ionic/angular';
import { Event } from 'src/app/models/event.model';
import { AlertService } from 'src/app/services/alert.service';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { ProcessesService } from 'src/app/services/processes.service';
import { EmendMessageModalPage } from 'src/app/pages/agenda/emend-message-modal/emend-message-modal.page';
import { EventActionsPopoverPage } from 'src/app/pages/agenda/event-actions-popover/event-actions-popover.page';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ToastService } from 'src/app/services/toast.service';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { ThemeService } from 'src/app/services/theme.service'

@Component({
  selector: 'app-approve-event',
  templateUrl: './approve-event.page.html',
  styleUrls: ['./approve-event.page.scss'],
})
export class ApproveEventPage implements OnInit {

  event: Event;
  @Input() loadedEvent:any;
  loadedAttachments:any;
  customDate:any;
  today:any;
  show: boolean = false;

  months = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
  days = ["Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado"];

  @Input() serialNumber:string;
  @Input() showComponent:string;
  @Input() componentTransparent: any
  @Input() InstanceId:string;
  @Input() showAside:boolean;

  @Output() approveEventDismiss = new EventEmitter<any>();
  @Output() closeEventToApprove = new EventEmitter<any>();
  @Output() AproveEventEditEvent = new EventEmitter<any>();

  @Output() EditApproveEventDismiss = new EventEmitter<any>();

  constructor(
    private router:Router,
    private modalController: ModalController,
    private processes:ProcessesService,
    private attachmentsService: AttachmentsService,
    private popoverController: PopoverController,
    private alertService: AlertService,
    private iab: InAppBrowser,
    private toastService: ToastService,
    public ThemeService: ThemeService
  ) {
    // Event to approve list

  }

  toDateString(e) {
    return new Date(e).toDateString()
  }

  ngOnInit() {
    this.getTask();
    this.getAttachments();
  }

  /* ngOnChanges() {
    this.getTask();
    this.getAttachments();

    setTimeout(()=>{
      this.getTask();
      this.getAttachments();
    }, 6000)

    setTimeout(()=>{
      this.getTask();
      this.getAttachments();
    }, 10000)

  } */

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

  close() {
    /* this.router.navigate(['/home/gabinete-digital/event-list']); */
    this.closeEventToApprove.emit();
    this.modalController.dismiss();
  }

  getTask() {
    this.processes.GetTask(this.serialNumber).subscribe(res => {
      console.log(res);
      this.loadedEvent = res;
      this.today = new Date(res.workflowInstanceDataFields.StartDate);
      // console.log(new Date(this.today));
      this.customDate = this.days[this.today.getDay()]+ ", "  + this.today.getDate() +" de "  + ( this.months[this.today.getMonth()]);

    })
  }

  async approveTask(serialNumber:string) {
    let body = { "serialNumber": serialNumber, "action": "Aprovar" }

    const loader = this.toastService.loading()

    try {
      await this.processes.PostTaskAction(body).toPromise()
      this.modalController.dismiss(serialNumber);
      this.toastService.successMessage()
    } catch (error) {
      this.toastService.badRequest()
    }   finally {
      this.close()
      loader.remove()
    }

    /* this.approveEventDismiss.emit({
      "serialNumber": serialNumber,
      "action": "Aprovar",
      "saveData": {
        loadedEvent: this.loadedEvent,
        today: this.today,
        customDate: this.customDate
      }
    }); */
  }

  async rejectTask(serialNumber:string) {

    let body = { "serialNumber": serialNumber, "action": "Rejeitar" }
    console.log(body);

    const loader = this.toastService.loading()

    try {
      await this.processes.PostTaskAction(body).toPromise()
      this.toastService.successMessage('Evento rejeitado')
    } catch (error) {
      this.toastService.badRequest('Processo não efectuado')
    } finally {
      loader.remove()
      this.close()
    }

  }

  async getAttachments() {
    this.loadedAttachments = await this.attachmentsService.getAttachmentsById(this.InstanceId).toPromise();

  }

  async viewDocument(DocId:string, Document) {

    const modal = await this.modalController.create({
      component: ViewDocumentPage,
      componentProps: {
        trustedUrl: '',
        file: {
          title: Document.Assunto,
          url: '',
          title_link: '',
        },
        Document,
        applicationId: Document.ApplicationId,
        docId: Document.DocId || Document.SourceId,
        folderId: this.loadedEvent.FolderId,
        task: this.loadedEvent
      },
      cssClass: 'modal modal-desktop'
    });
    await modal.present();

  }

  async openOptions(ev:any) {
    const popover = await this.popoverController.create({
      component: EventActionsPopoverPage,
      cssClass: 'event-actions-popover',
      event: ev,
      translucent: true
    });
    return await popover.present();
  }

  async emendTask(serialNumber:string) {
    console.log('Desktop');

    const modal = await this.modalController.create({
      component: EmendMessageModalPage,
      componentProps:{
      },
      cssClass: 'emend-message-modal',
      backdropDismiss: false
    });

    await modal.present();

    modal.onDidDismiss()
    .then( async (res) => {
      console.log(res.data);

      if(res.data !== ''){
        let body = { "serialNumber": serialNumber,
        "action": "Emendar",
            "dataFields": {
            "ReviewUserComment": res.data,
          }
        }
        console.log(body);
        const loader = this.toastService.loading()

        try {
          await this.processes.PostTaskAction(body).toPromise();
          this.toastService.successMessage('Pedido enviado');
          this.close();
        } catch (error) {
          this.toastService.badRequest();
        }  finally {
          loader.remove()
        }
      }
      else{
        //this.alertService.presentAlert('Operação cancelada!');
      }
    });

    //this.openEmendMessageModal(serialNumber);
    //this.goBack();
  }

  goToEventsToApprove() {
    if(window.location.pathname.startsWith('/home/agenda')) {
      this.close()
    } else {
      let navigationExtras: NavigationExtras = {
        queryParams: {
          "eventos": true,
        }
      };
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
    }

  }


  /** @description edit event to aprove */
  async editar(serialNumber: string) {

    this.EditApproveEventDismiss.emit();

  }
}
