import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AnimationController, ModalController, NavParams } from '@ionic/angular';
import { Despacho } from 'src/app/models/despacho.model';
import { EventPerson } from 'src/app/models/eventperson.model';
import { Participant } from 'src/app/models/participant.model';
import { Folder } from 'src/app/models/folder.model';
import { AuthService } from 'src/app/services/auth.service';
import { ProcessesService } from 'src/app/services/processes.service';
import { DiscartExpedientModalPage } from '../../discart-expedient-modal/discart-expedient-modal.page';
import { AttachmentsService } from 'src/app/services/attachments.service';
import { ExpedienteDetailPage } from '../expediente-detail/expediente-detail.page';
import { AlertService } from 'src/app/services/alert.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 { ToastService } from 'src/app/services/toast.service';
import { AttendeesPageModal } from 'src/app/pages/events/attendees/attendees.page';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { NGX_MAT_DATE_FORMATS } from '@angular-material-components/datetime-picker';
import { NgxMatDateFormats } from '@angular-material-components/datetime-picker';
import { task } from 'src/app/models/ExpedientTaskModalPage';
import { DespachoService } from 'src/app/Rules/despacho.service';
import { SearchDocumentPipe } from 'src/app/pipes/search-document.pipe';
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-expedient-task-modal',
  templateUrl: './expedient-task-modal.page.html',
  styleUrls: ['./expedient-task-modal.page.scss'],
  providers: [
    { provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
  ]
})
export class ExpedientTaskModalPage implements OnInit {

  modalTitle: string[] = [
    'Efectuar Despacho',
    'Solicitar Parecer',
    'Solicitar Deferimento'
  ];
  taskType:string;
  task: task;
  aplicationId = null

  taskParticipants: any = [];
  taskParticipantsCc: any = [];

  taskDate: Date;
  taskDescription: string;

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

  subjectTypes:any[] = [];
  selectedTypes: string[]=[];
  SearchFolder: any = []

  postData: Despacho;
  dispatchFolder: Folder;
  participants: Participant[];

  contacts= [];
  // trigger hide and show for attendee component
  showAttendees= false;

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

  emptyTextDescription = "Sem intervenientes selecionados";
  showEmptyContainer = true;

  taskResult: any = {}

  loggeduser: LoginUserRespose;
  toppings = new FormControl();

  Form: FormGroup;
  validateFrom = false;
  validateField = false;

  get toppingsValues() {
    return this.toppings.value;
  }

  private searchDocumentPipe = SearchDocumentPipe

  constructor(
    private modalController: ModalController,
    private router:Router,
    private processes:ProcessesService,
    private attachmentsService: AttachmentsService,
    private navParams: NavParams,
    private alertController: AlertService,
    private userAuth: AuthService,
    private toastService: ToastService,
    private despachoService: DespachoService,
    public ThemeService: ThemeService
    ) {

      this.loggeduser = userAuth.ValidatedUser;
      this.task = this.navParams.get('task');

      console.log('create dispatch with this data', this.task);

      this.SearchFolder = this.navParams.get('SearchFolder');
      this.aplicationId = this.navParams.get('aplicationId')

      this.taskType = this.navParams.get('taskAction');

      this.selectedTypes = ['99999850'];

      this.postData = new Despacho();
      this.participants = this.participants = new Array();
      this.dispatchFolder = {
        Nad: 30,
        Subject: '',
        Message: '',
        SourceSecFsId: this.task.workflowInstanceDataFields.SourceSecFsID, //361
        SourceType: this.task.workflowInstanceDataFields.SourceType, //FOLDER
        SourceId: this.task.workflowInstanceDataFields.SourceID, //FolderId
        DeadlineType: '',
        SubjectTypes: this.selectedTypes,
        NumberPDPP: this.task.workflowInstanceDataFields.DispatchNumber,
      };

      this.postData.DispatchFolder = this.dispatchFolder;
      this.postData.UsersSelected = this.participants;
      /* By Default TypeDeadline should be 'Normal' */
      this.postData.Priority = '99999861';
      /* Initialize 'Subject' with the title of the expedient */
      this.postData.DispatchFolder.Subject = this.task.workflowInstanceDataFields.Subject;
      this.profile = this.navParams.get('profile');

      console.log(this.postData);
  }

  async setAdding(type:  "intervenient" | "CC") {
    this.adding = type;
  }

  ngOnInit() {


    this.taskDate = new Date(this.task.taskStartDate);
    if(!this.task.hasOwnProperty('isEvent')) {
      this.getAttachments();
    }
    this.getSubjectType();
  }

