import { Component, Inject, OnInit } from '@angular/core';
import { SubcontratistItem, SubcontratistsResponse } from '../../../../interfaces/personal-managment/subcontratists.interface';
import { FormControl, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { EncService } from '../../../../services/enc.service';
import { SubcontratistService } from '../../../../services/personal-management/subcontratist.service';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-transfer-order-dialog',
    templateUrl: './transfer-order-dialog.component.html',
    styleUrl: './transfer-order-dialog.component.css',
    standalone: false
})
export class TransferOrderDialogComponent implements OnInit {
  idOrder: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  responsibleUsers: any[];
  subcontratists: SubcontratistItem[];
  formControl: FormControl;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _encService: EncService,
    private _subcontratistService: SubcontratistService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<TransferOrderDialogComponent>,
  ) {
    this.idOrder = '';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.responsibleUsers = [];
    this.subcontratists = [];
    this.formControl = new FormControl('', Validators.required);
  }

  ngOnInit(): void {
    this.idOrder = this._data.idOrder;
    this.getResponsibleUsers();
  }

  async getResponsibleUsers(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let responsibleUsers = await lastValueFrom(this._correctiveMaintenanceService.getResponsibleUsers(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let idUserDec = await this._encService.decrypt(idUser);
        let responsibleUsersArr: any[] = [];
        for(const user of responsibleUsers.response){
          let idDec = await this._encService.decrypt(user.ID);
          user.NOMBRE = `${user.NOMBRE} (${idDec})`;
          
          if(idDec != idUserDec){
            responsibleUsersArr.push(user);
          }
        }

        this.responsibleUsers = responsibleUsersArr;
        this.getSubcontratists();
      }
    }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 getSubcontratists(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let subcontratists: SubcontratistsResponse = await lastValueFrom(this._subcontratistService.getConsultOfSubcontratists(idUser, 1));

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

      if(!this.hasError){
        let subcontratistsArr: SubcontratistItem[] = [];
        for(const subcontratist of subcontratists.response){
          if(subcontratist.STATUS == 'Activo'){
            let idDec = await this._encService.decrypt(subcontratist.ID_SUBCONTRATIST);
            subcontratist.NAME = `${subcontratist.NAME} (${idDec})`;

            subcontratistsArr.push(subcontratist);
          }
        }

        this.subcontratists = subcontratistsArr;
      }

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

  confirmTransfer(){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '380px',
      maxWidth: '380px',
      disableClose: true,
      data: {
        title: 'Confirmación',
        icon: 'warning',
        description: '¿Está seguro de querer transferir esta orden?',
        description2: 'Esta acción enviará una notificación al nuevo responsable de atender la orden.'
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        this._dialogRef.close(`transfer|${this.formControl.value}`);
      }
    });
  }
}
