import { Component, OnInit } from '@angular/core';
import { MenuController, ModalController, NavParams, PopoverController } from '@ionic/angular';
import { AlertService } from 'src/app/services/alert.service';
import { ProcessesService } from 'src/app/services/processes.service';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ExpedientTaskModalPage } from 'src/app/pages/gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page';
import { DocumentSetUpMeetingPage } from '../document-set-up-meeting/document-set-up-meeting.page';
import { SearchDocumentDetails, SearchFolderDetails } from 'src/app/models/search-document';
import { ExpedientTaskModalPageNavParamsTask } from 'src/app/models/ExpedientTaskModalPage';
import { PermissionService } from 'src/app/OtherService/permission.service';
import { SearchedDocumentOptionsPage } from 'src/app/shared/popover/searched-document-options/searched-document-options.page';

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

  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"];

  customDate:any;

  docId: string;
  applicationId:string;
  LoadedDocument:any = null;

  folder: SearchFolderDetails
  document:  SearchDocumentDetails

  task: ExpedientTaskModalPageNavParamsTask;

  constructor(
    private navParams: NavParams,
    private modalController: ModalController,
    private alertService: AlertService,
    private processes: ProcessesService,
    private menu: MenuController,
    private iab: InAppBrowser,
    public p: PermissionService,
    private popoverController: PopoverController
  ) {
    this.docId = this.navParams.get('docId');
    this.applicationId = this.navParams.get('applicationId');
  }

  ngOnInit() {
    this.LoadDocumentDetails();
  }

  async LoadDocumentDetails() {
    this.processes.GetDocumentDetails(this.docId, this.applicationId).subscribe(res=>{
      this.LoadedDocument = res;

      this.LoadedDocument.Subject = this.LoadedDocument.Assunto

      let thedate = new Date(this.LoadedDocument.DateDispatch || this.LoadedDocument.DocDate);

      console.log(res)
      this.customDate = this.days[thedate.getDay()]+ ", "  + thedate.getDate() +" de "  + ( this.months[thedate.getMonth()]);

      let task: ExpedientTaskModalPageNavParamsTask
      let document: SearchDocumentDetails = this.LoadedDocument
      let folder: SearchFolderDetails = this.LoadedDocument
      
      if(this.LoadedDocument.ApplicationID == 361 || this.LoadedDocument.ApplicationId == 361) {
        task = {
          serialNumber: folder.DispatchNumber,
          taskStartDate: folder.DateDispatch,
          isEvent: true,
          workflowInstanceDataFields: {
            FolderID: folder['FolderId'] || folder['FolderID'] || folder.folderId,
            Subject: folder.Assunto,
            SourceSecFsID: folder.ApplicationID || folder['ApplicationId'],
            SourceType: 'FOLDER',
            SourceID: folder.folderId,
            DispatchNumber: folder.DispatchNumber
          },
        }
      } else if (document.ApplicationID == 8 || document.ApplicationId == 8) {
        task = {
          serialNumber: document.DocId,
          taskStartDate: document.DocDate,
          isEvent: true,
          workflowInstanceDataFields: {
            FolderID: null,
            Subject: document.Assunto,
            DispatchNumber: null,
            SourceSecFsID: document.ApplicationID || document.ApplicationId,
            SourceType: 'DOC',
            SourceID: document.DocId,
          }
        }
      } else {
        console.log('unexpected ApplicationID')
      }
  
      this.task = task
      console.log('this.task = task', this.task)

    });

  }

  viewDocument() {
    this.processes.GetDocumentUrl(this.docId, '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();
    });
  }

  openMenu() {
    this.menu.open();
    this.modalController.dismiss();
  }

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

  // efetuar despacho 
  async openExpedientActionsModal( taskAction: any) {

    let classs;
    if( window.innerWidth <= 800) {
      classs = 'modal modal-desktop'
    } else  {
      classs = 'modal modal-desktop showAsideOptions'
    }
    const modal = await this.modalController.create({
      component: ExpedientTaskModalPage,
      componentProps: {
        taskAction: taskAction,
        task: this.task,
        seachDocuments: this.LoadedDocument,
        aplicationId: this.LoadedDocument.ApplicationId || this.LoadedDocument.ApplicationID
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then( async(res)=>{});

  }

  async openBookMeetingModal() {

    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: DocumentSetUpMeetingPage,
      componentProps: {
        subject: this.task.workflowInstanceDataFields.Subject,
        document: this.LoadedDocument,
      },
      cssClass: classs,
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss();
  }

  async openOptions() {
    const popover = await this.popoverController.create({
      component: SearchedDocumentOptionsPage,
      cssClass: 'exp-options',
      componentProps: {
        task: this.task,
        LoadedDocument: this.LoadedDocument
      },
      translucent: true
    });
    await popover.present()

    popover.onDidDismiss().then((res:any) => {
      if(res.data.component == 'openBookMeetingModal') {
        this.openBookMeetingModal()
      } else if(res.data.component == 'openExpedientActionsModal') {
        this.openExpedientActionsModal(res.data.taskAction)
      } else {
        console.log(res.data)
        console.log('component not found')
      }
    });
  }
  
}