import { Component, OnInit, ViewChild } from '@angular/core';
import { AlertController, AnimationController, ModalController, NavParams } from '@ionic/angular';
import { Attachment } from 'src/app/models/attachment.model';
import { EventPerson } from 'src/app/models/eventperson.model';
import { SearchList } from 'src/app/models/search-document';
import { AttendeesPageModal } from 'src/app/pages/events/attendees/attendees.page';
import { SearchPage } from 'src/app/pages/search/search.page';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { EventsService } from 'src/app/services/events.service';
import { ProcessesService } from 'src/app/services/processes.service';
import { ToastService } from 'src/app/services/toast.service';
import { Event, EventToApproveEdit } from '../../../models/event.model';
import { NgxMatDateFormats, NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker';
import { NavigationExtras, Router } from '@angular/router';
import { ThemeService } from 'src/app/services/theme.service'

const CUSTOM_DATE_FORMATS: NgxMatDateFormats = {
  parse: {
    dateInput: "YYYY-MMMM-DD HH:mm"
  },
  display: {
    dateInput: "DD MMM YYYY H:mm",
    monthYearLabel: "MMM YYYY",
    dateA11yLabel: "LL",
    monthYearA11yLabel: "MMMM YYYY"
  }
}


@Component({
  selector: 'app-edit-event',
  templateUrl: './edit-event.page.html',
  styleUrls: ['./edit-event.page.scss'],
  providers: [
    { provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
  ]
})
export class EditEventToApproveComponent implements OnInit {

  public date: any;
  public disabled = false;
  public showSpinners = true;
  public showSeconds = false;
  public touchUi = false;
  public enableMeridian = false;
  public minDate = new Date().toISOString().slice(0,10)
  public endMinDate = new Date(new Date().getTime() + 15 * 60000);
  public maxDate: any;
  public stepHour = 1;
  public stepMinute = 5;
  public stepSecond = 5;
  recurringTypes: any;
  selectedRecurringType: any;

  showLoader = false

  @ViewChild('picker') picker: any;
  @ViewChild('fim') fim: any;
  @ViewChild('inicio') inicio: any;
  @ViewChild('picker1') picker1: any;

  serialNumber: string
  loadedAttachments: Attachment[]= []

  eventProcess = {
    serialNumber: "",
    taskStartDate: "",
    workflowInstanceDataFields:{
      Body: "",
      OccurrenceType: '',
      Category: '',
      LastOccurrence: new Date(),
      ParticipantsList: [],
      Agenda: '',
      EndDate: '',
      Location: '',
      Subject: '',
      InstanceId: '',
      EventType: '',
      StartDate: '',
      MDEmail: '',
      MDName: '',
      IsAllDayEvent: false,
      Message: '',
      IsRecurring: false
    }
  }

  show = false

  postEvent: Event;
  isRecurring:string;
  isEventEdited: boolean;
  segment:string = "true";
  profile:string;
  eventAttendees: EventPerson[];
  startDate: Date;
  endDate: Date;
  loadedEventAttachments: Attachment[];
  taskParticipants: any = [];
  taskParticipantsCc: any = [];
  adding: "intervenient" | "CC" = "intervenient";

  Location = ''

  showAttendees = false;

  InstanceId: string

  constructor(
    private modalController: ModalController,
    private navParams: NavParams,
    private eventsService: EventsService,
    public alertController: AlertController,
    private attachmentsService: AttachmentsService,
    private processes:ProcessesService,
    private animationController: AnimationController,
    private toastService: ToastService,
    private router:Router,
    public ThemeService: ThemeService
  ) {
    // Edit event to approve
    this.serialNumber = this.navParams.get('serialNumber');
    this.isEventEdited = false;
  }



  ngOnInit() {
    this.getTask()
    this.getRecurrenceTypes();
  }

  async getTask() {

    const result = await this.processes.GetTask(this.serialNumber).toPromise();
    console.log(result);
    
    this.eventProcess = result
    this.eventProcess.workflowInstanceDataFields.Category = result.workflowInstanceDataFields.EventType
    this.eventProcess.workflowInstanceDataFields.LastOccurrence = new Date(this.eventProcess.workflowInstanceDataFields.LastOccurrence)

    this.startDate = new Date(this.eventProcess.workflowInstanceDataFields.StartDate);
    this.endDate = new Date(this.eventProcess.workflowInstanceDataFields.EndDate);

    // description
    let body : any =this.eventProcess.workflowInstanceDataFields.Body.replace(/<[^>]+>/g, '')
    this.eventProcess.workflowInstanceDataFields.Body = body
    this.Location = this.eventProcess.workflowInstanceDataFields.Location

    this.InstanceId = this.eventProcess.workflowInstanceDataFields.InstanceId
    try {
      this.getAttachments()

    } catch (error) {

    }


    if(this.eventProcess.workflowInstanceDataFields.IsRecurring == false) {
      this.isRecurring = "Não se repete";
    }
    else {
      this.isRecurring = "Repete";
    }

    this.eventProcess.workflowInstanceDataFields.ParticipantsList.forEach(e => {
      if(e.IsRequired) {
        this.taskParticipants.push(e);
      } else {
        this.taskParticipantsCc.push(e);
      }
    })
    /* }) */
  }

  getRecurrenceTypes() {
    this.eventsService.getRecurrenceTypes().subscribe(res=>{
      console.log(res);
      this.recurringTypes = res;
    });
  }

  onSelectedRecurringChanged(ev:any){
    /* console.log(ev);
    if(ev.length > 1){
      console.log(ev.filter(data => data != '-1'));
      this.selectedRecurringType = ev.filter(data => data != '-1');
    }
    if(ev.length == 0){
      this.selectedRecurringType = "-1";
    } */
  }

  openLastOccurrence() {
    let input: any = document.querySelector('#last-occurrence')
    if(input) {
      input.click()
    }
  }

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

  }



  close() {
    this.modalController.dismiss();
    console.log('CLOSE');

  }

  save() {
    // set dates to eventProcess object

    this.taskParticipantsCc.forEach(e=>{
      e.IsRequired = false
    })

    this.eventProcess.workflowInstanceDataFields.ParticipantsList = this.taskParticipants.concat(this.taskParticipantsCc)

    this.eventProcess.workflowInstanceDataFields.ParticipantsList.forEach(e=>{

      if(e.hasOwnProperty('$type')) {
        delete e.$type
      }
    })

    const event: EventToApproveEdit = {
      SerialNumber: this.eventProcess.serialNumber,
      Body: this.eventProcess.workflowInstanceDataFields.Body,
      Location: this.eventProcess.workflowInstanceDataFields.Location,
      Subject: this.eventProcess.workflowInstanceDataFields.Subject,
      StartDate: this.startDate,
      EndDate: this.endDate,
      ReviewUserComment: '',
      MDName: this.eventProcess.workflowInstanceDataFields.MDName,
      MDEmail: this.eventProcess.workflowInstanceDataFields.MDEmail,
      IsAllDayEvent: this.eventProcess.workflowInstanceDataFields.IsAllDayEvent,
      Status: null,
      Agenda: this.eventProcess.workflowInstanceDataFields.Agenda,
      EventType: this.eventProcess.workflowInstanceDataFields.EventType,
      IsRecurring: this.eventProcess.workflowInstanceDataFields.IsRecurring,
      Message: this.eventProcess.workflowInstanceDataFields.Message,
      EventRecurrence: {
        Type: this.eventProcess.workflowInstanceDataFields.OccurrenceType,
        LastOccurrence: this.eventProcess.workflowInstanceDataFields.LastOccurrence,
      },
      ParticipantsList: this.eventProcess.workflowInstanceDataFields.ParticipantsList,
      Category: this.eventProcess.workflowInstanceDataFields.Category
    }


    this.eventsService.postEventToApproveEdit(event).subscribe(()=>{
      this.toastService.successMessage('Evento editado');
    }, error =>{
      this.toastService.badRequest('Evento não editado');
    })


    this.loadedAttachments.forEach((document:any)=>{
      if(document['action'] == 'add') {
        delete document.action
        this.attachmentsService.setEventAttachmentById(document).subscribe(()=>{
          this.toastService.successMessage();
        }, error =>{
          this.toastService.badRequest();
        });
      } else if(document['action'] == 'delete') {
        delete document.action
        this.attachmentsService.deleteEventAttachmentById(document.Id).subscribe( res=>{
          this.toastService.successMessage()
        }, error =>{
          this.toastService.badRequest()
        })
      }

    })

    this.modalController.dismiss();
    this.goBack();

  }

  async openAttendees() {

    if(window.innerWidth <= 1024) {
      const modal = await this.modalController.create({
        component: AttendeesPageModal,
         componentProps: {
          adding: this.adding,
          taskParticipants: this.taskParticipants,
          taskParticipantsCc: this.taskParticipantsCc
        },
        cssClass: 'attendee modal modal-desktop',
        backdropDismiss: false
      });

      await modal.present();

      modal.onDidDismiss().then((data) => {

        if(data) {
          data = data['data'];

          const newAttendees: EventPerson[] = data['taskParticipants'];
          const newAttendeesCC: EventPerson[] = data['taskParticipantsCc'];

          if(newAttendees.length) {
            this.setIntervenient(newAttendees);
          }
          if(newAttendeesCC) {
            this.setIntervenientCC(newAttendeesCC);
          }
          
        }
      });
    } else {
      this.showAttendees = true
    }
  }

  setIntervenient(data = []) {
    this.taskParticipants = data;
  }

  setIntervenientCC(data = []) {
    this.taskParticipantsCc = data;
  }

  addParticipants() {
    this.adding = 'intervenient'
    this.openAttendees();
  }

  addParticipantsCC() {

    this.adding = 'CC'
    this.openAttendees();
  }

  dynamicSetIntervenient({taskParticipants, taskParticipantsCc}) {
    this.taskParticipants = taskParticipants;
    this.taskParticipantsCc = taskParticipantsCc;
  }


  async getAttachments() {

   let result: any = await this.attachmentsService.getAttachmentsById(this.InstanceId).toPromise();

    result.forEach((e)=>{
      e.action = false
    })

    this.loadedAttachments = result

    // console.log('this.loadedAttachments', this.loadedAttachments, result)
  }

  deleteAttachment(attachment: Attachment, index) {

    this.loadedAttachments[index]['action'] = 'delete'
  }

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

        const data: SearchList = res.data.selected;

        const DocumentToSave: any = {
          SourceTitle: data.Assunto,
          ParentId: this.InstanceId,
          Source: '1',
          SourceId: data.Id,
          ApplicationId: data.ApplicationType.toString(),
          Id: '',
          Link: '',
          SerialNumber: '',
          action: 'add',
          CreateDate: data.Data,
          Data: data.Data,
          Description: data.DocTypeDesc,
          SourceName: data.Assunto,
          Stakeholders: data.EntidadeOrganicaNome,
        };


        this.loadedAttachments.push(DocumentToSave)
        console.log('push', DocumentToSave)

        // await this.attachmentsService.setEventAttachmentById(DocumentToSave).subscribe(()=>{
        //   this.getAttachments();
        // });
      }
    });
  }




}
