import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AnimationController, ModalController, NavParams, PopoverController } from '@ionic/angular';
import { AddNotePage } from 'src/app/modals/add-note/add-note.page';
import { CreateProcessPage } from 'src/app/modals/create-process/create-process.page';
import { DarParecerPage } from 'src/app/modals/dar-parecer/dar-parecer.page';
import { DelegarPage } from 'src/app/modals/delegar/delegar.page';
import { BookMeetingModalPage } from 'src/app/pages/gabinete-digital/expediente/book-meeting-modal/book-meeting-modal.page';
import { ProcessesService } from 'src/app/services/processes.service';
import { ToastService } from 'src/app/services/toast.service';
import { PedidoService } from 'src/app/Rules/pedido.service';
import { PermissionService } from 'src/app/services/worker/permission.service';
import { DataService } from 'src/app/services/data.service';
import { NewGroupPage } from 'src/app/pages/chat/new-group/new-group.page';


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

  task:any;
  fulltask: any;
  profile:string;
  serialNumber : string;
  showEnviarPendentes = false;

  constructor(
    private popoverController: PopoverController,
    private modalController: ModalController,
    private navParams: NavParams,
    private processes: ProcessesService,
    private activatedRoute: ActivatedRoute,
    private toastService: ToastService,
    private router: Router,
    public p: PermissionService,
    private pedidoService: PedidoService,
    private dataService: DataService,
  ) {
    this.task = this.navParams.get('task');
    this.fulltask = this.navParams.get('fulltask');
    this.serialNumber = this.navParams.get('serialNumber');

    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
    }

    this.showEnviarPendentes = this.navParams.get('showEnviarPendentes');

    if(!this.showEnviarPendentes) this.showEnviarPendentes = false

  }

  ngOnInit() {
    console.log(this.task);
    this.profile = "mdgpr";

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

  close() {
    this.popoverController.dismiss('close')
  }
  cancel(){
    this.popoverController.dismiss();
  }

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

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

  }

  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 openNewGroupPage(){
    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().then( () => {
      this.popoverController.dismiss('close');
    });
  }

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

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

      } else {
        this.popoverController.dismiss('close')
      }

    });
  }

  async repreciar(note:string, documents:any) {
    let body = {
      "serialNumber": this.serialNumber,
      "action": "Reapreciação",
      "ActionTypeId": 100000009,
      "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 <= 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) => {


      const DocumentToSave = res.data.documents.map((e) => {
        return {
          ApplicationId: e.ApplicationType,
          SourceId: e.Id,
        }
      });

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


      if(res.data) {
        if(actionName == 'Solicitar Reapreciação') {

          await this.repreciar(res.data.note, docs);
        }
        else if(actionName == 'Arquivar') {
          await this.arquivar(res.data.note, docs);
          this.popoverController.dismiss('close')
        }
      }

    });
  }

  async arquivar(note:string, documents:any) {

    const loader = this.toastService.loading()

    try {
      await this.pedidoService.arquivar({serialNumber: this.serialNumber,
        documents,
        note
      }).toPromise()

      this.toastService._successMessage('Processo arquivado')
    } catch (error) {
      this.toastService._badRequest('Processo não arquivado')
    } finally {
      loader.remove()
    }

  }

  async openDarParecer(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: DarParecerPage,
      componentProps: {
        serialNumber: this.task.SerialNumber,
        ProcessInstanceID: this.task.ProcessInstanceID,
      },
      cssClass: classs,
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss().then( () => {
      this.popoverController.dismiss('close');
    });

  }

  async openDelegarModal(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: DelegarPage,
      componentProps: {
        task: this.task,
      },
      cssClass: classs,
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss().then( async (res)=> {

      if(res['data']=='close') {
        this.popoverController.dismiss('close');
      }

    })
  }


}