  onSelectedTypesChanged(ev:any) {
    console.log(ev);
    if(ev.length > 1){
      console.log(ev.filter(data => data != '99999850'));
      this.selectedTypes = ev.filter(data => data != '99999850');
    }
    if(ev.length == 0){
      this.selectedTypes = ["99999850"];
    }
  }

  close() {
    this.router.navigate(['/home/gabinete-digital/expediente']);
    this.modalController.dismiss(null);
  }

  getSubjectType() {
    this.processes.GetSubjectType().subscribe(res=>{
      console.log(res);
      this.subjectTypes = res;
    });
  }

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

  runValidation() {
    this.validateFrom  = true;
  }

  injectValidation() {

    this.Form = new FormGroup({
      Subject: new FormControl(this.postData.DispatchFolder.Subject, [
        Validators.required,
        // Validators.minLength(4)
      ]),
      Location: new FormControl(this.postData.DispatchFolder.Message, [
        Validators.required,
      ]),
      selectedTypes: new FormControl(this.selectedTypes, [
        Validators.required,
      ]),
      Priority: new FormControl(this.postData.Priority, [
        Validators.required,
      ]),
      // CalendarName: new FormControl(this.postEvent.CalendarName, [
      //   Validators.required
      // ]),
      // Categories: new FormControl(this.postEvent.Categories, [
      //   Validators.required
      // ]),
      // IsRecurring: new FormControl(this.postEvent.IsRecurring, [
      //   Validators.required
      // ]),
      participantes: new FormControl(this.taskParticipants, [
        Validators.required
      ]),

    })
  }
  //
  async saveTask() {

    if(this.loggeduser.Profile == 'MDGPR') {
      this.injectValidation()
      this.runValidation()

      if(this.Form.invalid) return false
    }

    if(this.postData.Priority=='99999861') {
      this.dispatchFolder.DeadlineType = 'Normal';
    }
    else if(this.postData.Priority=='99999862') {
      this.dispatchFolder.DeadlineType = 'Urgente';
    }
    else if(this.postData.Priority=='99999863') {
      this.dispatchFolder.DeadlineType = 'Muito Urgente';
    }
    else if(this.postData.Priority=='99999864') {
      this.dispatchFolder.DeadlineType = 'Urgentíssimo';
    }

    let attendees = this.taskParticipants.concat(this.taskParticipantsCc);
    attendees = attendees.map(function(val) {
      return {
        UserEmail: val.EmailAddress,
        UserType:  val.IsRequired?"I": "CC"
      };
    })

    let docs = {
      ProcessInstanceID: "",
      Attachments: []
    }

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


    if(this.SearchFolder) {
      if(this.SearchFolder.Documents) { // 361
        this.SearchFolder.Documents.forEach( (ele) => {
          docs.Attachments.push({
            ApplicationId: 361,
            Source: 1,
            SourceId: ele.docID || ele.docId || ele.DocId,
            SourceName: ele.Assunto
          })
        });


      } else { // 8
        docs.Attachments.push({
          ApplicationId: 8,
          Source: 1,
          SourceId: this.SearchFolder.docID || this.SearchFolder.docId || this.SearchFolder.DocId,
          SourceName: this.SearchFolder.Assunto
        })

      }
    }




    this.dispatchFolder.SubjectTypes = this.selectedTypes;
    const loader = this.toastService.loading()

    switch (this.loggeduser.Profile) {
      case 'MDGPR':
        if(this.taskParticipants.length > 0) {
          switch (this.taskType) {
            case '0': // Despacho
              this.postData = {
                DistributionType: "Paralelo",
                CountryCode: 'AO',
                Priority: this.postData.Priority,
                UserEmail: this.loggeduser.Email,
                UsersSelected: attendees,
                DispatchFolder: this.dispatchFolder,
                AttachmentList: docs,
              }

              let action_despacho = {
                "serialNumber": this.task.serialNumber,
                "action": "Tratado",
                "ActionTypeId": 94,
                "dataFields": {
                  "Note": "",
                }
              }

              console.log(this.postData);

              try {

                this.taskResult = await this.processes.postDespatcho(this.postData).toPromise();
                await this.toastService._successMessage('Processo efetuado');
                this.modalController.dismiss(action_despacho);

              } catch (error) {
                await this.toastService._badRequest('Processo não efetuado')
              } finally {
                loader.remove()
              }

              console.log('this.taskResult', this.taskResult);
              break;

            case '1': // Parecer
              this.postData = {
                DistributionType: "Paralelo",
                CountryCode: 'AO',
                Priority: this.postData.Priority,
                UserEmail: this.loggeduser.Email,
                UsersSelected: attendees,
                DispatchFolder: this.dispatchFolder,
                AttachmentList: docs
              }

              let action_parecer = {
                "serialNumber": this.task.serialNumber,
                "action": "Tratado",
                "ActionTypeId": 92,
                "dataFields": {
                  "Note": "",
                }
              }

              try {
                this.taskResult = await this.processes.postParecer(this.postData).toPromise();
                await this.toastService._successMessage('Pedido enviado');
                this.modalController.dismiss(action_parecer);

              } catch (error) {
                await this.toastService._badRequest('Processo não efetuado')
              } finally {
                loader.remove()
              }
              break;
            case '2': // Deferimento
              this.postData = {
                DistributionType: "Paralelo",
                CountryCode: 'AO',
                Priority: this.postData.Priority,
                UserEmail: this.loggeduser.Email,
                UsersSelected: attendees,
                DispatchFolder: this.dispatchFolder,
                AttachmentList: docs
              }
              //console.log(this.postData);
              let action_deferimento = {
                  "serialNumber": this.task.serialNumber,
                  "action": "Tratado",
                  "ActionTypeId": 93,
                  "dataFields": {
                    "Note": "",
                }
              }

            try {

              this.taskResult = await this.processes.postDeferimento(this.postData).toPromise();
              this.toastService._successMessage('Processo efetuado');
              this.modalController.dismiss(action_deferimento);
            } catch (error) {
              await this.toastService._badRequest('Processo não efetuado')
            } finally {
              loader.remove()
            }

            console.log('this.taskResult', this.taskResult);
          break;
        }
      }
      else {
        this.alertController.presentAlert("Lista de i-ntervenientes vazia. Por favor, adicione 1 ou mais intervenientes.");
      }
        break;
      case 'PR':
        switch (this.taskType) {
          case '0': // despacho
            this.postData = {
              DistributionType: "Paralelo",
              CountryCode: 'AO',
              Priority: this.postData.Priority,
              UserEmail: this.loggeduser.Email,
              UsersSelected: attendees,
              DispatchFolder: this.dispatchFolder,
              AttachmentList: docs,
            }
            console.log(this.postData);

            let action_despacho_pr = {
              "serialNumber": this.task.serialNumber,
              "action": "Tratado",
              "ActionTypeId": 99999881 ,
              "dataFields": {
                "Note": "",
              }
            }

            if(this.postData.DispatchFolder.Message){
              try {
                this.taskResult = await this.despachoService.createDespacho(this.postData).toPromise();
                await this.toastService._successMessage('Processo efetuado');
                this.modalController.dismiss(action_despacho_pr);
              } catch (error) {

                await this.toastService._badRequest('Processo não efetuado')
              } finally {
                //loader.remove()
              }
            }
            else{
              this.validateField = true;
              this.toastService._badRequest('Por favor adicione uma descrição');
            }
            loader.remove();
            break;

          case '1': // parecer
            this.postData = {
              DistributionType: "Paralelo",
              CountryCode: 'AO',
              Priority: this.postData.Priority,
              UserEmail: this.loggeduser.Email,
              UsersSelected: attendees,
              DispatchFolder: this.dispatchFolder,
              AttachmentList: docs
            }

            let action_parecer_pr = {
              "serialNumber": this.task.serialNumber,
              "action": "Tratado",
              "ActionTypeId": 99999881,
              "dataFields": {
                "Note": "",
              }
            }

            try {
              this.taskResult = await this.processes.postParecerPr(this.postData).toPromise();
              await this.toastService._successMessage('Pedido enviado');
              this.modalController.dismiss(action_parecer_pr);
            } catch (error) {

              await this.toastService._badRequest('Processo não efetuado')
            } finally {
                loader.remove()
            }

            break;
        }
        break;
    }
  }

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

  }

  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'];

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

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

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

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

  async addParticipantsCc() {
    this.adding = "CC";
    this.openAttendees();
  }

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

  async setContact(data:EventPerson[]) {

    if(this.adding == "intervenient"){
      this.taskParticipants = data;
    } else if (this.adding == "CC") {

      this.taskParticipantsCc = data;
    }

  }

  async closeComponent() {
    this.showAttendees = false;
  }

  async viewExpedientDetail() {
    console.log(this.profile);

    let classs;
    if( window.innerWidth <= 800){
      classs = 'modal  modal-desktop'
    } else  {
      classs = 'modal modal-desktop showAsideOptions'
    }

    const modal = await this.modalController.create({
      component: ExpedienteDetailPage,
      componentProps:{
        serialNumber: this.task.serialNumber,
        profile: this.profile,
      },
      cssClass: classs,
      backdropDismiss: false
    });
    await modal.present();
    modal.onDidDismiss().then((res)=>{
     /*  console.log('!refresh list'); */
    });
  }


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

  }

}
