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 } from '@angular/router';
import { Event } from '../../../../models/event.model';
import { MenuController, ModalController, PopoverController } from '@ionic/angular';
import { momentG } from 'src/plugin/momentG'
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 { AddNotePage } from 'src/app/modals/add-note/add-note.page';
import { DespachosOptionsPage } from 'src/app/shared/popover/despachos-options/despachos-options.page';
import { ToastService } from 'src/app/services/toast.service';
import { DespachoService } from 'src/app/Rules/despacho.service'
import { Location } from '@angular/common'
import { fullTask } from 'src/app/models/dailyworktask.model';
import { AttachmentList } from 'src/app/models/Excludetask';
import { PermissionService } from 'src/app/services/worker/permission.service';
import { ViewDocumentPage } from 'src/app/modals/view-document/view-document.page';

import { SqliteService } from 'src/app/services/sqlite.service';
import { Platform } from '@ionic/angular';
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-despacho',
  templateUrl: './despacho.page.html',
  styleUrls: ['./despacho.page.scss'],
})
export class DespachoPage 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: customTask;
  task;

  attachments: any;
  fulltask: any;
  eventsList: Event[] = [];
  serialnumber: string;
  caller: string;
  profile: string;
  intervenientes: any;
  cc: any = [];

  constructor(private activateRoute: ActivatedRoute,
    private processes: ProcessesService,
    private iab: InAppBrowser,
    private menu: MenuController,
    private modalController: ModalController,
    public popoverController: PopoverController,
    private activatedRoute: ActivatedRoute,
    private toastService: ToastService,
    private despachoService: DespachoService,
    private RouteService: RouteService,
    public p: PermissionService,
    private sqliteservice: SqliteService,
    private platform: Platform,
    private backgroundservice: BackgroundService,
    public ThemeService: ThemeService


  ) {
    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.profile = "mdgpr";
    this.activateRoute.paramMap.subscribe(paramMap => {
      if (!paramMap.has('SerialNumber')) {
        return;
      }
    });
    this.LoadTaskDetail(this.serialnumber)
    this.backgroundservice.registerBackService('Online', () => {
      this.LoadTaskDetail(this.serialnumber)
    });

  }

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

  goBack() {

    //this.navigationService.back()
    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/despachos']);
    //   } else {
    //     let navigationExtras: NavigationExtras = {
    //       queryParams: {
    //         'despachos': true
    //       }
    //     }
    //     this.router.navigate(['/home/gabinete-digital'], navigationExtras);
    //   }
    // }
  }

  async LoadTaskDetail(serial: string) {
    this.processes.GetTask(serial).subscribe((res: fullTask) => {
      console.log('despacho detail', 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,
        "DocumentsQty": '',
        "WorkflowName": res.workflowDisplayName,
        "DeadlineType": res.workflowInstanceDataFields.DeadlineType,
        "activityInstanceName": res.activityInstanceName,
        "Status": res.workflowInstanceDataFields.Status,
      }

      this.updateProcessOnDB(res);
      this.fulltask = 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)
        console.log('interveniers online', users)

        this.intervenientes = users.filter(user => {
          console.log('interveniers online 2', users)
          return user.Type == 'I';
        });
        this.cc = users.filter(user => {
          console.log('interveniers online 3', users)
          return user.Type == 'CC';
        });
      });
    }, (error) => {
      if (error.status == 0) {
        this.getFromDb();
      } else {
        try {
          this.goBack()
        } catch (e) {
          this.RouteService.goBack();
        }
        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.platform.ready().then(() => {
      if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
      } else {
        this.sqliteservice.getProcessById(this.serialnumber).then((process) => {

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

          console.log('sqlite', process)

          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,
            "DocumentsQty": process[0].DocumentsQty,
            "WorkflowName": process[0].workflowDisplayName,
            "DeadlineType": workflow.DeadlineType,
            "activityInstanceName": process[0].activityInstanceName,
            "Status": workflow.Status,
          }

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

          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('interveniers offline', intervine)
          this.intervenientes = intervine.filter(user => {
            console.log('interveniers offline 2', user)
            return user.Type == 'I';
          });
          this.cc = intervine.filter(user => {
            console.log('interveniers offline 3', user)
            return user.Type == 'CC';
          });

        })
      }
    })
  }

  async viewDocument(docId: string, Document) {


    console.log(this.fulltask)

    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 executado(note: string, documents: any) {

    const loader = this.toastService.loading()

    try {
      await this.despachoService.executado(note, documents, this.serialnumber).toPromise();
      this.toastService.successMessage('Processo criado')
      this.close();
    } catch (error) {
      this.toastService.badRequest("Processo não criado")
    }
    finally {
      loader.remove()
    }
  }

  async arquivar(note: string, documents: AttachmentList) {

    const loader = this.toastService.loading()

    try {
      await this.despachoService.arquivar(note, documents, this.serialnumber).toPromise()
      this.toastService.successMessage('Processo descartado')
      this.close();
    } catch (error) {
      this.toastService.badRequest("Processo não descartado")
    }
    finally {
      loader.remove()
    }

  }

  async reexecute(note: string, documents: any) {
    let body = {
      "serialNumber": this.serialnumber,
      "action": "Reexecução",
      "ActionTypeId": 100000010,
      "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 generateDiploma(note:string, documents:any) {
    let body = { 
      "serialNumber": this.serialnumber, 
      "action": "Reencaminhar",
      "ActionTypeId": 99999839,
      "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()
    }

  }


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

  async sendExpedienteToPending() {

    this.despachoService.sendExpedienteToPending(this.serialnumber).subscribe(res => {
      this.goBack();
      this.toastService.successMessage()
    },
      error => {
        this.toastService.badRequest("Processo não enviado para despacho")
      });

  }

  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) => {
      if (res.data) {

        const DocumentToSave = res.data.documents.map((e) => {
          return {
            ApplicationId: e.ApplicationType,
            SourceId: e.Id,
          }
        });

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

        if (actionName == 'Executado') {

          await this.executado(res.data.note, docs);
          this.goBack();
        }
        else if (actionName == 'Arquivar') {
          await this.arquivar(res.data.note, docs);
          this.goBack();
        }
        else if (actionName == 'Reexecução') {
          await this.reexecute(res.data.note, docs);
          this.goBack();
        }  else if(actionName == 'Gerar Diploma') {
          await this.generateDiploma(res.data.note, docs);
          this.goBack();
        }
      }
    });
  }

  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: task,
        profile: this.profile,
        fulltask: this.fulltask
      },
      cssClass: classs,
    });
    await modal.present();
    modal.onDidDismiss().then(async (res) => {
      console.log(res['data']);

      if (res['data'] == 'openDiscart') {
        await this.distartExpedientModal();
      }

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

  async openDelegarModal(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: 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 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 openOptions(taskAction?: any) {

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


}
