import { Component, OnInit } from '@angular/core';
import { ProcessesService } from 'src/app/services/processes.service';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { Event } from '../../../../models/event.model';
import { AnimationController, MenuController, ModalController, PopoverController } from '@ionic/angular';
import { AlertService } from 'src/app/services/alert.service';
import { DiscartExpedientModalPage } from '../../discart-expedient-modal/discart-expedient-modal.page';
import { BookMeetingModalPage } from '../../expediente/book-meeting-modal/book-meeting-modal.page';
import { CreateProcessPage } from 'src/app/modals/create-process/create-process.page';
import { DelegarPage } from 'src/app/modals/delegar/delegar.page';
import { DarParecerPage } from 'src/app/modals/dar-parecer/dar-parecer.page';
import { AddNotePage } from 'src/app/modals/add-note/add-note.page';
import { RequestOptionsPage } from 'src/app/shared/popover/request-options/request-options.page';
import { AuthService } from 'src/app/services/auth.service';
import { LoginUserRespose } from 'src/app/models/user.model';
import { ToastService } from 'src/app/services/toast.service';
import { ForwardPage } from 'src/app/modals/forward/forward.page';
import { Platform } from '@ionic/angular';
import { Location } from '@angular/common';
import { PedidoService } from 'src/app/Rules/pedido.service';

import { SqliteService } from 'src/app/services/sqlite.service';
import { BackgroundService } from 'src/app/services/background.service';

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 { DataService } from 'src/app/services/data.service';
import { NewGroupPage } from 'src/app/pages/chat/new-group/new-group.page';
import { RouteService } from 'src/app/services/route.service';

