import { Component, OnInit } from '@angular/core';
import { AnimationController, ModalController, PopoverController } from '@ionic/angular';
import { AddNotePage } from 'src/app/modals/add-note/add-note.page';
import { ProcessesService } from 'src/app/services/processes.service';
import { OptsExpedientePage } from 'src/app/shared/popover/opts-expediente/opts-expediente.page';
import { momentG }  from 'src/plugin/momentG';

import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { BookMeetingModalPage } from '../../expediente/book-meeting-modal/book-meeting-modal.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 { DeplomaOptionsPage } from 'src/app/shared/popover/deploma-options/deploma-options.page';
import { ToastService } from 'src/app/services/toast.service';
import { Location } from '@angular/common'

@Component({
  selector: 'app-diploma-assinar',
  templateUrl: './diploma-assinar.page.html',
  styleUrls: ['./diploma-assinar.page.scss'],
})
export class DiplomaAssinarPage 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"];

  serialnumber: string;
  profile: string;
  task: any
  fulltask: any
  intervenientes: any;
  cc: any = [];
  attachments:any;
  customDate: any;
  caller:string;

  constructor(
    private processes: ProcessesService,
    public popoverController: PopoverController,
    private modalController: ModalController,
    private iab: InAppBrowser,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private animationController: AnimationController,
    private toastService: ToastService,
    private location: Location,
  ) {
    this.activatedRoute.paramMap.subscribe(params => {
      if(params["params"].SerialNumber) {
        this.serialnumber = params["params"].SerialNumber;
      }
      if(params["params"].caller) {
        this.caller = params["params"].caller;
      }
    });

  }

  ngOnInit() {
    this.profile = "mdgpr";
    this.LoadTaskDetail(this.serialnumber);
  }

  goBack() {
    this.location.back();
  }

  async openOptions(taskAction?: any) {
    const popover = await this.popoverController.create({
      component: DeplomaOptionsPage,
      cssClass: 'exp-options',
      componentProps: {
        serialNumber: this.task.SerialNumber,
        task: this.task,
        showEnviarPendentes: false
      },
      translucent: true
    });
    return await popover.present();
  }

  async LoadTaskDetail(serial: string) {

    this.processes.GetTask(serial).subscribe(res => {
      this.task = {
        "SerialNumber": res.serialNumber,
        "Folio": res.workflowInstanceDataFields.Subject,
        "Senders": res.originator.email,
        "CreateDate": momentG(new Date(res.taskStartDate),'yyyy-MM-dd HH:mm:ss'),
        "DocumentURL": res.workflowInstanceDataFields.ViewerRequest,
        "Remetente": res.workflowInstanceDataFields.Sender,
        "Note": res.workflowInstanceDataFields.TaskMessage || res.workflowInstanceDataFields.Note,
        "FolderId": res.workflowInstanceDataFields.FolderID,
        "FsId": '361',
        "DocId": res.workflowInstanceDataFields.DispatchDocId,
        "WorkflowName": res.workflowDisplayName,
        "DeadlineType": res.workflowInstanceDataFields.DeadlineType,
        "activityInstanceName": res.activityInstanceName,
      }

      this.fulltask = res;
      console.log(this.task);

      console.log('GetTask', res);

      let thedate = new Date(this.task.CreateDate);
      this.customDate = this.days[thedate.getDay()]+ ", "  + thedate.getDate() +" de "  + ( this.months[thedate.getMonth()]);

      this.processes.GetTaskParticipants(this.task.FolderId).subscribe(users=>{
        this.intervenientes = users.filter(user=>{
          return user.Type == 'I';
        });
        this.cc = users.filter(user=>{
          return user.Type == 'CC';
        });
        console.log(users);

      });
      this.getDocumentDetails(this.task.FolderId, '361');

    }, (error)=>{
      try {
        this.toastService.badRequest('Processo não encontrado')
        this.goBack()
      } catch (e) {
        window.history.back();
      }   finally {
        if(error.status ==  0) {
          this.toastService.badRequest('Não é possível  visualizar este processo no modo offline')
        } else {
          this.toastService.badRequest('Processo não encontrado')
        }
      }
    });

  }

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

  getDocumentDetails(forlderId:string, applicationId:string) {
    this.processes.GetDocumentDetails(forlderId,applicationId).subscribe(res=>{
      this.attachments = res.Documents;
      console.log(res['Documents']);
      console.log(this.attachments);
    })
  }

  async Assinar(){
    let body = {
      "serialNumber": this.serialnumber,
      "action": "Assinado",
      "ActionTypeId": 99999842,
      "dataFields": {
        "ReviewUserComment": '',
      },
      "AttachmentList": {},
    }

    const loader = this.toastService.loading()

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

      this.toastService.successMessage(false, ()=>{
        this.goBack();
      })
    } catch (error) {
      this.toastService.badRequest()
    }
    finally {
      loader.remove()
    }

  }


  toDateString(e) {
    return new Date(e).toDateString()
  }
  close() {
    this.modalController.dismiss();
  }


}
