import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AnimationController, MenuController, ModalController, NavParams, 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 { EditEventToApproveComponent } from 'src/app/shared/gabinete-digital/edit-event-to-approve/edit-event.page';
import { BadRequestPage } from 'src/app/shared/popover/bad-request/bad-request.page';
import { SuccessMessagePage } from 'src/app/shared/popover/success-message/success-message.page';
import { EmendMessageModalPage } from '../../../agenda/emend-message-modal/emend-message-modal.page';
import { EventActionsPopoverPage } from '../../../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 { ThemeService } from 'src/app/services/theme.service'

@Component({
  selector: 'app-approve-event-modal',
  templateUrl: './approve-event-modal.page.html',
  styleUrls: ['./approve-event-modal.page.scss'],
})
export class ApproveEventModalPage implements OnInit {
  event: Event;
  loadedEvent: any;
  loadedAttachments: any;
  serialNumber: string;
  customDate: any;
  today: any;

  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"];
  InstanceId: string

  constructor(
    private router: Router,
    private modalController: ModalController,
    private navParams: NavParams,
    private processes: ProcessesService,
    private attachmentsService: AttachmentsService,
    private popoverController: PopoverController,
    private menu: MenuController,
    private alertService: AlertService,
    private activatedRoute: ActivatedRoute,
    private iab: InAppBrowser,
    private animationController: AnimationController,
    private toastService: ToastService,
    public ThemeService: ThemeService
  ) {


    this.activatedRoute.paramMap.subscribe(paramMap =>
    {
      if (!paramMap.has("serialNumber")){
        return;
      }
      else{
        this.serialNumber = paramMap.get('serialNumber'); 
      }
    });
  }

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

  }


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

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

  getTask() {

    this.processes.GetTask(this.serialNumber).subscribe(res => {
      console.log('GET TASK SERIALNUMBER: ', this.serialNumber,'Approve event',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()]);
      
      this.InstanceId = res.workflowInstanceDataFields.InstanceId
      this.getAttachments()

    })
    
  }

  viewDocument(docId:string, applicationId:string){
    this.processes.GetDocumentUrl(docId, applicationId).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 approveTask(serialNumber:string) {
    console.log('approveTask SERIALNUMBER: ', serialNumber)
    let body = { "serialNumber": serialNumber, "action": "Aprovar" }
    console.log(body);

    const loader = this.toastService.loading()

    try {
      await this.processes.PostTaskAction(body).toPromise()

      this.toastService._successMessage('Evento aprovado', ()=>{
        this.router.navigate(['/home/gabinete-digital/event-list']);
        this.modalController.dismiss(null);
      })

    } catch (error) {
      this.toastService._badRequest('Evento não aprovado')
    }    
    finally {
      loader.remove()
    }

  }

  emendTask(serialNumber:string){
    console.log('emendTask: ',serialNumber)
    /* console.log('Emendar'); */
    this.menu.close();
    this.openEmendMessageModal(serialNumber);
    this.modalController.dismiss(null);
  }

  async rejectTask(serialNumber:string) {

    let body = { "serialNumber": serialNumber, "action": "Rejeitar" }
    
    const loader = this.toastService.loading()

    try { 
      await  this.processes.PostTaskAction(body).toPromise()

      this.toastService._successMessage('Evento rejeitado', () =>{
        this.router.navigate(['/home/gabinete-digital/event-list']);
      })
    } catch (error) {
      this.toastService._badRequest('Evento não rejeitado')
    }    
    finally {
      loader.remove()
    }

    this.modalController.dismiss(null);
  }

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

    console.log(this.loadedAttachments);
  }

  async openOptions(ev:any) {
    const popover = await this.popoverController.create({
      component: EventActionsPopoverPage,
      cssClass: 'event-actions-popover',
      event: ev,
      translucent: true
    });
    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) => {
      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.router.navigate(['/home/gabinete-digital/event-list']);
          this.toastService.successMessage()
        } catch (error) {
          this.toastService.badRequest()
          this.router.navigate(['/home/gabinete-digital/event-list']);
        }     
        finally {
          loader.remove()
        }

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

  async editar(serialNumber: string) {

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

    await modal.present();

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

  } 


}
