import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AnimationController, ModalController, NavParams } from '@ionic/angular';
import { Event } from 'src/app/models/event.model'
import { EventBody } from 'src/app/models/eventbody.model';
import { ProcessesService } from 'src/app/services/processes.service';
import { EventPerson } from 'src/app/models/eventperson.model';
import { EventsService } from 'src/app/services/events.service';
import { DiscartExpedientModalPage } from '../../discart-expedient-modal/discart-expedient-modal.page';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { SearchPage } from 'src/app/pages/search/search.page';
import { SearchList } from 'src/app/models/search-document';
import { LoginUserRespose } from 'src/app/models/user.model';
import { AuthService } from 'src/app/services/auth.service';
import { AttendeesPageModal } from 'src/app/pages/events/attendees/attendees.page';
import { ToastService } from 'src/app/services/toast.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import * as _moment from 'moment';
import * as _rollupMoment from 'moment';
import { NgxMatDateFormats } from '@angular-material-components/datetime-picker';
import { NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker';
import { ThemeService } from 'src/app/services/theme.service'


const moment = _rollupMoment || _moment;

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-book-meeting-modal',
  templateUrl: './book-meeting-modal.page.html',
  styleUrls: ['./book-meeting-modal.page.scss'],
  providers: [
    { provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
  ]
})

export class BookMeetingModalPage implements OnInit {

  public date: any;
  public disabled = false;
  public showSpinners = true;
  public showSeconds = false;
  public touchUi = false;
  public enableMeridian = false;
  public minDate = new Date();
  public ionicMinDate = new Date().toISOString().slice(0,10)

  // curent timestamp + 15 minutes
  public endMinDate = new Date(new Date().getTime() + 15 * 60000);

  public stepHour = 1;
  public stepMinute = 5;
  public stepSecond = 5;

  public dateControlStart = new FormControl(moment("DD MM YYYY hh"));
  public dateControlEnd = new FormControl(moment("DD MM YYYY hh"));

  Form: FormGroup;
  validateFrom = false
  recurringTypes = [];
  Occurrence: Date = new Date()
  EventRecurrenceType = '-1'

  showLoader = false

  get dateStart () {
    if( window.innerWidth < 801) {
      return this.postData.StartDate;
    }
    else{
      return this.dateControlStart.value;
    }
  }

  get dateEnd () {
    if( window.innerWidth < 801) {
      return this.postData.EndDate;
    }
    else{
      return this.dateControlEnd.value;
    }
  }

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

  task: any;

  taskParticipants: EventPerson[];
  taskParticipantsCc: EventPerson[] = [];

  taskDocId:string;
  loadedAttachments:any;
  documents:SearchList[] = [];

  adding: "intervenient" | "CC" = "intervenient";

  postData: Event;
  eventBody: EventBody;
  eventAttendees: EventPerson[];

  formLocationSatus: boolean = false;
  showAttendees= false;
  loggeduser: LoginUserRespose;
  emptyTextDescription = "Sem intervenientes selecionados";

  constructor(
    private modalController: ModalController,
    private router:Router,
    private navParams: NavParams,
    private processes:ProcessesService,
    private attachmentsService: AttachmentsService,
    private calendarService: EventsService,
    authService: AuthService,
    private toastService: ToastService,
    private activatedRoute: ActivatedRoute,
    public ThemeService: ThemeService
    ) {
      this.taskParticipants = [];
      this.loggeduser = authService.ValidatedUser;
      this.task = this.navParams.get('task');

      console.log(this.task)
      this.postData = new Event();
      this.eventBody = { BodyType : "1", Text : ""};
      this.postData.Body = this.eventBody;

      this.postData.Subject = this.task.Folio;
      this.postData.CalendarName = "Oficial";

     this.dateControlStart = new FormControl(moment(new Date()));
     this.dateControlEnd = new FormControl(moment(new Date(new Date().getTime() + 15 * 60000)));

     this.postData.Category = 'Reunião'
    }

  ngOnInit() {
    this.adding = "intervenient";
    console.log(this.task);
    this.getAttachments();
    this.setDefaultTime()
    this.getRecurrenceTypes();

  }

  getRecurrenceTypes() {
    this.calendarService.getRecurrenceTypes().subscribe(res=>{
      this.recurringTypes = res;
    });
  }


  setDefaultTime() {
    this.postData.StartDate =  new Date()
    this.postData.EndDate = (new Date(new Date().getTime() + 15 * 60000))
  }

  getAttachments(){
    this.attachmentsService.getAttachmentsBySerial(this.task.SerialNumber).subscribe(res=>{
      this.loadedAttachments = res;
    });
  }

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

  goBack() {
    this.modalController.dismiss(null);
    window.history.back();
  }


  runValidation() {
    this.validateFrom  = true
  }

  get dateValid() {
    if (window.innerWidth <= 800) {
      return this.postData.StartDate < this.postData.EndDate? ['ok']: []
    } else {
      return ['ok']
    }
  }

