import { Component, OnInit } from '@angular/core';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
import { FormArray, FormBuilder, FormGroup, UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { ResizeEvent } from 'angular-resizable-element';
import { SignatureForm } from 'src/app/modules/signataireForm';
import { Demande } from 'src/app/modules/demande';
import { ApiService } from 'src/app/services/api.service';
import { TypeDocument } from 'src/app/modules/typeDocument';
import { UserPosition } from 'src/app/modules/userPosition';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-demande-signature',
  templateUrl: './demande-signature.component.html',
  styleUrls: ['./demande-signature.component.scss']
})
export class DemandeSignatureComponent implements OnInit {

  demande : Demande = new Demande();
  validateForm!: FormGroup;
  list_signataire: number[] = [1];
  signataire! : string ;
  hidesignataire : boolean = false;
  files_list : any [] = [];
  file! : File;
  step = 0;
  minDate!: string;
  existed = false;
  tdocuments: TypeDocument[] = [];

  signataireForm : SignatureForm = new SignatureForm();

  signataireLIst : UserPosition[]  = [];
  isVisible = false;

  constructor(private fb: FormBuilder, private apiService: ApiService, private router : Router, private message: NzMessageService){
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    this.minDate = tomorrow.toISOString().split('T')[0];
  }

  // validation du formulaire
  submitForm(): void {
    console.log(this.validateForm);
    if(this.validateForm.valid){

       // vérifie si le formulaire des signatures ne contient pas de doublons
      if(this.existed == false){
        var stateP = false;
        var stateE = false;
  
         // check le type de demande en fonction des signataires
        this.validateForm.value.users.map((element:any, i:number ) => {
            if(i > 0){
              let previousUser = this.validateForm.value.users[i-1];
              if(previousUser.envoie == "En séquence"){
                if(element.envoie == "En séquence"){
                  element.place = previousUser.place + 1;
                }else{
                  element.place = previousUser.place + 1;
                };
              }else{
                  element.place = previousUser.place ;
              }
              if(element.envoie == "En séquence")
                stateP = true;
              else if(element.envoie == "En parallèle")
                stateE = true;
            }
        });
  
        if(this.validateForm.value.users.length > 1){
          if(!stateE && stateP){
            this.demande.edemande = "En séquence";
          }else if(stateE && !stateP){
            this.demande.edemande = "En parallèle";
          }else if(stateE && stateP){
            this.demande.edemande = "En simultanée";
          }
          
        }else{
          console.log("4");
          let previousUser = this.validateForm.value.users[0];
          console.log(previousUser)
          this.demande.edemande = previousUser.envoie;
        }
        this.signataireForm.setObjet(this.validateForm.value.document, this.validateForm.value.users, this.files_list[0], this.validateForm.value.objet,
          this.validateForm.value.message)
  
          this.tdocuments.forEach((data:TypeDocument) => {
              if(data.name == this.validateForm.value.document){
                this.demande.typeDocument = data
              }
          })
          this.demande.expirationDate = this.validateForm.value.dateExpiration
          this.demande.confidentiality = this.validateForm.value.confidentiality
          this.demande.priority = this.validateForm.value.priority
          this.demande.objetMail = this.validateForm.value.objet
          this.demande.message = this.validateForm.value.message
          this.demande.destinataires = this.validateForm.value.users;
          this.demande.user = JSON.parse(localStorage.getItem("user")!);
          this.signataireForm.demande = this.demande;
       //   console.log(this.demande);
  
        this.step = 1;
      }else{
        this.createMessage("warning", "Vous avez dupliqué des informations  d'un destinataire. Veuillez le changer.")
      }

   
    }else{
      this.createMessage("error", "Votre formulaire de demande est incomplet. Veuillez remplir tous les champs.")
    }
    // Vous pouvez envoyer les données à votre backend ici
  }
  
  get users(): FormArray {
    return this.validateForm.get('users') as FormArray;
  }

  get files(): FormArray {
    return this.validateForm.get('files') as FormArray;
  }

  deleteUser(index : number){
    this.users.controls.splice(index, 1);
    const usersArray = this.validateForm.get('users') as FormArray;
    const user = usersArray.at(index);
    usersArray.removeAt(index);
  }

  deleteFile(){
    this.files_list = [];
  }

  
  createMessage(type: string, messqge: string): void {
    this.message.create(type, messqge);
  }

  // méthode excuté chez edit-document
  maMethodeDansLeParent() {
    this.step = 0;
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      dateExpiration: ["", [Validators.required]],
      confidentiality: ["Interne", [Validators.required]],
      priority: ["Urgent", [Validators.required]],
      document: ["", [Validators.required]],
      users: this.fb.array([this.createItem()]),
      file: [null, [Validators.required]],
      objet: ['', Validators.required],
      message: ['', Validators.required],
    });
    console.log(this.validateForm);
    this.getTDocuments();
  }

  createItem(): FormGroup {
    return this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      envoie: ["En séquence", [Validators.required]],
      role : ["Observateur", [Validators.required]],
      statut : [0, [Validators.required]],
      place : [0, [Validators.required]],
      // Ajoutez d'autres champs ici si nécessaire
    });
  }

  createItemFile(): FormGroup {
    return this.fb.group({
      file: ["",Validators.required],
    });
  }

  getTDocuments(){
      this.apiService.getDocuments().subscribe((data: any) => {
          console.log(data);
          this.tdocuments = data.response_data;
          this.validateForm = this.fb.group({
            dateExpiration: ["", [Validators.required]],
            confidentiality: ["Interne", [Validators.required]],
            priority: ["Urgent", [Validators.required]],
            document: [ this.tdocuments[0].name, [Validators.required]],
            users: this.fb.array([this.createItem()]),
            file: [null, [Validators.required]],
            objet: ['', Validators.required],
            message: ['', Validators.required],
          });

      })
  }

  removeItem(index: number): void {
    const usersArray = this.validateForm.get('users') as FormArray;
    const user = usersArray.at(index);
    const isEmpty = Object.values(user.value).every(val => val === '');
    console.log(isEmpty)
    if (isEmpty) {
      console.log("aaaaa")
      usersArray.removeAt(index);
    }
  }

  // ajouter le nouveau signataire
  addItem(){
    console.log(this.users)
    this.existed = false;
    if(this.users.status == "VALID"){
      let data = this.users.controls;
      this.users.controls.forEach((element:any) => {
        var tab = data.filter((dt:any) => dt.value.email == element.value.email)
          if(tab.length > 1){
            this.existed = true;
          }
      })
      console.log(data);
      if(this.existed == false){
        this.users.push(this.createItem());
      }else{
        this.createMessage("warning", "Ce destinataire existe déjà. Veuillez le changer.")
      }

    }else{
      this.createMessage("error", "Veuillez remplir tous les champs du destinataire.")
    }
    //this.users.push(this.createItem());
  }

  addFiles(){
    this.files.push(this.createItemFile());
  }

  fileObserver($event : any){
    console.log($event);
    this.files_list.push($event.target.files[0]);
    console.log(this.files_list)
  } 

  setSignature(event : any){
    console.log(this.validateForm)
    if(this.validateForm.value.signataire == "seul"){
      this.hidesignataire = true;
    }else{
      this.hidesignataire = false
    }
  }

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.users.controls, event.previousIndex, event.currentIndex);
    moveItemInArray(this.users.value, event.previousIndex, event.currentIndex);
  }
}