@Component({
  selector: 'app-pedido',
  templateUrl: './pedido.page.html',
  styleUrls: ['./pedido.page.scss'],
})
export class PedidoPage 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;
  attachments: any;
  fulltask: any;
  eventsList: Event[];
  serialnumber: string;
  caller: string;
  intervenientes: any;
  cc: any = [];
  loggeduser: LoginUserRespose;

  constructor(private activatedRoute: ActivatedRoute,
    private processes: ProcessesService,
    private iab: InAppBrowser,
    private menu: MenuController,
    private router: Router,
    private modalController: ModalController,
    private alertService: AlertService,
    public popoverController: PopoverController,
    authService: AuthService,
    private animationController: AnimationController,
    private toastService: ToastService,
    public p: PermissionService,
    private RouteService: RouteService,
    private pedidoService: PedidoService,
    private sqliteservice: SqliteService,
    private backgroundservices: BackgroundService,
    private platform: Platform,
    public ThemeService: ThemeService,
    private dataService: DataService,
  ) {
    this.loggeduser = authService.ValidatedUser;

    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.LoadTaskDetail(this.serialnumber);
    this.backgroundservices.registerBackService('Online', () => {
      this.LoadTaskDetail(this.serialnumber);
    });
  }

  close() {
    this.modalController.dismiss();
  }
  notImplemented() {
    this.alertService.presentAlert('Funcionalidade em desenvolvimento');
  }

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

  async LoadTaskDetail(serial: string) {
    this.processes.GetTask(this.serialnumber).subscribe(res => {

      this.fulltask = res
      console.log('FULLTAK ONLINe', this.fulltask);

      if (res.workflowDisplayName == 'Pedido de Parecer' || res.workflowDisplayName == 'Pedido de Parecer do Presidente') {

        let date = new Date(res.taskStartDate);
        date.setMonth(date.getMonth() + 1);
        let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

        this.task = {
          "SerialNumber": res.serialNumber,
          "Folio": res.workflowInstanceDataFields.Subject,
          "Senders": res.workflowInstanceDataFields.Sender,
          "CreateDate": taskDate,
          "DocumentURL": res.workflowInstanceDataFields.ViewerRequest,
          "Remetente": res.workflowInstanceDataFields.Sender,
          "Note": res.workflowInstanceDataFields.TaskMessage,
          "FolderId": res.workflowInstanceDataFields.FolderID,
          "FsId": '361',
          "DocId": res.workflowInstanceDataFields.ParecerDocId,
          "WorkflowName": res.workflowDisplayName,
          "DeadlineType": res.workflowInstanceDataFields.DeadlineType,
          "ProcessInstanceID": res.workflowInstanceDataFields.InstanceID,
          "activityInstanceName": res.activityInstanceName,
          "Status": res.workflowInstanceDataFields.Status,
        }
        console.log(this.task);
        this.updateProcess(res);
      }
      else if (res.workflowDisplayName == 'Pedido de Deferimento') {

        let date = new Date(res.taskStartDate);
        date.setMonth(date.getMonth() + 1);
        let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

        this.task = {
          "SerialNumber": res.serialNumber,
          "Folio": res.workflowInstanceDataFields.Subject,
          "Senders": res.workflowInstanceDataFields.Sender,
          "CreateDate": taskDate,
          "DocumentURL": res.workflowInstanceDataFields.ViewerRequest,
          "Remetente": res.workflowInstanceDataFields.Sender,
          "Note": res.workflowInstanceDataFields.TaskMessage,
          "FolderId": res.workflowInstanceDataFields.FolderID,
          "FsId": '361',
          "DocId": res.workflowInstanceDataFields.DocIdDeferimento,
          "WorkflowName": res.workflowDisplayName,
          "DeadlineType": res.workflowInstanceDataFields.DeadlineType,
          "ProcessInstanceID": res.workflowInstanceDataFields.InstanceID,
          "activityInstanceName": res.activityInstanceName,
          "Status": res.workflowInstanceDataFields.Status,
        }
        this.updateProcess(res)
      }

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

      this.processes.GetTaskParticipants(res.workflowInstanceDataFields.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(res.workflowInstanceDataFields.FolderID, '361');
    }, (error) => {
      if (error.status == 0) {
        this.getfromDb();
      } else {
        try {
          this.goBack()
          this.close()
        } catch (e) {
          window.history.back();
        }
        this.toastService._badRequest('Processo não encontrado')
      }

    });
  }

  updateProcess(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() {
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      this.sqliteservice.getProcessById(this.serialnumber).then((process) => {

        console.log('PROCESS BY ID', process, this.serialnumber)

        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;
        console.log('FULLTAK OFFLINE', this.fulltask);

        if (process[0].workflowDisplayName == 'Pedido de Parecer' || process[0].workflowDisplayName == 'Pedido de Parecer do Presidente') {
          let date = new Date(process[0].taskStartDate);
          date.setMonth(date.getMonth() + 1);
          let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

          this.task = {
            "SerialNumber": process[0].serialNumber,
            "Folio": JSON.parse(process[0].workflowInstanceDataFields).Subject,
            "Senders": JSON.parse(process[0].workflowInstanceDataFields).Sender,
            "CreateDate": taskDate,
            "DocumentURL": JSON.parse(process[0].workflowInstanceDataFields).ViewerRequest,
            "Remetente": JSON.parse(process[0].workflowInstanceDataFields).Sender,
            "Note": JSON.parse(process[0].workflowInstanceDataFields).TaskMessage,
            "FolderId": JSON.parse(process[0].workflowInstanceDataFields).FolderID,
            "FsId": '361',
            "DocId": JSON.parse(process[0].workflowInstanceDataFields).DocIdDeferimento,
            "WorkflowName": process[0].workflowDisplayName,
            "DeadlineType": JSON.parse(process[0].workflowInstanceDataFields).DeadlineType,
            "ProcessInstanceID": JSON.parse(process[0].workflowInstanceDataFields).InstanceID,
            "activityInstanceName": process[0].activityInstanceName,
            "Status": JSON.parse(process[0].workflowInstanceDataFields).Status,
          }

          this.attachments = JSON.parse(process[0].Documents);
        } else if (process[0].workflowDisplayName == 'Pedido de Deferimento') {

          let date = new Date(process[0].taskStartDate);
          date.setMonth(date.getMonth() + 1);
          let taskDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
          this.task = {
            "SerialNumber": process[0].serialNumber,
            "Folio": JSON.parse(process[0].workflowInstanceDataFields).Subject,
            "Senders": JSON.parse(process[0].workflowInstanceDataFields).Sender,
            "CreateDate": taskDate,
            "DocumentURL": JSON.parse(process[0].workflowInstanceDataFields).ViewerRequest,
            "Remetente": JSON.parse(process[0].workflowInstanceDataFields).Sender,
            "Note": JSON.parse(process[0].workflowInstanceDataFields).TaskMessage,
            "FolderId": JSON.parse(process[0].workflowInstanceDataFields).FolderID,
            "FsId": '361',
            "DocId": JSON.parse(process[0].workflowInstanceDataFields).DocIdDeferimento,
            "WorkflowName": process[0].workflowDisplayName,
            "DeadlineType": JSON.parse(process[0].workflowInstanceDataFields).DeadlineType,
            "ProcessInstanceID": JSON.parse(process[0].workflowInstanceDataFields).InstanceID,
            "activityInstanceName": process[0].activityInstanceName,
            "Status": JSON.parse(process[0].workflowInstanceDataFields).Status,
          }
          this.attachments = JSON.parse(process[0].Documents);
        }

        let thedate = new Date(process[0].taskStartDate);
        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.getDocumentDetails(JSON.parse(process[0].workflowInstanceDataFields).FolderID, '361');

      })
    }
  }

  getDocumentDetails(forlderId: string, applicationId: string) {
    this.processes.GetDocumentDetails(forlderId, applicationId).subscribe(res => {
      this.attachments = res.Documents;
      console.log(res['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();

  }

  openMenu() {
    this.menu.open();
    this.modalController.dismiss();
  }

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

    popover.onDidDismiss().then((res => {

      if (res['data'] == 'close') {
        this.goBack()
      }

      // alert(JSON.stringify(res)+' nada')

    }))
  }

  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.toastService._successMessage()
      this.close();
    } catch (error) {
      this.toastService._badRequest()
    } finally {
      loader.remove()
    }
  }

  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')
      this.close();
    } catch (error) {
      this.toastService._badRequest()
    } finally {
      loader.remove()
    }

  }

  async assignar(note: string, documents: any) {
    let body = {
      "serialNumber": this.serialnumber,
      "action": "Reencaminhar",
      "ActionTypeId": 98,
      "dataFields": {
        "ReviewUserComment": note,
      },
      "AttachmentList": documents,
    }

    const loader = this.toastService.loading()

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

  }

  sendExpedienteToPending() {
    this.processes.SetTaskToPending(this.serialnumber).subscribe(res => {
      this.goBack();
    }, () => {

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

  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: CreateProcessPage,
      componentProps: {
        taskAction: taskAction,
        task: this.fulltask,
        fulltask: this.fulltask
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then(res => {
      console.log('Modal closed');
      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: task,
      },
      cssClass: classs,
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss();
  }

  openNewGroupPage() {
    if (window.innerWidth < 801) {
      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();
  }

  // async viewEventDetail(eventId: any) {

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

  async distartExpedientModal() {
    console.log(this.fulltask);
    const modal = await this.modalController.create({
      component: DiscartExpedientModalPage,
      componentProps: {
        serialNumber: this.fulltask.SerialNumber,
        folderId: this.fulltask.workflowInstanceDataFields.FolderID,
        action: 'complete',
      },
      cssClass: 'discart-expedient-modal',
      backdropDismiss: false
    });

    await modal.present();
    modal.onDidDismiss().then(res => {
      if (res['data'] == 'close') {
        this.close();
        /* console.log('2Expedient Discard closed2');
        this.close();
        this.openMenu(); */
      }

    });
  }

  async openDelegarModal(task: any) {
    console.log(task);

    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(res => {
      if(res){
        const data = res.data;
        if(data == 'close') {
          this.goBack();
        }
      }

    });
  }

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

  async openDarParecer(task: any) {
    console.log(task);

    let classs;
    if (window.innerWidth <= 800) {
      classs = 'book-meeting-modal modal modal-desktop'
    } else {
      classs = 'add-note-modal-no-height 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(res => {
      this.goBack();
    });
  }

  async openAddNoteModal(actionName: string) {
    let classs;
    if (window.innerWidth <= 800) {
      classs = 'modal modal-desktop'
    } else {
      classs = 'add-note-modal-no-height'
    }
    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 = await res.data.documents.map(async (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);
          this.goBack();
        }
        else if (actionName == 'Arquivar') {
          await this.arquivar(res.data.note, docs);
          this.goBack();
        }
        else if (actionName == 'Assignar') {
          await this.assignar(res.data.note, docs);
        }
      }
    });
  }

  goBack() {
    this.RouteService.goBack();
    // if(this.task.Status == "Pending" && this.caller == 'gabinete-digital'){
    //   if (window.innerWidth <= 700) {
    //     this.router.navigate(['/home/gabinete-digital/pendentes']);
    //   }
    //   else {

    //     let navigationExtras: NavigationExtras;

    //     if (this.task.activityInstanceName == 'Concluir Deferimento') {
    //       navigationExtras= { queryParams: {"deferimento": true,}};
    //     } else if (this.task.activityInstanceName == 'Tarefa de Parecer' ) {
    //       navigationExtras = { queryParams: {"parecer": true,}};
    //     }

    //     this.router.navigate(['/home/gabinete-digital'], navigationExtras);
    //   }
    // }
    // else {
    //   if (window.innerWidth <= 700) {
    //     this.router.navigate(['/home/gabinete-digital/pedidos']);
    //   }
    //   else {

    //     let navigationExtras: NavigationExtras;

    //     if (this.task.activityInstanceName == 'Concluir Deferimento') {
    //       navigationExtras= { queryParams: {"deferimento": true,}};
    //     } else if (this.task.activityInstanceName == 'Tarefa de Parecer' ) {

    //       navigationExtras = { queryParams: {"parecer": true,}};
    //     }
    //     this.router.navigate(['/home/gabinete-digital'], navigationExtras);
    //   }
    // }
  }

}
