import { Component, OnInit } from '@angular/core';
import { ProcessesService } from 'src/app/services/processes.service';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { EventsService } from 'src/app/services/events.service';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ActivatedRoute, Router } from '@angular/router';
import { Event } from '../../../../models/event.model';
import { ModalController, PopoverController } from '@ionic/angular';
import { ExpedientTaskModalPage } from '../expedient-task-modal/expedient-task-modal.page';
import { BookMeetingModalPage } from '../book-meeting-modal/book-meeting-modal.page';
import { ViewEventPage } from 'src/app/pages/agenda/view-event/view-event.page';
import { momentG } from 'src/plugin/momentG'
import { DiscartExpedientModalPage } from '../../discart-expedient-modal/discart-expedient-modal.page';
import { OptsExpedientePage } from 'src/app/shared/popover/opts-expediente/opts-expediente.page';
import { ToastService } from 'src/app/services/toast.service';
import { Location } from '@angular/common';
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchList } from 'src/app/models/search-document';
import { AddNotePage } from 'src/app/modals/add-note/add-note.page';
import { SearchDocumentPipe } from 'src/app/pipes/search-document.pipe';
import { ExpedienteService } from 'src/app/Rules/expediente.service';
import { expedienteTask } from 'src/app/models/dailyworktask.model';
import { TaskService } from 'src/app/Rules/task.service';
import { DocumentViewerPage } from 'src/app/modals/document-viewer/document-viewer.page';
import { PermissionService } from 'src/app/services/worker/permission.service';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';
import { ThemeService } from 'src/app/services/theme.service'


import { SqliteService } from 'src/app/services/sqlite.service';
import { Platform } from '@ionic/angular';
import { BackgroundService } from 'src/app/services/background.service';
import { NewGroupPage } from 'src/app/pages/chat/new-group/new-group.page';
import { DataService } from 'src/app/services/data.service';
import { RouteService } from 'src/app/services/route.service';

