import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { AnimationController, MenuController, 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 { EditEventToApproveComponent } from 'src/app/shared/gabinete-digital/edit-event-to-approve/edit-event.page';
import { ToastService } from 'src/app/services/toast.service';
import { Location } from '@angular/common';

@Component({
  selector: 'app-approve-event',
  templateUrl: './approve-event.page.html',
  styleUrls: ['./approve-event.page.scss'],
})
export class ApproveEventPage implements OnInit {
  event: Event;
  loadedEvent:any = false
  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"];

  serialNumber:string;
  caller:string;
  @Input() InstanceId:string;

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

  constructor(
    private router:Router,
    private activatedRoute: ActivatedRoute,
    private modalController: ModalController,
    private processes:ProcessesService,
    private attachmentsService: AttachmentsService,
    private popoverController: PopoverController,
    private menu: MenuController,
    private alertService: AlertService,
    private iab: InAppBrowser,
    private animationController: AnimationController,
    private toastService: ToastService,
    private location: Location,
  ) {
    this.activatedRoute.paramMap.subscribe(params => {
      console.log(params["params"]);

      if(params["params"].serialNumber) {
        this.serialNumber = params["params"].serialNumber;
      }
      if(params["params"].caller){
        this.caller = params["params"].caller;
      }
    });

  }

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

  ngOnInit() {
    console.log(this.serialNumber);
    console.log(this.caller);

    this.getTask();
  }

  goBack() {
    this.location.back();
    /* let navigationExtras: NavigationExtras = {
      queryParams: {
        "eventos": true,
      }
    };
    if( window.innerWidth < 801) {
      this.router.navigate(['/home',this.caller, 'event-list']);
    } else {
      this.router.navigate(['/home/gabinete-digital'], navigationExtras);
    } */

  }

  async getTask() {
    this.loadedEvent = await this.processes.GetTask(this.serialNumber).toPromise();
    console.log(this.loadedEvent);

    this.today = new Date(this.loadedEvent.workflowInstanceDataFields.StartDate);

    this.customDate = this.days[this.today.getDay()]+ ", "  + this.today.getDate() +" de "  + ( this.months[this.today.getMonth()]);

    let instanceId = this.loadedEvent.workflowInstanceDataFields.InstanceId;
    this.getAttachments(instanceId);
  }

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

    const loader = this.toastService.loading()

    try {
      await this.processes.PostTaskAction(body).toPromise()
      this.toastService.successMessage();
      this.goBack();

    } catch (error) {
      this.toastService.badRequest()
    }
    finally {
      loader.remove()
    }


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

  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.goBack();
        } catch (error) {
          this.toastService.badRequest();
        }  finally {
          loader.remove()
        }

      }
      else{
        //this.alertService.presentAlert('Operação cancelada!');
      }
    });

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

  async rejeitar(serialNumber:string){
    let body = { "serialNumber": serialNumber, "action": "Rejeitar" }
    console.log(body);
    const loader = this.toastService.loading()
    try {
      await this.processes.PostTaskAction(body).toPromise();
      await this.toastService.successMessage('Processo rejeitado');
      this.goBack();
    } catch (error) {
      this.toastService.badRequest()
    }
    finally {
      loader.remove()
    }
  }

  async getAttachments(instanceId:string) {

    try {
      this.loadedAttachments = await this.attachmentsService.getAttachmentsById(instanceId).toPromise();

    } catch (error) {

    }

  }

  viewDocument(sourceId){
    this.processes.GetDocumentUrl(sourceId, '8').subscribe(res=>{
      /* console.log(res); */
      const url: string = res.replace("webTRIX.Viewer","webTRIX.Viewer.Branch1");
      const browser = this.iab.create(url,"_blank");
      browser.show();

    });
  }

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

  openMenu() {
    this.menu.open();
  }
  async openEmendMessageModal(serialNumber:string) {
    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();
          this.goBack();
        } catch (error) {
          this.toastService.badRequest();
        }  finally {
          loader.remove()
        }

      }
      else{
        //this.alertService.presentAlert('Operação cancelada!');
      }
    });
  }

  goToEventsToApprove(){
    let navigationExtras: NavigationExtras = {
      queryParams: {
        "eventos": true,
      }
    };
    this.router.navigate(['/home/gabinete-digital'], navigationExtras);
  }

  async editar(serialNumber: string) {

    const modal = await this.modalController.create({
      component: EditEventToApproveComponent,
      componentProps: {
        serialNumber: serialNumber,
        InstanceId:this.InstanceId
      },
      cssClass: 'modal modal-desktop',
      // backdropDismiss: false
    });

    await modal.present();

    modal.onDidDismiss().then(res => {
      this.getTask();
    });

  }

}
