import { Component, OnInit } from '@angular/core';
import { ProcessesService } from 'src/app/services/processes.service';
import { ActivatedRoute, Router } from '@angular/router';
import { AnimationController, ModalController, NavParams, PopoverController } from '@ionic/angular';
import { CreateProcessPage } from 'src/app/modals/create-process/create-process.page';
import { DelegarPage } from 'src/app/modals/delegar/delegar.page';
import { AddNotePage } from 'src/app/modals/add-note/add-note.page';
import { BookMeetingModalPage } from 'src/app/pages/gabinete-digital/expediente/book-meeting-modal/book-meeting-modal.page';
import { DiscartExpedientModalPage } from 'src/app/pages/gabinete-digital/discart-expedient-modal/discart-expedient-modal.page';
import { ToastService } from 'src/app/services/toast.service';
import { customTask, fullTask } from 'src/app/models/dailyworktask.model';
import { PermissionService } from 'src/app/services/worker/permission.service';
import { ThemeService } from 'src/app/services/theme.service'
import { Location } from '@angular/common'
import { RouteService } from 'src/app/services/route.service';

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

  task: customTask
  fulltask: fullTask;
  serialNumber: string;

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


      this.serialNumber = this.task.SerialNumber
    }

  ngOnInit() {
  }

  close () {
    this.goBack()
  }

  async openTaskProcessModal(taskAction: any, task: any) {
    this.popoverController.dismiss();
    let classs;
    if( window.innerWidth <= 800){
      classs = 'modal modal-desktop'
    } else {
      classs = 'modal modal-desktop showAsideOptions'
    }
    const modal = await this.modalController.create({
      component: CreateProcessPage,
      componentProps: {
        taskAction: taskAction,
        task: task,
        fulltask: this.fulltask
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then( res => {
      this.goBack();
    });
  }

  sendExpedienteToPending(){
    this.popoverController.dismiss();
    this.processes.SetTaskToPending(this.task.SerialNumber).subscribe(res=>{
      this.toastService._successMessage()
      console.log(res);
      this.close();
    },()=>{

      this.toastService._badRequest('Processo não encontrado')
    });
  }
  
  async distartExpedientModal(){
    this.popoverController.dismiss();
    console.log(this.fulltask);
    const modal = await this.modalController.create({
      component: DiscartExpedientModalPage,
       componentProps: {
        serialNumber: this.fulltask.serialNumber,
        folderId: this.fulltask.workflowInstanceDataFields.FolderID,
        action: 'complete',
      },
      cssClass: 'discart-expedient-modal',
      backdropDismiss: false
    });
    
    await modal.present();
    modal.onDidDismiss().then(res=>{
      if(res['data']=='close'){
        this.close();
      }
    });
  }


  async openBookMeetingModal(task: any) {
    this.popoverController.dismiss();
    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 openDelegarModal(task: any) {
    this.popoverController.dismiss();
    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: DelegarPage,
      componentProps: {
        task: this.task,
      },
      cssClass: classs,
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss().then(res => {
      if(res){
        const data = res.data;
        if(data == 'close') {
          this.goBack();
        }
      }

    });
  }

  async generateDiploma(note:string, documents:any){
    let body = { 
      "serialNumber": this.serialNumber, 
      "action": "Reencaminhar",
      "ActionTypeId": 99999839,
      "dataFields": {
        "ReviewUserComment": note,
      },
      "AttachmentList" :documents,
    }

    const loader = this.toastService.loading()

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

  }

  async openAddNoteModal(actionName:string) {

    this.popoverController.dismiss();
    let classs;
    if( window.innerWidth <= 800){
      classs = 'modal modal-desktop'
    } else  {
      classs = 'modal modal-desktop'
    }
    const modal = await this.modalController.create({
      component: AddNotePage,
      componentProps: {
        showAttachmentBtn: true
      },
      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 == 'Executado') {
          await this.executado(res.data.note, docs);
        }
        else if(actionName == 'Arquivar'){
         await this.arquivar(res.data.note, docs);
        }
        else if(actionName == 'Gerar Diploma') {
          await this.generateDiploma(res.data.note, docs);
        }
        else if(actionName == 'Concluido') {
          //this.concluir(res.data.note, docs);
        }
        else if(actionName == 'Reexecução') {
          await this.reexecutar(res.data.note, docs);
        }
        this.goBack();
      }
    });
  } 

  async arquivar(note:string, documents:any) {
    let body = { 
      "serialNumber": this.serialNumber, 
      "action": "Arquivo",
      "ActionTypeId": 95,
      "dataFields": {
        "ReviewUserComment": note,
      },
      "AttachmentList" :documents,
    }

    const loader = this.toastService.loading()

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

  }


  async executado(note:string, documents:any){
    let body = { 
      "serialNumber": this.serialNumber, 
      "action": "Conhecimento",
      "ActionTypeId": 104,
      "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 reexecutar(note:string, documents:any){
    let body = { 
      "serialNumber": this.serialNumber, 
      "action": "Reexecutar",
      "ActionTypeId": 100000010,
      "dataFields": {
        "ReviewUserComment": note,
      },
      "AttachmentList" :documents,
    }

    const loader = this.toastService.loading()

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

  }

  goBack() {
    this.RouteService.goBack();
  }

}
