import { Component, OnInit } from '@angular/core';
import { ProcessesService } from 'src/app/services/processes.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ModalController, 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 { Location } from '@angular/common'
import { PermissionService } from 'src/app/OtherService/permission.service';

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


  task: any;
  fulltask: any;
  serialNumber: string;
  profile: string

  constructor(private activateRoute: ActivatedRoute,
    private processes: ProcessesService,
    private router: Router,
    private modalController: ModalController,
    public popoverController: PopoverController,
    private activatedRoute: ActivatedRoute,
    private toastService: ToastService,
    private location: Location,
    public p: PermissionService,
  ) { }

  ngOnInit() {
    
    this.profile = "mdgpr";

    this.activatedRoute.queryParams.subscribe(params => {
      if(params["serialNumber"]) {
        this.serialNumber = params["serialNumber"];
        console.log(params["serialNumber"]);
      }
    });

    if(this.task.serialNumber) {
      this.serialNumber = this.task.serialNumber
    } else if(this.task.SerialNumber) {
      this.serialNumber = this.task.SerialNumber
    }

  }

  close () {
    this.goBack()
  }


  async openExpedientActionsModal(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,
        profile: this.profile,
        fulltask: this.fulltask
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then( (res)=> {
      console.log(res['data']);
      if(res['data']=='openDiscart') {
        console.log('open discart');
        
        this.distartExpedientModal();

      } else {
        this.goBack()
      }

      this.popoverController.dismiss('close')

    });
  }

  sendExpedienteToPending() {
    this.processes.SetTaskToPending(this.serialNumber).subscribe(res=>{
      console.log(res);
      this.toastService.successMessage()
      this.popoverController.dismiss('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();
        /* console.log('2Expedient Discard closed2');
        this.close();
        this.openMenu(); */
      }
      this.popoverController.dismiss('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();
  }

  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 == 'Reexecução') {
          await this.reexecutar(res.data.note, docs);
        } 
        else if(actionName == 'Concluido') {
          await this.concluir(res.data.note, docs);
        }
        this.goBack();
      }
    });
  } 


  async concluir(note:string, documents:any){
    let body = {
      "serialNumber": this.serialNumber,
      "action": "Executado",
      "ActionTypeId": 104,
      "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 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.router.navigate(['/home/gabinete-digital/despachos-pr'])
  }

  cancle() {
    this.popoverController.dismiss()
  }

}
