import { Component, OnInit } from '@angular/core';
import { AnimationController, ModalController, NavParams } from '@ionic/angular';
import { SearchList } from 'src/app/models/search-document';
import { SearchPage } from 'src/app/pages/search/search.page';
import { ProcessesService } from 'src/app/services/processes.service';
import { ToastService } from 'src/app/services/toast.service';
import { ThemeService } from 'src/app/services/theme.service'

@Component({
  selector: 'app-dar-parecer',
  templateUrl: './dar-parecer.page.html',
  styleUrls: ['./dar-parecer.page.scss'],
})
export class DarParecerPage implements OnInit {
  note:string;
  serialNumber:string;
  instanceId: string;
  documents:SearchList[] = [];

  constructor(
    private processes: ProcessesService,
    private modalController: ModalController,
    private navParams: NavParams,
    private animationController: AnimationController,
    private toastService: ToastService,
    public ThemeService: ThemeService
  ) { 
    this.serialNumber = this.navParams.get('serialNumber');
    this.instanceId = this.navParams.get('ProcessInstanceID');
  }

  ngOnInit() {
    console.log(this.serialNumber
  );
    
  }
  
  cancel() {
    this.modalController.dismiss();
  }
  
  async save() {
    
    const DocumentToSave = this.documents.map((e) => {
      return {
        ApplicationId: e.ApplicationType,
        SourceId: e.Id,
      }
    });

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

    let body = { 
      "serialNumber": this.serialNumber, 
      "action": "Registar",
      "ActionTypeId": 104,
      "dataFields": {
        "ReviewUserComment": this.note,
      },
      "AttachmentList": docs,
    }
    console.log(body);

    const loader = this.toastService.loading()

    try {
      await this.processes.CompleteTask(body).toPromise();
      this.modalController.dismiss();
      this.toastService._successMessage('Parecer enviado');
    } catch (error) {
      this.toastService._badRequest("Parecer não solicitado");
    } finally {
      loader.remove()
    }

  }

  removeAttachment(index: number){
    this.documents = this.documents.filter( (e, i) =>  index != i);
  }
  
  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);
        }
    });
  }


  
}
