import { Component, Inject, OnInit } from '@angular/core';
import { SpecialtiesListItem, SpecialtiesListResponse } from '../../../../interfaces/specialties.interface';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { DialogModule, Workteam } from '../../../../interfaces/personal-managment/workteam.interface';
import { ResourcesService, ResponseData } from '../../../../services/resources.service';
import { WorkTeamService } from '../../../../services/personal-management/work-team.service';
import { EncService } from '../../../../services/enc.service';
import { InterventionService } from '../../../../services/personal-management/intervention.service';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-work-team-form',
    templateUrl: './work-team-form.component.html',
    styleUrl: './work-team-form.component.css',
    standalone: false
})
export class WorkTeamFormComponent implements OnInit {
  action: string;
  title: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  specialties: SpecialtiesListItem[];
  workTeam: any | null;

  public formGroup: FormGroup;
  public idWorkteam: string;
  public enable: string;
  public members: any[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _dialogData: DialogModule,
    private _resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _workteamService: WorkTeamService,
    private _dialogRef: MatDialogRef<WorkTeamFormComponent>,
    private _encService: EncService,
    private _interventionService: InterventionService,
  ) {
    this.action = "";
    this.title = "";
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.specialties = [];
    this.workTeam = null;

    this.idWorkteam = "";
    this.enable = "";
    this.members = [];
    this.formGroup = this.createFormGroup();
  }

  private createFormGroup() {
    return new FormGroup({
      name: new FormControl({value: '', disabled: true}, [Validators.required, Validators.maxLength(75)]),
      speciality: new FormControl({value: [], disabled: true}, Validators.required),
    })
  }

  ngOnInit() {
    this.action = this._dialogData.action;
    if(this.action == 'REG'){
      this.title = "Registrar equipo de trabajo";
      this.getSpecialties();
    }else{
      this.title = this.action == 'UPD' ? "Modificación equipo de trabajo" : "Detalles equipo de trabajo";
      this.init();
    }
    
    /*this.isLoading = true;
    if (this.dialogData.action != "REG") {
      this.idWorkteam = this.dialogData.dataElement.WORKTEAM_ID;
      await this._getData();
      await this._getMembers();
    }
    this.enable = this.dialogData.action == "DET" ? "0" : "1";
    this.isLoading = false;*/
  }

  async getSpecialties(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let specialties: SpecialtiesListResponse = await lastValueFrom(this._interventionService.getSpecialties(idUser, 1));

      this.hasError = specialties.error;
      this.errorStr = specialties.msg;

      if(!this.hasError){
        let selectedSpecialties: string[] = [];
        if(this.workTeam != null){
          for(const specialtyCode of this.workTeam.SPECIALTY_ARR){
            let codeDec = await this._encService.decrypt(specialtyCode);
            let codeArr = codeDec.split(' - ');
            selectedSpecialties.push(codeArr[0]);
          }
        }

        let specialtiesArr: SpecialtiesListItem[] = [];
        for(const specialty of specialties.response){
          let codeDec = await this._encService.decrypt(specialty.CODIGO_ESPECIALIDAD);
          specialty.NOMBRE_ESPECIALIDAD = `${codeDec} - ${specialty.NOMBRE_ESPECIALIDAD}`;

          if(specialty.ESTADO == 'Activo'){
            specialtiesArr.push(specialty);
            if(selectedSpecialties.includes(codeDec)){
              let specialtiesVal = this.formGroup.controls['speciality'].value;
              specialtiesVal.push(specialty.CODIGO_ESPECIALIDAD);

              this.formGroup.controls['speciality'].setValue(specialtiesVal);
            }
          }
        }

        this.specialties = specialtiesArr;
        if(this.action == 'UPD' || this.action == 'REG'){
          this.formGroup.controls['name'].enable();
          this.formGroup.controls['speciality'].enable();
        }
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async init(){
    try{
      this.workTeam = this._dialogData.dataElement;
      this.idWorkteam = this.workTeam.WORKTEAM_ID;
      this.formGroup.controls['name'].setValue(this.workTeam.NAME);

      if(this.action == 'DET'){
        this._getMembers();
      }else{
        this.getSpecialties();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  private async _getMembers(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let idWorkteamEnc = await this._encService.encrypt(this.idWorkteam);
      let members = await lastValueFrom(this._workteamService.getMembersOfWorkteamById(
        idWorkteamEnc,
        idUser,
        1
      ));

      this.hasError = members.error;
      this.errorStr = members.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{
        let membersArr: any[] = [];
        for(const member of members.response){
          let idEmp = await this._encService.decrypt(member.IDEMPLEADO);
          let idUsr = await this._encService.decrypt(member.IDUSUARIO);

          member.NAME = `${member.NAME} (${idEmp}) (${idUsr})`,
          membersArr.push(member);
        }

        this.members = membersArr;
        this.getSpecialties();
      }
    }catch(error: any){
      if(error.error){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  public alert(typeForm: string) {
    if (typeForm === 'REG') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Registrar Equipo de Trabajo',
          description: '¿Está seguro que desea registrar al equipo?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.storeWorkteam();
        }
      });
    } else {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Actualizar Equipo de Trabajo',
          description: '¿Está seguro que desea actualizar al equipo?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.updateWorkteam();
        }
      });
    }
  }

  private async storeWorkteam(){
    const WORKTEAM: Workteam = await this.workteamObject(undefined);
    await lastValueFrom(this._workteamService.storeWorkteam( WORKTEAM )).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this._resourcesService.openSnackBar("¡Creación Exitosa!");
          this._dialogRef.close(true);
        } else {
          this._resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this._resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.storeWorkteam();
        }
      }
    );
  }

  private async updateWorkteam(){
    let idWorkteamEnc = await this._encService.encrypt(`${this.idWorkteam}`);
    const WORKTEAM: Workteam = await this.workteamObject(idWorkteamEnc);
    await lastValueFrom(this._workteamService.updateWorkteam( WORKTEAM )).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this._resourcesService.openSnackBar("Actualización Exitosa!");
          this._dialogRef.close(true);
        } else {
          this._resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this._resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.updateWorkteam();
        }
      }
    );
  }

  private async workteamObject(idWorkteamEnc: string | undefined): Promise<Workteam> {
    let formValue = this.formGroup.getRawValue();
    
    return {
      WORKTEAM_ID: idWorkteamEnc,
      NAME: formValue.name,
      SPECIALITY: JSON.stringify(formValue.speciality),
      id_user: localStorage.getItem('idusuario')!,
      linea: 1,
    }
  }
}
