import { Component, OnInit } from '@angular/core';
import { AnimationController, ModalController, PopoverController } from '@ionic/angular';
import { AddNotePage } from 'src/app/modals/add-note/add-note.page';
import { ProcessesService } from 'src/app/services/processes.service';
import { OptsExpedientePage } from 'src/app/shared/popover/opts-expediente/opts-expediente.page';
import { momentG } from 'src/plugin/momentG';

import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { BookMeetingModalPage } from '../../expediente/book-meeting-modal/book-meeting-modal.page';
import { DeplomaOptionsPage } from 'src/app/shared/popover/deploma-options/deploma-options.page';
import { ToastService } from 'src/app/services/toast.service';
import { Location } from '@angular/common';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { Platform } from '@ionic/angular';
import { SqliteService } from 'src/app/services/sqlite.service';
import { BackgroundService } from 'src/app/services/background.service';
import { ThemeService } from 'src/app/services/theme.service'
import { RouteService } from 'src/app/services/route.service';


@Component({
  selector: 'app-diploma',
  templateUrl: './diploma.page.html',
  styleUrls: ['./diploma.page.scss'],
})
export class DiplomaPage 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"];

  serialNumber: string;
  caller: string;
  profile: string;
  task: any
  fulltask: any
  intervenientes: any;
  cc: any = [];
  attachments: any;
  customDate: any

  constructor(
    private processes: ProcessesService,
    public popoverController: PopoverController,
    private modalController: ModalController,
    private iab: InAppBrowser,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private animationController: AnimationController,
    private toastService: ToastService,
    private RouteService: RouteService,
    private sqliteservice: SqliteService,
    private backgroundservice: BackgroundService,
    private platform: Platform,
    public ThemeService: ThemeService
  ) {
    this.activatedRoute.paramMap.subscribe(params => {
      // console.log(params["params"]);

      if (params["params"].SerialNumber) {
        this.serialNumber = params["params"].SerialNumber;
      }
      if (params["params"].caller) {
        this.caller = params["params"].caller;
      }

    });

  }

  ngOnInit() {
    this.profile = "mdgpr";
    this.LoadTaskDetail(this.serialNumber);
    this.backgroundservice.registerBackService('Online', () => {
      this.LoadTaskDetail(this.serialNumber);
    });
  }

  goBack() {
    this.RouteService.goBack();
    /* if(this.task.Status == "Pending" && this.caller == 'gabinete-digital'){
      if (window.innerWidth < 801) {
        this.router.navigate(['/home/gabinete-digital/pendentes']);
      }
      else {
        let navigationExtras: NavigationExtras = {
          queryParams: {
              "pendentes": true,
            }
        }
        this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      }
    }
    else{
      if (window.innerWidth < 801) {
        this.router.navigate(['/home/gabinete-digital/diplomas']);
      } else {
        let navigationExtras: NavigationExtras = {
          queryParams: {
            'diplomas': true
          }
        }
        this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      }
    } */
  }

  async openOptions(taskAction?: any) {
    const popover = await this.popoverController.create({
      component: DeplomaOptionsPage,
      cssClass: 'exp-options',
      componentProps: {
        serialNumber: this.serialNumber,
        task: this.task,
        fulltask: this.fulltask,
        taskAction: taskAction,
        showEnviarPendentes: false
      },
      translucent: true
    });
    return await popover.present();
  }

  async LoadTaskDetail(serial: string) {
    this.processes.GetTask(serial).subscribe(res => {
      this.task = {
        "SerialNumber": res.serialNumber,
        "Folio": res.workflowInstanceDataFields.Subject,
        "Senders": res.originator.email,
        "CreateDate": momentG(new Date(res.taskStartDate), 'yyyy-MM-dd HH:mm:ss'),
        "DocumentURL": res.workflowInstanceDataFields.ViewerRequest,
        "Remetente": res.workflowInstanceDataFields.Sender,
        "Note": res.workflowInstanceDataFields.TaskMessage || res.workflowInstanceDataFields.Note,
        "FolderId": res.workflowInstanceDataFields.FolderID,
        "FsId": '361',
        "DocId": res.workflowInstanceDataFields.DispatchDocId,
        "WorkflowName": res.workflowDisplayName,
        "DeadlineType": res.workflowInstanceDataFields.DeadlineType,
        "activityInstanceName": res.activityInstanceName,
      }
      this.fulltask = res;
      this.updateProcessOnDB(res)

      let thedate = new Date(this.task.CreateDate);
      this.customDate = this.days[thedate.getDay()] + ", " + thedate.getDate() + " de " + (this.months[thedate.getMonth()]);

      this.processes.GetTaskParticipants(this.task.FolderId).subscribe(users => {
        this.updateProcessInterveners(users)
        this.intervenientes = users.filter(user => {
          return user.Type == 'I';
        });
        this.cc = users.filter(user => {
          return user.Type == 'CC';
        });
      });
      this.getDocumentDetails(this.task.FolderId, '361');

    }, (error) => {
      if (error.status == 0) {
        this.getFromDb();
      } else {
        try {
          this.goBack()
        } catch (e) {
          window.history.back();
        }
        this.toastService._badRequest('Processo não encontrado')
      }
    });

  }

  updateProcessOnDB(res) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      this.sqliteservice.updateProcess(res);
    }
  }
  updateProcessInterveners(users) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      this.sqliteservice.updateProcessInterveners(JSON.stringify(this.serialNumber), JSON.stringify(users))
    }
  }

  getFromDb() {

    this.sqliteservice.getProcessById(this.serialNumber).then((process) => {

      this.task = {
        "SerialNumber": process[0].serialNumber,
        "Folio": JSON.parse(process[0].workflowInstanceDataFields).Subject,
        "Senders": JSON.parse(process[0].originator).email,
        "CreateDate": momentG(new Date(process[0].taskStartDate), 'yyyy-MM-dd HH:mm:ss'),
        "DocumentURL": JSON.parse(process[0].workflowInstanceDataFields).ViewerRequest,
        "Remetente": JSON.parse(process[0].workflowInstanceDataFields).Sender,
        "Note": JSON.parse(process[0].workflowInstanceDataFields).TaskMessage || JSON.parse(process[0].workflowInstanceDataFields).Note,
        "FolderId": JSON.parse(process[0].workflowInstanceDataFields).FolderID,
        "FsId": '361',
        "DocId": JSON.parse(process[0].workflowInstanceDataFields).DispatchDocId,
        "WorkflowName": process[0].workflowDisplayName,
        "DeadlineType": JSON.parse(process[0].workflowInstanceDataFields).DeadlineType,
        "activityInstanceName": process[0].activityInstanceName,
      }

      let fulltak = {
        Documents: JSON.parse(process[0].Documents),
        actions: JSON.parse(process[0].actions),
        activityInstanceName: process[0].activityInstanceName,
        formURL: process[0].formURL,
        originator: JSON.parse(process[0].originator),
        serialNumber: process[0].serialNumber,
        taskStartDate: process[0].taskStartDate,
        totalDocuments: process[0].totalDocuments,
        workflowDisplayName: process[0].workflowDisplayName,
        workflowID: process[0].workflowID,
        workflowInstanceDataFields: JSON.parse(process[0].workflowInstanceDataFields),
        workflowInstanceFolio: process[0].workflowInstanceFolio,
        workflowInstanceID: process[0].workflowInstanceID,
        workflowName: process[0].workflowName
      }
      this.fulltask = fulltak

      let thedate = new Date(this.task.CreateDate);
      this.customDate = this.days[thedate.getDay()] + ", " + thedate.getDate() + " de " + (this.months[thedate.getMonth()]);

      this.intervenientes = JSON.parse(process[0].interveners).filter(user => {
        return user.Type == 'I';
      });
      this.cc = JSON.parse(process[0].interveners).filter(user => {
        return user.Type == 'CC';
      });

      this.attachments = JSON.parse(process[0].Documents)

    })
  }

  async viewDocument(DocId: string, Document) {

    const modal = await this.modalController.create({
      component: ViewDocumentPage,
      componentProps: {
        trustedUrl: '',
        file: {
          title: Document.Assunto,
          url: '',
          title_link: '',
        },
        Document,
        applicationId: Document.ApplicationId,
        docId: Document.DocId || Document.SourceId,
        folderId: this.task.FolderId,
        task: this.fulltask
      },
      cssClass: 'modal modal-desktop'
    });
    await modal.present();

  }

  getDocumentDetails(forlderId: string, applicationId: string) {
    this.processes.GetDocumentDetails(forlderId, applicationId).subscribe(res => {
      this.attachments = res.Documents;
      console.log(res['Documents']);
      console.log(this.attachments);
    })
  }

  async askSignature(note: string, documents: any) {
    let body = {
      "serialNumber": this.serialNumber,
      "action": "Aprovar",
      "ActionTypeId": 99999840,
      "dataFields": {
        "ReviewUserComment": note,
      },
      "AttachmentList": documents,
    }

    const loader = this.toastService.loading()

    try {
      await this.processes.CompleteTask(body).toPromise()

      this.toastService._successMessage(false, () => {
        this.close();
      })

    } catch (error) {
      this.toastService._badRequest()
    }
    finally {
      loader.remove()
    }
  }

  async askToChange(note: string, documents: any) {
    let body = {
      "serialNumber": this.serialNumber,
      "action": "Retificar",
      "ActionTypeId": 99999841,
      "dataFields": {
        "ReviewUserComment": note,
      },
      "AttachmentList": documents,
    }

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

  }

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

    let body = {
      "serialNumber": this.serialNumber,
      "action": "Concluir",
      "ActionTypeId": 95,
      "dataFields": {
        "ReviewUserComment": note,
      },
      "AttachmentList": documents,
    }

    const loader = this.toastService.loading()

    try {
      await this.processes.CompleteTask(body).toPromise();
      this.toastService._successMessage('Processo concluído')
    } catch (error) {
      this.toastService._badRequest()
    }
    finally {
      loader.remove()
    }

  }

  toDateString(e) {
    return new Date(e).toDateString()
  }

  async openAddNoteModal(actionName: string) {
    let classs;
    if (window.innerWidth <= 800) {
      classs = 'modal modal-desktop'
    } else {
      classs = 'add-note-modal'
    }
    const modal = await this.modalController.create({
      component: AddNotePage,
      componentProps: {
      },
      cssClass: classs,
      backdropDismiss: true
    });

    await modal.present();

    modal.onDidDismiss().then(async (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 == 'Solicitar assinatura') {
          await this.askSignature(res.data.note, docs);
          this.goBack();
        }
        else if (actionName == 'Solicitar alteração') {
          await this.askToChange(res.data.note, docs);
          this.goBack();
        }
        else if (actionName == 'Concluir diploma') {
          await this.finish(res.data.note, docs);
          this.goBack();
        }
      }
    });
  }

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

  close() {
    this.modalController.dismiss();
  }


}