  injectValidation() {

    this.Form = new FormGroup({
      Subject: new FormControl(this.postData.Subject, [
        Validators.required,
        // Validators.minLength(4)
      ]),
      Location: new FormControl(this.postData.Location, [
        Validators.required,
      ]),
      CalendarName: new FormControl(this.postData.CalendarName, [
        Validators.required
      ]),
      Date: new FormControl(this.dateValid, [
        Validators.required
      ]),
      participantes: new FormControl(this.taskParticipants, [
        Validators.required
      ]),
      Categories: new FormControl(this.postData.Category, [
        Validators.required
      ]),

    })
  }

  async saveTask(){

    if(this.loggeduser.Profile == 'MDGPR') {
      this.injectValidation()
      this.runValidation()
      if(this.Form.invalid) return false
    }

    let Attendees = this.taskParticipants.concat(this.taskParticipantsCc);

    this.eventBody={
      BodyType: '1',
      Text: this.postData.Body.Text,
    }
    this.postData = {
      EventId: '',
      Subject: this.postData.Subject,
      Body: this.eventBody,
      Location: this.postData.Location,
      CalendarId: '',
      CalendarName: this.postData.CalendarName,
      StartDate: this.dateStart,
      EndDate: this.dateEnd,
      EventType: 'Reunião',
      Attendees: Attendees,
      IsMeeting: false,
      IsRecurring: false,
      AppointmentState: 0,
      TimeZone: 'UTC',
      Organizer: null,
      Category: 'Reunião',
      HasAttachments: true,
      EventRecurrence: {
        Type: this.EventRecurrenceType,
        LastOccurrence: this.Occurrence
      },
    }

    if(this.task.FsId == '8') {
      alert('Chegou')
      const loader = this.toastService.loading()
      try {
        switch (this.loggeduser.Profile) {
          case 'MDGPR':
            await this.calendarService.postExpedientEvent(this.task.DocId, this.postData, "md",this.task.SerialNumber, this.task.FsId).toPromise();
            break;

          case 'PR':
            await this.calendarService.postExpedientEvent(this.task.DocId, this.postData, "pr",this.task.SerialNumber, this.task.FsId).toPromise()
            break;
        }

        this.modalController.dismiss();
        // this.distartExpedientModal();
        this.toastService._successMessage('Reunião criada');

      } catch (error) {
        this.toastService._badRequest('Reunião não criada')
      }
      finally {
        loader.remove()
      }


    }
    else if(this.task.FsId == '361') {

      const loader = this.toastService.loading()
      try {
        switch (this.loggeduser.Profile) {
          case 'MDGPR':
            await this.calendarService.createTaskEvent(this.task.FolderID | this.task.FolderId, this.postData, "md",this.task.SerialNumber, this.task.FsId).toPromise();
            break;

          case 'PR':
            await this.calendarService.createTaskEvent(this.task.FolderID | this.task.FolderId, this.postData, "pr",this.task.SerialNumber, this.task.FsId).toPromise();
            break;
        }
        this.close();
        this.toastService._successMessage('Reunião criada');

      } catch (error) {
        this.toastService._badRequest()
      } finally {
        loader.remove()
      }
    }
    else{
      this.toastService._successMessage('Não é possível marcar a reunião de momento');
    }

  }

  async addParticipants() {

    this.adding = "intervenient";

    if(window.innerWidth <= 801){
      const modal = await this.modalController.create({
        component: AttendeesPageModal,
          componentProps: {
          adding: this.adding,
          taskParticipants: this.taskParticipants,
          taskParticipantsCc: this.taskParticipantsCc
        },
        cssClass: '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'];

          this.setIntervenient(newAttendees);
          this.setIntervenientCC(newAttendeesCC);
        }
      });

    } else {
      this.showAttendees = true;
    }
  }

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

  async addParticipantsCc() {

    this.adding = "CC";

    if(window.innerWidth <= 800) {
      const modal = await this.modalController.create({
        component: AttendeesPageModal,
          componentProps: {
          adding: this.adding,
          taskParticipants: this.taskParticipants,
          taskParticipantsCc: this.taskParticipantsCc
        },
        cssClass: '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'];

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

  async distartExpedientModal() {
    const modal = await this.modalController.create({
      component: DiscartExpedientModalPage,
       componentProps: {
         serialNumber: this.task.SerialNumber,
      },
      cssClass: 'discart-expedient-modal',
      backdropDismiss: false
    });

    await modal.present();
    modal.onDidDismiss();
  }

  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((res)=> {
        if(res){
          const data = res.data;
          this.documents.push(data.selected);
        }
    });
  }

  removeAttachment(index: number){
    this.documents = this.documents.filter( (e, i) =>  index != i);
  }

  validateFormInputs() {
    let formLocation = this.postData.Location.trim();
    if(!this.postData.Location && formLocation.length <= 0){
      this.formLocationSatus = true;
    }
  }

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

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

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

}
