import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { ModalController, NavParams, PopoverController } from '@ionic/angular';
import { AddNotePage } from 'src/app/modals/add-note/add-note.page';
import { expedienteTask } from 'src/app/models/dailyworktask.model';
import { SearchList } from 'src/app/models/search-document';
import { DiscartExpedientModalPage } from 'src/app/pages/gabinete-digital/discart-expedient-modal/discart-expedient-modal.page';
import { BookMeetingModalPage } from 'src/app/pages/gabinete-digital/expediente/book-meeting-modal/book-meeting-modal.page';
import { ExpedientTaskModalPage } from 'src/app/pages/gabinete-digital/expediente/expedient-task-modal/expedient-task-modal.page';
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchDocumentPipe } from 'src/app/pipes/search-document.pipe';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { ProcessesService } from 'src/app/services/processes.service';
import { ToastService } from 'src/app/services/toast.service';
import { Location } from '@angular/common';
import { TaskService } from 'src/app/Rules/task.service'
import { ExpedienteService } from 'src/app/Rules/expediente.service';
import { PermissionService } from 'src/app/services/worker/permission.service';
import { ThemeService } from 'src/app/services/theme.service'
import { NewGroupPage } from 'src/app/pages/chat/new-group/new-group.page';
import { RouteService } from 'src/app/services/route.service';

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

  task: expedienteTask
  fulltask: any;
  profile:string;
  caller:string;

  showEnviarPendentes = false
  searchDocumentPipe = new SearchDocumentPipe()
  documents:SearchList[] = [];

  constructor(
    private popoverController: PopoverController,
    private modalController: ModalController,
    private navParams: NavParams,
    private processes: ProcessesService,
    private toastService: ToastService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    public p: PermissionService,
    private attachmentsService: AttachmentsService,
    private RouteService: RouteService,
    private TaskService: TaskService,
    private expedienteService: ExpedienteService,
    public ThemeService: ThemeService
  ) {
    this.task = this.navParams.get('task');
    this.fulltask = this.navParams.get('fulltask');

    if(this.task.Status != 'Pending') {
      this.showEnviarPendentes = true;
    }
  }

  ngOnInit() {
    window.onresize = (event) => {
      if( window.innerWidth >= 800){
        this.popoverController.dismiss();
      }
    };
  }

  async openNewGroupPage(){
    console.log(this.fulltask);

    const modal = await this.modalController.create({
      component: NewGroupPage,
      cssClass: 'modal modal-desktop',
      componentProps: {
        name: this.task.Folio,
        task: this.task,
        documents: this.fulltask.Documents,
      },
    });
    await modal.present();
    modal.onDidDismiss();
  }

  close() {
    if( window.innerWidth < 801) {
      this.popoverController.dismiss();
    }
    else{
      this.popoverController.dismiss();
    }
  }

  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.RouteService.goBack()


      /* this.activatedRoute.paramMap.subscribe(params => {
        console.log('YES');
        console.log(params);


        switch (params["params"].caller) {
          case 'events':
            console.log('here-1');

            this.router.navigate(['/home',params["params"].caller]);
            break;

          case 'gabinete-digital':
            console.log('here0');
            let navigationExtras: NavigationExtras = {
              queryParams: {
                "expedientes": true,
              }
            }
            if( window.innerWidth < 801) {
              this.router.navigate(['/home/gabinete-digital/expediente']);
              console.log('here');

            } else {
              this.router.navigate(['/home/gabinete-digital'], navigationExtras);
            }
            break;

        }
      }); */
    }
  }

  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( async (res)=>{
        if(res){
          const data = res.data;
          this.documents.push(data.selected);
          this.documents.forEach((element: any) =>{

            let body = {
              "InstanceID": this.task.InstanceID,
              "WorkflowDisplayName": this.task.WorkflowName,
              "FolderID": this.task.FolderId,
              "DispatchNumber": this.task.DispatchNumber,
              "AttachmentsProcessLastInstanceID": this.task.AttachmentsProcessLastInstanceID,
              "Attachments": []
            }

            const Attachments = this.searchDocumentPipe.transformToAttachment(element)
            body.Attachments = Attachments;

            const loader = this.toastService.loading()

            this.attachmentsService.AddAttachment(body).subscribe((res)=> {
              this.toastService._successMessage()
            },()=> {
              this.toastService._badRequest()
            },()=> {
              loader.remove()
            });

        });

        this.popoverController.dismiss()

      }
    });

  }

  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( async (res) => {
      console.log(res);
      if(res.data){
        const DocumentToSave = res.data.documents.map((e) => {
          return {
            ApplicationId: e.ApplicationType,
            SourceId: e.Id,
          }
        });

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

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

  async sendToReview(note:string, documents:any) {
    let body = {
      "serialNumber": this.task.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()
    }
  }

  sendExpedienteToPending() {
    this.close();
    this.processes.SetTaskToPending(this.task.SerialNumber).subscribe(res=>{
      this.goBack();
    },()=>{

      this.toastService._badRequest('Processo não encontrado')
    });
  }

  async approve(note:string, documents:any){
    let body = {
      "serialNumber": this.task.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 openBookMeetingModal() {
    this.close();
    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 openExpedientActionsModal(taskAction: any, task: any) {

    console.log(taskAction, task)

    this.close();
    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,
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then(async res=>{
      console.log(res['data']);
      let body = res['data'];
      if(res['data']){
        const loader = this.toastService.loading()
        try {
          await this.processes.CompleteTask(body).toPromise();
            this.goBack();
          } catch (error) {
            this.toastService._badRequest('Processo não descartado')
          } finally {
            loader.remove()
        }
      }
      else{
        console.log('Not open');
      }
    });
  }

  async distartExpedientModal(body:any){
    this.close();
    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') {

          const loader = this.toastService.loading()

          try {
            await this.expedienteService.discard({SerialNumber: this.task.SerialNumber}).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()
          }
        }
      }
    });
  }

}
