import { Component, OnInit } from '@angular/core';
import { ProcessesService } from 'src/app/services/processes.service';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { EventsService } from 'src/app/services/events.service';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ActivatedRoute, Router } from '@angular/router';
import { Event } from '../../../../models/event.model';
import { AnimationController, MenuController, ModalController, PopoverController } from '@ionic/angular';
import { ViewEventPage } from 'src/app/pages/agenda/view-event/view-event.page';
import { DiscartExpedientModalPage } from '../../discart-expedient-modal/discart-expedient-modal.page';
import { ExpedientTaskModalPage } from '../../expediente/expedient-task-modal/expedient-task-modal.page';
import { BookMeetingModalPage } from '../../expediente/book-meeting-modal/book-meeting-modal.page';
import { LoginUserRespose } from 'src/app/models/user.model';
import { AuthService } from 'src/app/services/auth.service';
import { AddNotePage } from 'src/app/modals/add-note/add-note.page';
import { OptsExpedientePrPage } from 'src/app/shared/popover/opts-expediente-pr/opts-expediente-pr.page';
import { ToastService } from 'src/app/services/toast.service';
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchList } from 'src/app/models/search-document';
import { Location } from '@angular/common';
import { AttachmentList } from 'src/app/models/Excludetask';
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-expediente-pr',
  templateUrl: './expediente-pr.page.html',
  styleUrls: ['./expediente-pr.page.scss'],
})
export class ExpedientePrPage 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;

  task: any;
  fulltask: any;
  eventsList: Event[];
  serialnumber: string;
  caller:string;
  profile: string;
  intervenientes: any;
  cc: any = [];

  loggeduser: LoginUserRespose;
  documents: SearchList[] = [];
  attachments:any;

  constructor(
    private processes: ProcessesService,
    private iab: InAppBrowser,
    private events: EventsService,
    private menu: MenuController,
    private modalController: ModalController,
    public popoverController: PopoverController,
    private activatedRoute: ActivatedRoute,
    private userAuth: AuthService,
    private animationController: AnimationController,
    private toastService: ToastService,
    private attachmentsService: AttachmentsService,
    private RouteService: RouteService,
    public ThemeService: ThemeService

    ) {
      this.loggeduser = userAuth.ValidatedUser;
      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.activatedRoute.paramMap.subscribe(paramMap => {
      if (!paramMap.has('SerialNumber')) {
        return;
      }
      this.LoadTaskDetail(this.serialnumber);
    });

  }

  toDateString(e) {
    return new Date(e).toDateString()
  }

  close() {
    this.modalController.dismiss();
  }

  goBack() {
    this.RouteService.goBack();
    /* if(this.task.Status == "Pending" && this.caller != 'events'){
      if (window.innerWidth <= 800) {
        this.router.navigate(['/home/gabinete-digital/pendentes']);
      }
      else {
        let navigationExtras: NavigationExtras = {
          queryParams: {
              "pendentes": true,
            }
        }
        this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      }
    }
    else{
      this.activatedRoute.paramMap.subscribe(params => {
        switch (params["params"].caller) {
          case 'events':
            this.router.navigate(['/home',params["params"].caller]);
            break;

          case 'gabinete-digital':
            let navigationExtras: NavigationExtras = {
              queryParams: {
                "expedientes-pr": true,
              }
            }
            if( window.innerWidth < 801) {
              this.router.navigate(['/home/gabinete-digital/expedientes-pr']);
            } else {
              this.router.navigate(['/home/gabinete-digital'], navigationExtras);
            }
            break;
        }
      });
    } */
  }

  sendExpedienteToPending() {
    this.processes.SetTaskToPending(this.serialnumber).subscribe(res=>{
      console.log(res);
      this.toastService._successMessage('Processo enviado para pendentes')
      this.goBack();
    },
    (error)=>{
      this.toastService._badRequest('Processo não enviado para pendentes')
    });
  }

  async LoadTaskDetail(serial: string) {
    this.processes.GetTask(serial).subscribe(res => {

      let date = new Date(res.taskStartDate);
      date.setMonth(date.getMonth() + 1);
      let taskDate = date.getFullYear()+"-"+ date.getMonth()+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+ ":"+date.getSeconds();

      this.task = {
        "SerialNumber": res.serialNumber,
        "Folio": res.workflowInstanceDataFields.Subject,
        "Senders": res.originator.email,
        "CreateDate":taskDate,
        "DocumentURL": res.workflowInstanceDataFields.ViewerRequest,
        "Remetente": res.workflowInstanceDataFields.Sender,
        "Note": res.workflowInstanceDataFields.TaskMessage || res.workflowInstanceDataFields.Note, //
        "FolderId": res.workflowInstanceDataFields.FolderID,
        "FsId": res.workflowInstanceDataFields.FsId, //
        "DocId": res.workflowInstanceDataFields.DocId || res.workflowInstanceDataFields.DocID,
        "WorkflowName": res.workflowDisplayName,
        "activityInstanceName": res.activityInstanceName,
        "Status": res.workflowInstanceDataFields.Status,
      }

      this.fulltask = 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';
        });

      })

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

  }

  attachDocument() {

    this.getDoc();
  }

  async getDoc() {
    const modal = await this.modalController.create({
      component: SearchPage,
      cssClass: 'modal-width-100-width-background modal',
      componentProps: {
        type: 'AccoesPresidenciais & ArquivoDespachoElect',
        showSearchInput: true,
        select: true
      }
    });
    await modal.present();
      modal.onDidDismiss().then((res)=>{
        if(res){
          console.log(res);

          const data = res.data;
          this.documents.push(data.selected);
          console.log('RES'+ this.documents);

          /* let body = {
            "InstanceID":null,
            "WorkflowDisplayName": "",
            "FolderID": '',
            "DispatchNumber": '',
            "AttachmentsProcessLastInstanceID": '',
            "Attachments": this.documents,
          }
          this.attachmentsService.AddAttachment(body).subscribe((res)=>{
            this.getAttachments(this.task.SerialNumber);
          }); */

          /* this.documents.forEach(element =>{
            let body = {
              "InstanceID":'',
              "WorkflowDisplayName": "1",
              "FolderID": element.Id,
              "DispatchNumber": element.Assunto,
              "AttachmentsProcessLastInstanceID": this.task.SerialNumber,
              "Attachments": element.ApplicationType
            }
            this.attachmentsService.AddAttachment(body).subscribe((res)=>{
              this.getAttachments(this.task.SerialNumber);
            });
          }) */

        }
    });

  }

  removeAttachment(index: number){
    this.documents = this.documents.filter( (e, i) =>  index != i);
  }

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

  async approve(note:string, documents:any) {
    let body = {
      "serialNumber": this.serialnumber,
      "action": "Aprovar",
      "ActionTypeId": 100000004 ,
      "dataFields": {
        "ReviewUserComment": note,
      },
      "AttachmentList" :documents,
    }

    console.log(body);

    const loader = this.toastService.loading()

    try {
      await this.processes.CompleteTask(body).toPromise();
      this.close();
      this.toastService._successMessage('Processo aprovado')
    } catch(error) {
      this.toastService._badRequest('Processo não aprovado')
    }  finally {
      loader.remove()
    }

  }

  async sendToReview(note:string, documents:any) {
    let body = {
      "serialNumber": this.serialnumber,
      "action": "Retificar",
      "ActionTypeId": 99999877,
      "dataFields": {
        "ReviewUserComment": note,
      },
      "AttachmentList" :documents,
    }

    const loader = this.toastService.loading()

    try {
      await this.processes.CompleteTask(body).toPromise()
      this.close();
      this.toastService._successMessage()
    } catch(error) {
      this.toastService._badRequest()
    } finally {
      loader.remove()
    }
  }

  async openAddNoteModal(actionName:string) {
    let classs;
    if( window.innerWidth < 801){
      classs = 'modal modal-desktop'
    } else  {
      classs = 'add-note-modal'
    }
    const modal = await this.modalController.create({
      component: AddNotePage,
      componentProps: {
        showAttachmentBtn: false,
      },
      cssClass: classs,
      //backdropDismiss: true
    });

    await modal.present();

    modal.onDidDismiss().then(res => {
      console.log(res);
      if(res.data){
        const DocumentToSave = res.data.documents.map((e:SearchList) => {
          return {
            ApplicationId: e.ApplicationType,
            SourceId: e.Id,
          }
        });

        let docs: AttachmentList = {
          ProcessInstanceID: "",
          Attachments: DocumentToSave,
        }

        if(actionName == 'Aprovar'){
          this.approve(res.data.note, docs);
        }
        else if(actionName == 'Revisão'){
          this.sendToReview(res.data.note, docs);
        }
        this.goBack();
      }
    });
  }

  async openExpedientActionsModal(taskAction: any, task: any) {
    //this.modalController.dismiss();
    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: task,
        profile: this.profile,
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then(async(res)=>{
      let body = res['data'];
      if(res['data']) {

        //await this.distartExpedientModal(body);
        const loader = this.toastService.loading()
        try {
          await this.processes.CompleteTask(body).toPromise();
            // this.toastService.successMessage('Processo descartado');
            this.goBack();
          } catch (error) {
            // this.toastService.badRequest('Processo não descartado')
          } finally {
            loader.remove()
        }
      }
      else{
        this.close();
      }
    });
  }

  async distartExpedientModal(body:any){
    const modal = await this.modalController.create({
      component: DiscartExpedientModalPage,
       componentProps: {
      },
      cssClass: 'discart-expedient-modal',
      backdropDismiss: false
    });

    await modal.present();
    modal.onDidDismiss().then( async (res)=>{
      console.log(res['data']);

      if(body == 'descartar') {
        if(res['data']== 'Yes'){
          let otherbody = {
            "serialNumber": this.task.SerialNumber,
            "action": "Passivo",
            "ActionTypeId": 99999877,
            "dataFields": {
              "Note": "",
            }
          }

          const loader = this.toastService.loading()

          try {
            await this.processes.CompleteTask(otherbody).toPromise()
            this.toastService._successMessage('Processo descartado');
            this.goBack();
          } catch (error) {
            this.toastService._badRequest('Processo não descartado')
          }  finally {
            loader.remove()
          }

        }
        else if(res['data'] == 'No'){
          //Do nothing
        }
      }
      else {
        if(res['data']== 'Yes') {

          const loader = this.toastService.loading()

          try {
            await this.processes.CompleteTask(body).toPromise();
            // this.toastService._successMessage('Processo descartado');
            this.goBack();
          } catch (error) {
            // this.toastService._badRequest('Processo não descartado')
          }  finally {
            loader.remove()
          }

          this.goBack();
        }
        else if(res['data'] == 'No') {
          console.log('Update');

          const loader = this.toastService.loading()

          try {
            await this.processes.UpdateTaskStatus(this.task.FolderId).toPromise();
            this.toastService._successMessage();
            this.goBack();
          } catch (error) {
            this.toastService._badRequest()
          }  finally {
            loader.remove()
          }
        }
      }
    });
  }

  async distartExpedientModal2(task: any){
    const modal = await this.modalController.create({
      component: DiscartExpedientModalPage,
       componentProps: {
        serialNumber: task.serialNumber,
        folderId: task.workflowInstanceDataFields.FolderID,
        action: 'discart',
      },
      cssClass: 'discart-expedient-modal',
      backdropDismiss: false
    });

    await modal.present();
    modal.onDidDismiss();
  }

  async openBookMeetingModal(task: any) {
    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: BookMeetingModalPage,
      componentProps: {
        task: this.task,
      },
      cssClass: classs,
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss();
  }

  async viewEventDetail(eventId: any) {
    console.log(this.profile);

    const modal = await this.modalController.create({
      component: ViewEventPage,
      componentProps: {
        eventId: eventId,
        profile: this.profile,
      },
      cssClass: 'modal modal-desktop',
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss().then((res) => {
      if (res) {
      }
    });
  }

  async openOptions(taskAction?: any) {

    const popover = await this.popoverController.create({
      component: OptsExpedientePrPage,
      cssClass: 'exp-options',
      componentProps: {
        task: this.task,
        fulltask: this.fulltask,
        taskAction:taskAction,
      },
      translucent: true
    });
    return await popover.present();
  }

}
