import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { AlertController, ModalController, NavParams } from '@ionic/angular'; import { Attachment } from 'src/app/models/attachment.model'; import { EventBody } from 'src/app/models/eventbody.model'; import { EventPerson } from 'src/app/models/eventperson.model'; import { AttachmentsService } from 'src/app/services/attachments.service'; import { EventsService } from 'src/app/services/events.service'; import { ToastService } from 'src/app/services/toast.service'; import { Event } from '../../../models/event.model'; import { AttendeesPageModal } from '../../events/attendees/attendees.page'; import { SearchPage } from '../../search/search.page'; import { ThemeService } from 'src/app/services/theme.service'; import { NgxMatDateFormats } from '@angular-material-components/datetime-picker'; import { NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker'; import { SessionStore } from 'src/app/store/session.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 EditEventPage implements OnInit { Form: FormGroup; validateFrom = false postEvent: Event; isRecurring:string; isEventEdited: boolean; loadedEvent: Event; eventBody: EventBody; segment:string = "true"; profile:string; eventAttendees: EventPerson[]; selectedSegment: string; selectedDate: Date; initCalendarName: string; caller:string; recurringTypes: any; selectedRecurringType: any; 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).toISOString().slice(0,10) public maxDate: any; public stepHour = 1; public stepMinute = 15; public stepSecond = 15; currentDate = this.roundTimeQuarterHour(); loadedEventAttachments: Attachment[] = []; taskParticipants: any = []; taskParticipantsCc: any = []; adding: "intervenient" | "CC" = "intervenient"; showAttendees = false; public listColors = ['primary', 'accent', 'warn']; public stepHours = [1, 2, 3, 4, 5]; public stepMinutes = [1, 5, 10, 15, 20, 25]; public stepSeconds = [1, 5, 10, 15, 20, 25]; sesseionStora = SessionStore constructor( private modalController: ModalController, private navParams: NavParams, private eventsService: EventsService, public alertController: AlertController, private attachmentsService: AttachmentsService, private toastService: ToastService, private router: Router, public ThemeService: ThemeService ) { /* this.postEvent = new Event(); */ this.isEventEdited = false; /* this.postEvent.EventRecurrence = { Type:'-1', LastOccurrence:''}; */ this.postEvent = this.navParams.get('event'); // console.log(this.postEvent); this.caller = this.navParams.get('caller'); this.initCalendarName = this.postEvent.CalendarName; if(this.postEvent){ if( this.postEvent.Body){ if(typeof(this.postEvent.Body.Text) == 'string'){ this.postEvent.Body.Text = this.postEvent.Body.Text.replace(/<[^>]+>/g, ''); } } } if(this.postEvent.Attendees == null) { this.taskParticipants = [] } else { this.postEvent.Attendees.forEach(e =>{ if(e.IsRequired){ this.taskParticipants.push(e); } else { this.taskParticipantsCc.push(e); } }) } if(this.postEvent.IsRecurring == false) { this.isRecurring = "Não se repete"; } else { this.isRecurring = "Repete"; } this.getAttachments(this.postEvent.EventId); } ngOnInit() { window.onresize = (event) => { // if not mobile remove all component if( window.innerWidth >= 1024) { this.modalController.dismiss(); } } if(window.innerWidth > 800){ this.showAttendees=true; } this.getRecurrenceTypes(); setTimeout(() => { this.selectedRecurringType = this.postEvent.EventRecurrence.Type.toString(); }, 500); } close() { this.modalController.dismiss(); } goBack() { this.router.navigate(['/home',this.caller]); } getRecurrenceTypes() { this.eventsService.getRecurrenceTypes().subscribe(res=>{ this.recurringTypes = res; }); } roundTimeQuarterHour() { var timeToReturn = new Date(); // var minutes = timeToReturn.getMinutes(); var minutes = timeToReturn.getMinutes(); var hours = timeToReturn.getHours(); // console.log("MINUTOS: " +minutes); // console.log("BEFORE MINUTES: " +(Math.round(minutes/15) * 15)); var m = (Math.round(minutes/15) * 15) % 60; // console.log("AFTER MINUTES: " +m); var h = minutes > 52 ? (hours === 23 ? 0 : ++hours) : hours; if (m == 0) { if(minutes > m){ m = m + 15; } timeToReturn.setHours(h); timeToReturn.setMinutes(m); }else{ if(minutes > m){ m = m + 15; timeToReturn.setHours(h); timeToReturn.setMinutes(m); }else { timeToReturn.setHours(h); timeToReturn.setMinutes(m); } } } onSelectedRecurringChanged(ev?:any) { this.calculetedLastOccurrence(ev); if(ev.length > 1){ this.selectedRecurringType = ev.filter(data => data != '-1'); } if(ev.length == 0){ this.selectedRecurringType = "-1"; } } calculetedLastOccurrence(type:number){ // console.log(type); var valor; var opcao: boolean; if (type == 0) { valor = 7; opcao = true; } else if(type == 1){ valor = 30; opcao = true; } else if(type == 2){ valor = 1; opcao = false; }else if(type == 3){ valor = 5; opcao = false; } this.defineLastOccurrence(valor, opcao); } defineLastOccurrence(valor:number, opcao:boolean){ var time = new Date(this.postEvent.EndDate); if (opcao == true) { time.setDate(time.getDate() + valor); this.postEvent.EventRecurrence.LastOccurrence = time; } else { time = new Date( time.getFullYear() + valor, time.getMonth(), time.getDate(), time.getHours(), time.getMinutes() ); this.postEvent.EventRecurrence.LastOccurrence = time; } } runValidation() { this.validateFrom = true } injectValidation() { this.Form = new FormGroup({ Subject: new FormControl(this.postEvent.Subject, [ Validators.required, // Validators.minLength(4) ]), Location: new FormControl(this.postEvent.Location, [ Validators.required, ]), CalendarName: new FormControl(this.postEvent.CalendarName, [ Validators.required ]), Categories: new FormControl(this.postEvent.Category, [ Validators.required ]), IsRecurring: new FormControl(this.postEvent.IsRecurring, [ Validators.required ]), dateOccurrence: new FormControl(this.postEvent.EventRecurrence.Type.toString() == '-1' ? ['ok']: this.postEvent.EventRecurrence.LastOccurrence && new Date(this.postEvent.EventRecurrence.LastOccurrence).getTime() > new Date(this.postEvent.EndDate).getTime() ? 'ok': null, [ Validators.required ]), Date: new FormControl(new Date(this.postEvent.StartDate).getTime() <= new Date(this.postEvent.EndDate).getTime()? 'ok': null,[ Validators.required ]), participantes: new FormControl(this.taskParticipants, [ Validators.required ]), }) } openInicio() { let input: any = document.querySelector('#new-inicio') if(input) { input.click() } } openFim() { let input: any = document.querySelector('#new-fim') if(input) { input.click() } } openLastOccurrence() { let input: any = document.querySelector('#last-occurrence') if(input) { input.click() } } save() { this.injectValidation() this.runValidation() if(this.Form.invalid) return false; if(this.selectedRecurringType != '-1'){ this.postEvent.EventRecurrence.Type = this.selectedRecurringType; } this.postEvent.Attendees = this.taskParticipants.concat(this.taskParticipantsCc) this.postEvent.EventRecurrence.Type = this.selectedRecurringType; if(this.sesseionStora.user.Profile == 'MDGPR' || this.sesseionStora.user.Profile == 'PR') { this.eventsService.editEvent(this.postEvent, 2, 3).subscribe(async () => { if(this.initCalendarName != this.postEvent.CalendarName) { let body = { "EventId": this.postEvent.EventId, "CalendarDestinationName": this.postEvent.CalendarName, } try { await this.eventsService.changeAgenda(body).toPromise(); } catch (error) {} finally { this.goBack(); } } this.toastService._successMessage(); }, error => { if(error.status != 0) this.toastService._badRequest() }); } else { this.eventsService.editEvent(this.postEvent, 2, 3, this.postEvent.CalendarId).subscribe(async () => { if(this.initCalendarName != this.postEvent.CalendarName) { let body = { "EventId": this.postEvent.EventId, "CalendarDestinationName": this.postEvent.CalendarName, } try { await this.eventsService.changeAgenda(body).toPromise(); } catch (error) {} finally { this.goBack(); } } this.toastService._successMessage(); }, error => { if(error.status != 0) this.toastService._badRequest() }); } this.isEventEdited = true; this.modalController.dismiss(this.isEventEdited); this.saveDocument() } saveDocument() { this.loadedEventAttachments.forEach((e) => { const id: any = e.Id const remove = e['remove'] if ( id == 'add') { //data.selected const DocumentToSave = { SourceTitle: e.SourceName, ParentId: this.postEvent.EventId, Source: '1', SourceId: e.SourceId, ApplicationId: e.ApplicationId.toString(), Id: '0', Link: '', SerialNumber: '', }; this.attachmentsService.setEventAttachmentById(DocumentToSave).subscribe(()=>{ this.getAttachments(this.postEvent.EventId); }); } else if(remove) { this.attachmentsService.deleteEventAttachmentById(e.Id).subscribe( res=> {}) } }) } async openAttendees() { if(window.innerWidth > 801) { this.showAttendees=true; } else { const modal = await this.modalController.create({ component: AttendeesPageModal, componentProps: { adding: this.adding, taskParticipants: this.taskParticipants, taskParticipantsCc: this.taskParticipantsCc }, cssClass: 'modal attendee 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); } else { this.setIntervenient([]); } if(newAttendeesCC) { this.setIntervenientCC(newAttendeesCC); } else { this.setIntervenientCC([]); } } }); } } setIntervenient(data) { this.taskParticipants = data; this.postEvent.Attendees = 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; } getAttachments(eventId: string){ this.attachmentsService.getAttachmentsById(eventId).subscribe(res=>{ this.loadedEventAttachments = res; }); } deleteAttachment(attachmentID: string, index) { const id: any = this.loadedEventAttachments[index].Id if(id == 'add') { this.loadedEventAttachments = this.loadedEventAttachments.filter((e,i)=> i!=index) } else { this.loadedEventAttachments[index]['remove'] = true } } 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 = res.data; const ApplicationIdDocumentToSave: any = { SourceName: data.selected.Assunto, ParentId: this.postEvent.EventId, SourceId: data.selected.Id, Stakeholders: false, ApplicationId: data.selected.ApplicationType.toString(), CreateDate: false, // needed to attach this document Id: 'add', SourceTitle: data.selected.Assunto, Source: '1', Link: '', SerialNumber: '', } this.loadedEventAttachments.push(ApplicationIdDocumentToSave) } }) } }