import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { AnimationController, MenuController, ModalController, NavParams, PopoverController } from '@ionic/angular';
import { AddNotePage } from 'src/app/modals/add-note/add-note.page';
import { SearchList } from 'src/app/models/search-document';
import { LoginUserRespose } from 'src/app/models/user.model';
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 { AttachmentsService } from 'src/app/services/attachments.service';
import { AuthService } from 'src/app/services/auth.service';
import { ProcessesService } from 'src/app/services/processes.service';
import { ToastService } from 'src/app/services/toast.service';
import { Location } from '@angular/common'
import { ThemeService } from 'src/app/services/theme.service'
import { RouteService } from 'src/app/services/route.service';

@Component({
  selector: 'app-opts-expediente-pr',
  templateUrl: './opts-expediente-pr.page.html',
  styleUrls: ['./opts-expediente-pr.page.scss'],
})
export class OptsExpedientePrPage 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;
  profile: string;

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

  showEnviarPendentes = false;

  loggeduser: LoginUserRespose;

  constructor(
    private popoverController: PopoverController,
    private modalController: ModalController,
    private processes: ProcessesService,
    private attachmentsService: AttachmentsService,
    private userAuth: AuthService,
    private navParams: NavParams,
    private animationController: AnimationController,
    private toastService: ToastService,
    private RouteService: RouteService,
    public ThemeService: ThemeService

  ) {

    this.task = this.navParams.get('task');
    this.fulltask = this.navParams.get('fulltask');

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


    console.log('OptsExpedientePrPage ---- ', this.task);

  }

  ngOnInit() {
  }

  close() {
    if( window.innerWidth <= 1024){
      this.popoverController.dismiss();
    }
    else{
      this.modalController.dismiss();
    }
  }

  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: 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.goBack();
      }
    });
  }

  async approve(note:string, documents:any) {
    this.popoverController.dismiss();
    let body = {
      "serialNumber": this.task.SerialNumber,
      "action": "Aprovar",
      "ActionTypeId": 100000004 ,
      "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 distartExpedientModal(body:any){
    this.popoverController.dismiss();
    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 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.popoverController.dismiss();
    this.processes.SetTaskToPending(this.task.SerialNumber).subscribe(res=>{
      console.log(res);
      this.close();
    },()=>{

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

  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: ExpedientTaskModalPage,
      componentProps: {
        taskAction: taskAction,
        task: task,
        profile: this.profile,
        fulltask: this.fulltask,
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then( async (res)=>{
      console.log(res['data']);
      let body = res['data'];
      // console.log('close '+ res['data'])
      if(res['data']) {
        console.log('open discart');

        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{
        console.log('Not open');
      }

    });
  }

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

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

  getAttachments(serialNumber){
    this.attachmentsService.getAttachmentsBySerial(serialNumber).subscribe(res=>{
      this.attachments = res;
    });
  }

  attachDocument(){
    this.popoverController.dismiss();
    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){
          const data = res.data;
          this.documents.push(data.selected);
          console.log( this.documents);
          this.documents.forEach(element =>{
            let body = {
              "Source": "1",
              "SourceId": element.Id,
              "SourceTitle": element.Assunto,
              "SerialNumber": this.task.SerialNumber,
              "ApplicationId": element.ApplicationType
            }
            this.attachmentsService.setEventAttachmentById(body).subscribe((res)=>{
              this.getAttachments(this.task.SerialNumber);
            });
          })

        }
    });

  }



}