@Component({
  selector: 'app-expediente-detail',
  templateUrl: './expediente-detail.page.html',
  styleUrls: ['./expediente-detail.page.scss'],
})
export class ExpedienteDetailPage 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: expedienteTask;
  fulltask: any;
  eventsList: Event[];
  serialNumber: string;
  caller: string;
  profile: string;
  intervenientes: any;
  cc: any = [];
  documents: SearchList[] = [];
  attachments: any;

  hideSendToPendentes = true
  searchDocumentPipe = new SearchDocumentPipe()

  onlinecheck: boolean;

  constructor(
    private processes: ProcessesService,
    private iab: InAppBrowser,
    //private attachments: AttachmentsService,
    private events: EventsService,
    private router: Router,
    private modalController: ModalController,
    public popoverController: PopoverController,
    private activatedRoute: ActivatedRoute,
    private toastService: ToastService,
    private RouteService: RouteService,
    private attachmentsService: AttachmentsService,
    public p: PermissionService,
    private taskService: TaskService,
    private expedienteService: ExpedienteService,
    public platform: Platform,
    private sqliteservice: SqliteService,
    private backgroundservice: BackgroundService,
    public ThemeService: ThemeService,
    private dataService: DataService,
  ) {
    this.activatedRoute.paramMap.subscribe(params => {
      if (params["params"].SerialNumber) {
        this.serialNumber = params["params"].SerialNumber;
      }
      if (params["params"].caller) {
        this.caller = params["params"].caller;
      }
    });
  }

  ngOnInit() {

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

  }

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

  showToast() {
    this.toastService.presentToast('Não foi possível fazer login');
  }

  updateProcessDB(res) {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      this.sqliteservice.updateProcess(res)
    }
  }
  getFromDB() {

    this.platform.ready().then(() => {
      this.onlinecheck = false;
      this.sqliteservice.getProcessById(this.serialNumber).then((process) => {
        console.log("expedient ditail", process)

        var workflow = JSON.parse(process[0].workflowInstanceDataFields);
        var origina
        if (process[0].originator === "undefined") {
          origina = ""
        } else {
          origina = JSON.parse(process[0].originator)
        }

        this.task = {
          "SerialNumber": process[0].serialNumber,
          "Folio": workflow.Subject,
          "Senders": origina.email || process[0].originator,
          "CreateDate": momentG(new Date(process[0].taskStartDate), 'yyyy-MM-dd HH:mm:ss'),
          "DocumentURL": workflow.ViewerRequest,
          "Remetente": workflow.Sender,
          "Note": workflow.TaskMessage || workflow.Note,
          "FolderId": workflow.FolderID,
          "FsId": workflow.FsId,
          "DocId": workflow.DocID,
          "WorkflowName": process[0].workflowDisplayName,
          "Status": workflow.Status,
          "DispatchNumber": workflow.DispatchNumber,
          "AttachmentsProcessLastInstanceID": workflow.AttachmentsProcessLastInstanceID,
          "InstanceID": workflow.InstanceID
        }

        this.fulltask = {
          Documents: JSON.parse(process[0].Documents),
          actions: JSON.parse(process[0].actions),
          activityInstanceName: process[0].activityInstanceName,
          formURL: process[0].formURL,
          interveners: process[0].interveners,
          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,
        }

      })
    })
  }


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

    console.log(body);

    const loader = this.toastService.loading()

    try {
      await this.processes.CompleteTask(body).toPromise();
      this.close();
      this.toastService._successMessage('Processo aprovado')
    } catch (error) {
      this.toastService._badRequest('Processo não aprovado')
    } finally {
      loader.remove()
    }

  }

  async sendToReview(note: string, documents: any) {
    let body = {
      "serialNumber": this.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()
    }
  }


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

    await modal.present();

    modal.onDidDismiss().then(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') {
          this.approve(res.data.note, docs);
        }
        else if (actionName == 'Revisão') {
          this.sendToReview(res.data.note, docs);
        }
        this.goBack();
      }
    });
  }


  goBack() {
    this.RouteService.goBack();
    /* if(this.task.Status == "Pending" && this.caller != 'events'){
      if (window.innerWidth <= 800) {
        this.router.navigate(['/home/gabinete-digital/pendentes']);
      }
      else {
        let navigationExtras: NavigationExtras = {
          queryParams: {
              "pendentes": true,
            }
        }
        this.router.navigate(['/home/gabinete-digital'], navigationExtras);
      }
    }
    else{
      this.activatedRoute.paramMap.subscribe(params => {
        switch (params["params"].caller) {
          case 'events':
            this.router.navigate(['/home',params["params"].caller]);
            break;

          case 'gabinete-digital':
            let navigationExtras: NavigationExtras = {
              queryParams: {
                "expedientes": true,
              }
            }
            if( window.innerWidth < 801) {
              this.router.navigate(['/home/gabinete-digital/expediente']);
            } else {
              this.router.navigate(['/home/gabinete-digital'], navigationExtras);
            }
            break;

        }
      });
    } */
  }

  sendExpedienteToPending() {
    this.processes.SetTaskToPending(this.serialNumber).subscribe(res => {
      console.log(res);
      this.toastService._successMessage('Processo enviado para pendentes')
      this.goBack();
    },
      (error) => {
        this.toastService._badRequest('Processo não enviado para pendentes')
      });
  }

  async LoadTaskDetail(serial: string) {

    this.processes.GetTask(serial).subscribe(res => {
      console.log(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": res.workflowInstanceDataFields.FsId,
        "DocId": res.workflowInstanceDataFields.DocID,
        "WorkflowName": res.workflowDisplayName,
        "Status": res.workflowInstanceDataFields.Status,
        "DispatchNumber": res.workflowInstanceDataFields.DispatchNumber,
        "AttachmentsProcessLastInstanceID": res.workflowInstanceDataFields.AttachmentsProcessLastInstanceID,
        "InstanceID": res.workflowInstanceDataFields.InstanceID
      }

      this.fulltask = res;
      this.updateProcessDB(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.intervenientes = users.filter(user => {
          return user.Type == 'I';
        });
        this.cc = users.filter(user => {
          return user.Type == 'CC';
        });
      })

      console.log('this.task', this.task.InstanceID)
      console.log('this.task.DocumentURL', this.fulltask)

    }, (error) => {

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



  }

  async LoadRelatedEvents(serial: string) {

  }

  async viewDocument(DocId: string, Document) {

    // this.expedienteService.viewDocument({ApplicationId:'361', DocId})

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

  }

  // viewDocument(DocId:string) {

  //   this.expedienteService.viewDocument({ApplicationId:'361', DocId})
  // }

  getAttachments(serialNumber) {
    console.log(serialNumber);

    this.attachmentsService.getAttachmentsBySerial(serialNumber).subscribe(res => {
      this.attachments = res;
      console.log('res', res);
    });
  }

  attachDocument() {
    this.getDoc();
  }

  async getDoc() {
    const modal = await this.modalController.create({
      component: SearchPage,
      cssClass: 'modal-width-100-width-background modal',
      componentProps: {
        type: 'Correspondencia',
        showSearchInput: true,
        select: true,
        findOnly: [8]
      }
    });
    await modal.present();
    modal.onDidDismiss().then(async (res) => {
      if (res) {
        const data = res.data;
        this.documents.push(data.selected);
        await this.documents.forEach( async (element: any) => {

          let body = {
            "InstanceID": this.task.InstanceID,
            "WorkflowDisplayName": this.task.WorkflowName,
            "FolderID": this.task.FolderId,
            "DispatchNumber": this.task.DispatchNumber,
            "AttachmentsProcessLastInstanceID": this.task.AttachmentsProcessLastInstanceID,
            "Attachments": []
          }

          const Attachments = this.searchDocumentPipe.transformToAttachment(element)
          body.Attachments = Attachments;

          const loader = this.toastService.loading()

          try {
            loader.remove()
            await this.attachmentsService.AddAttachment(body).toPromise()
            this.toastService._successMessage()
          } catch(e) {
            this.toastService._badRequest()
          }
        });
      }
      setTimeout(() => {
        this.LoadTaskDetail(this.serialNumber);
      }, 5000);

    });
  }

  async openExpedientActionsModal(taskAction: any, task: any) {
    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,
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then(async (res) => {
      let body = res['data'];
      if (res['data']) {
        const loader = this.toastService.loading()
        try {
          await this.processes.CompleteTask(body).toPromise();
          this.goBack();
        } catch (error) {
          this.toastService._badRequest('Processo não descartado')
        } finally {
          loader.remove()
        }
      }
      else {
        this.close();
      }
    });
  }

  async distartExpedientModal(body: any) {
    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') {

          const loader = this.toastService.loading()

          try {
            await this.expedienteService.discard({ SerialNumber: this.task.SerialNumber }).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.expedienteService.CompleteTask(body).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') {
          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 openBookMeetingModal(task: any) {
    console.log(task);

    let classs;
    if (window.innerWidth < 701) {
      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().then(res => {

    });
  }

  goToEvent(eventId: any) {
    this.router.navigate(['/home/events', eventId, 'expediente']);
  }

  async viewEventDetail(eventId: any) {
    console.log(this.profile);

    const modal = await this.modalController.create({
      component: ViewEventPage,
      componentProps: {
        eventId: eventId,
        profile: this.profile,
      },
      cssClass: 'modal modal-desktop',
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss().then((res) => {
      if (res) {
      }
    });
  }

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

  openNewGroupPage() {
    if (window.innerWidth < 701) {
      this.router.navigate(['/home/chat']);
      this.newGroup();
    }
    else {
      this.dataService.set("newGroup", true);
      this.dataService.set("task", this.task);
      this.dataService.set("newGroupName", this.task.Folio);
      this.dataService.set("documents", this.fulltask.Documents);
      this.router.navigate(['/home/chat']);
    }
  }

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

}
