import { Component, OnInit } from '@angular/core';
import { AnimationController, ModalController, PopoverController } from '@ionic/angular';
import { ProcessesService } from 'src/app/services/processes.service';
import { momentG }  from 'src/plugin/momentG';

import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ActivatedRoute, Router } from '@angular/router';
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'
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { ThemeService } from 'src/app/services/theme.service'
import { RouteService } from 'src/app/services/route.service';

@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 RouteService: RouteService,
    public ThemeService: ThemeService
  ) {
    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.RouteService.goBack();
  }

  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')
        }
      }
    });

  }

  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.task.FolderId,
        task: this.fulltask
      },
      cssClass: 'modal modal-desktop'
    });
    await modal.present();

  }

  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();
  }


}
