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';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';

import { SqliteService } from '../../../../services/sqlite.service';
import { BackgroundService } from '../../../../services/background.service';
import { Platform } from '@ionic/angular';
import { ThemeService } from 'src/app/services/theme.service'
import { OfflineManagerService } from 'src/app/services/offline-manager.service';
import { RouteService } from 'src/app/services/route.service';

@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;
  attachments: any;

  @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 RouteService: RouteService,
    private sqliteservice: SqliteService,
    private platform: Platform,
    private backgroundservice: BackgroundService,
    public ThemeService: ThemeService,
    private offlineManager: OfflineManagerService
  ) {
    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();
    this.backgroundservice.registerBackService('Online', () => {
      this.getTask();
    });

  }

  goBack() {
    this.RouteService.goBack();
    /* 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);
    } */

  }

  addProcessToDB(data) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      this.sqliteservice.updateProcess(data);
    }
  }

  getProcessFromDB() {

    this.platform.ready().then(() => {

      this.sqliteservice.getProcessById(this.serialNumber).then((process) => {
        console.log('event aprove serial', process)

        var doc;
        var action = [];
        var origi = [];
        var wordafi = {};
        if (process[0].Documents === "null" || process[0].Documents === "undefined") {
          doc = []
        } else {
          doc = JSON.parse(process[0].Documents)
        }

        if (process[0].actions === "null" || process[0].actions === "undefined") {
          action = []
        } else {
          action = JSON.parse(process[0].Documents)
        }

        if (process[0].originator === "null" || process[0].originator === "undefined") {
          origi = []
        } else {
          origi = JSON.parse(process[0].Documents)
        }
        if (process[0].workflowInstanceDataFields === "null" || process[0].workflowInstanceDataFields === "undefined") {
          wordafi = []
        } else {
          wordafi = JSON.parse(process[0].workflowInstanceDataFields)
        }

        let task = {
          "Documents": doc,
          "actions": action,
          "activityInstanceName": process[0].activityInstanceName,
          "formURL": process[0].formURL,
          "originator": origi,
          "serialNumber": process[0].serialNumber,
          "taskStartDate": process[0].taskStartDate,
          "totalDocuments": process[0].totalDocuments,
          "workflowDisplayName": process[0].workflowDisplayName,
          "workflowID": process[0].workflowID,
          "workflowInstanceDataFields": wordafi,
          "workflowInstanceFolio": process[0].workflowInstanceFolio,
          "workflowInstanceID": process[0].workflowInstanceID,
          "workflowName": process[0].workflowInstanceID

        }

        this.loadedEvent = task
        console.log('offline event', 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.loadedAttachments = this.loadedEvent.Documents;
        console.log('Attatara', this.loadedAttachments)

      })
    })
    console.log('Offlineee')
  }

  async getTask() {
    this.processes.GetTask(this.serialNumber).subscribe(async res => {

      this.loadedEvent = await this.processes.GetTask(this.serialNumber).toPromise();
      this.addProcessToDB(this.loadedEvent)
      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()]);

    }, (error) => {
      this.getProcessFromDB();
    })
  }

  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()
            .catch(() => {
              console.log('Send event to approve for revition')
              this.offlineManager.storeRequestData('event-listRever', body);
            });
            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 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: '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();
    });

  }

}
