import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { PreventiveOrderStaff, PreventiveOrderStaffResponse } from '../../../../interfaces/preventive-order-staff.interface';
import { MatTableDataSource } from '@angular/material/table';
import { TempFileInfo } from '../../../../interfaces/temp-file-info.interface';
import { Hour, InterventionsListItem, InterventionsListResponse } from '../../../../interfaces/personal-managment/intervention.interface';
import { ActivatedRoute } from '@angular/router';
import { ResourcesService } from '../../../../services/resources.service';
import { InterventionService } from '../../../../services/personal-management/intervention.service';
import { EncService } from '../../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { PreventiveMaintenanceService } from '../../../../services/preventive-maintenance.service';
import { GdelService } from '../../../../services/gdel.service';
import { PreventiveWorkOrdersActiveResponse } from '../../../../interfaces/preventive-work-orders-active.interface';
import { lastValueFrom } from 'rxjs';
import { availableFiles } from '../../../../../environments/environment.prod';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { EmployeeService } from '../../../../services/personal-management/employee.service';
import { SubcontratistService } from '../../../../services/personal-management/subcontratist.service';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { CorrectiveWorkOrderDetailsResponse, CorrectiveWorkOrderStaffListResponse, NoMeasuresOrdersListResponse } from '../../../../interfaces/corrective-maintenance.interface';
import { PreventiveOrderExecutionResponse } from '../../../../interfaces/preventive-order-execution.interface';
import { EmployeesListResponse } from '../../../../interfaces/personal-managment/employee.interface';

@Component({
    selector: 'app-contract-form',
    templateUrl: './contract-form.component.html',
    styleUrl: './contract-form.component.css',
    standalone: false
})
export class ContractFormComponent implements OnInit {
  public action: string;
  public isLoading: boolean;
  public hasError: boolean;
  public errorStr: string;
  public searchingOrders: boolean;
  public interventions: any[];
  public loadingStaff: boolean;
  public interns!: Array<any>;
  public subcontratists!: Array<any>;

  public isUploading: boolean;
  public disableDelete: boolean;
  public screenSize: number;

  public idContract: string;
  public enable: string;
  public btnSmall: boolean;
  public formGroup: FormGroup;
  public formData: FormData = new FormData();
  public isLoadingForm: boolean;
  public document!: Array<any>;

  public dataSource: MatTableDataSource<TempFileInfo>;
  public displayedColumns: string[] =  ['ID', 'NOMBRE', 'PESO', 'ACCIONES'];
  public hours: Hour[];

  public preventiveOrders: any[];
  public correctiveOrders: any[];
  public attached: TempFileInfo[];

  public minDate: Date | undefined;
  public maxDate: Date | undefined;

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _resourcesService: ResourcesService,
    private _interventionService: InterventionService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _prevMaintService: PreventiveMaintenanceService,
    private _gdelService: GdelService,
    private _employeeService: EmployeeService,
    private _subcontratistService: SubcontratistService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
  ) {
    this.enable = this._activatedRoute.snapshot.paramMap.get('enable')!;
    this.idContract = this._activatedRoute.snapshot.paramMap.get('id')!;

    this.action = "";
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.searchingOrders = false;
    this.interventions = [];
    this.loadingStaff = false;
    this.dataSource = new MatTableDataSource();

    this.isUploading = false;
    this.disableDelete = false;
    this.screenSize = window.innerWidth;

    this.btnSmall = false;
    this.formGroup = this.createFormGroup();
    this.isLoadingForm = false;
    this.document = [];
    this.hours = [];
    this.subcontratists = [];
    this.interns = [];

    this.preventiveOrders = [];
    this.correctiveOrders = [];
    this.attached = [];

    this.minDate = undefined;
    this.maxDate = undefined;
  }

  private createFormGroup() {
    return new FormGroup({
      name: new FormControl('', [Validators.required, Validators.maxLength(100)]),
      orderType: new FormControl('', Validators.required),
      includeMeasures: new FormControl({ value: true, disabled: true }, Validators.required),
      workOrder: new FormControl({ value: '', disabled: true }, Validators.required),
      contractType: new FormControl('', Validators.required),
      denominationIntern: new FormControl({value: '', disabled: true}, Validators.required),
      denominationSubcontratist: new FormControl({value: '', disabled: true}, Validators.required),
      startDate: new FormControl('', Validators.required),
      endDate: new FormControl('', Validators.required),
      startHour: new FormControl('', Validators.required),
      endHour: new FormControl('', Validators.required),
      cost: new FormControl('', Validators.required),
    })
  }

  ngOnInit(): void {
    this.setHours();
    this.init();
  }

  private setHours() {
    for (let i = 0; i <= 23; i++) {
      let timeLapse = i < 12 ? 'AM' : 'PM';
      let hour = i > 12 ? i - 12 : i;
      let hourStr = hour < 10 ? `0${hour}` : `${hour}`;

      let ent = `${hourStr}:00 ${timeLapse}`;
      let quart = `${hourStr}:15 ${timeLapse}`;
      let half = `${hourStr}:30 ${timeLapse}`;
      let quartTo = `${hourStr}:45 ${timeLapse}`;
      let hs = i < 10 ? `0${i}` : `${i}`;

      let entHour: Hour = {
        value: `${hs}:00:00`,
        label: ent
      }

      let quartHour: Hour = {
        value: `${hs}:15:00`,
        label: quart
      }

      let halfHour: Hour = {
        value: `${hs}:30:00`,
        label: half
      }

      let quartToHour: Hour = {
        value: `${hs}:45:00`,
        label: quartTo
      }

      this.hours.push(entHour);
      this.hours.push(quartHour);
      this.hours.push(halfHour);
      this.hours.push(quartToHour);
    }
  }

  async init(){
    try{
      let idDec = await this._encService.decrypt(this.idContract);
      this.idContract = idDec;

      if(idDec == "0"){
        this.action = "Registrar";
        this.getPreventiveOrdersActive();
      }else if(idDec != '0' && this.enable == '1'){
        this.action = "Editar";
      }else{
        this.action = "Detalle de";
      }
    }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 getPreventiveOrdersActive(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let preventiveOrdersActive: PreventiveWorkOrdersActiveResponse = await lastValueFrom(this._prevMaintService.getActiveWorkOrders(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        for(const order of preventiveOrdersActive.response){
          let idEnc = await this._encService.encrypt(`${order.IDORDEN}`);
          this.preventiveOrders.push({
            ID: idEnc,
            LABEL: `Orden #${order.IDORDEN}`
          });
        }
        
        this.getCorrectiveOrdersActive();
      }
    }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 getCorrectiveOrdersActive(){
    try{
      //Pendiente implementar
      let idUser = localStorage.getItem('idusuario');
      
      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;
    }
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize(): void {
    this.btnSmall = window.innerWidth <= 1405;
    this.screenSize = window.innerWidth;
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  async workOrderChange(value: string){
    try{
      /*let idUser = localStorage.getItem('idusuario')!;
      let idOrderArr = value == undefined ? ['', ''] : value.split('-');

      this.loadingStaff = true;
      this.interns = [];
      this.subcontratists = [];

      if(idOrderArr[1] == 'prev'){
        let orderStaff: PreventiveOrderStaffResponse = await lastValueFrom(this._prevMaintService.getOrderStaff(idOrderArr[0], idUser, 1));
        
        if(orderStaff.error){
          this._resourcesService.openSnackBar(orderStaff.msg);
        }else{
          for(const person of orderStaff.response){
            let idEnc = await this._encService.encrypt(`${person.IDEMPLEADO}`);

            person.NOMBREUSUARIO = `${person.NOMBREUSUARIO} (${person.IDEMPLEADO}) (${person.IDUSUARIO})`;
            person.IDEMPLEADO = idEnc;

            if(person.TIPOCONTRATO == 'Interno'){
              this.interns.push(person);
            }else{
              this.subcontratists.push(person);
            }
          }
        }
      }

      let contractType = this.formGroup.controls['contractType'].value;
      let validContractType = contractType != '' && contractType != undefined && contractType != null;
      let validWorkOrder = value != '' && value != undefined && value != null;

      if(validContractType && validWorkOrder){
        switch(contractType){
          case "Subcontratista": 
            this.formGroup.controls['denominationSubcontratist'].enable();
            this.formGroup.controls['denominationIntern'].disable();
            this.formGroup.controls['denominationIntern'].setValue(null);
          break;
          case "Interno":
            this.formGroup.controls['denominationSubcontratist'].disable();
            this.formGroup.controls['denominationSubcontratist'].setValue(null);
            this.formGroup.controls['denominationIntern'].enable();
          break;
          default: 
            this.formGroup.controls['denominationSubcontratist'].disable();
            this.formGroup.controls['denominationIntern'].disable();
          break;
        }
      }else{
        this.formGroup.controls['denominationSubcontratist'].disable();
        this.formGroup.controls['denominationSubcontratist'].setValue(null);
        this.formGroup.controls['denominationIntern'].disable();
        this.formGroup.controls['denominationIntern'].setValue(null);
      }

      this.loadingStaff = false;*/
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }

      this.formGroup.controls['denominationSubcontratist'].disable();
      this.formGroup.controls['denominationSubcontratist'].setValue(null);
      this.formGroup.controls['denominationIntern'].disable();
      this.formGroup.controls['denominationIntern'].setValue(null);
    }
  }

  public async changeContractType(value: string) {
    this.loadingStaff = true;

    let relatedOrder = this.formGroup.controls['workOrder'].value;
    if(relatedOrder == null || relatedOrder == undefined || relatedOrder == ''){
      this._resourcesService.openSnackBar('Aún no ha seleccionado ninguna orden de trabajo.');
      this.formGroup.controls['contractType'].setValue('');
      this.loadingStaff = false;
      return;
    }

    let orderType = this.formGroup.controls['orderType'].value;
    let includeMeasures = this.formGroup.controls['includeMeasures'].value;
    let idUser = localStorage.getItem('idusuario')!;

    if(orderType == 'MP'){
      let relatedOrderDec = await this._encService.decrypt(relatedOrder);
      let relatedOrderArr = relatedOrderDec.split('|');
      let relatedOrderIDEnc = await this._encService.encrypt(relatedOrderArr[0]);

      let order: PreventiveOrderExecutionResponse = await lastValueFrom(this._prevMaintService.getExecRegister(
        relatedOrderArr[1],
        relatedOrderIDEnc,
        idUser,
        1
      ));

      if(order.error){
        this._resourcesService.openSnackBar(order.msg);
        this.formGroup.controls['contractType'].setValue('');
      }else{
        let internStaff: any[] = [];
        let subcontratistStaff: any[] = [];

        for(const specialty of order.response.OPERARIOS!){
          for(const item of specialty.OPERARIOS){
            let idEmployeeDec = await this._encService.decrypt(item.ID_EMPLEADO);
            let idUserDec = await this._encService.decrypt(item.ID_USUARIO);

            let itemObj = {
              ID: item.ID_EMPLEADO,
              NOMBRE: `${item.NOMBRE_EMPLEADO} (${idUserDec}) (${idEmployeeDec})`,
            };

            if(item.TIPO_EMPLEADO == 'Interno'){
              internStaff.push(itemObj);
            }else{
              subcontratistStaff.push(itemObj);
            }
          }
        }

        this.interns = internStaff;
        this.subcontratists = subcontratistStaff;
      }
    }else if(orderType == 'MC' && includeMeasures){
      let order: CorrectiveWorkOrderStaffListResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrderStaff(
        relatedOrder,
        idUser,
        1
      ));

      if(order.error){
        this._resourcesService.openSnackBar(order.msg);
        this.formGroup.controls['contractType'].setValue('');
      }else{
        let internStaff: any[] = [];
        let subcontratistStaff: any[] = [];

        for(const item of order.response){
          let idEmployeeDec = await this._encService.decrypt(item.ID);
          let idUserDec = await this._encService.decrypt(item.ID_USER);

          let itemObj = {
            ID: item.ID,
            NOMBRE: `${item.NAME} (${idUserDec}) (${idEmployeeDec})`,
          };

          if(item.TYPE == 'Interno'){
            internStaff.push(itemObj);
          }else{
            subcontratistStaff.push(itemObj);
          }
        }

        this.interns = internStaff;
        this.subcontratists = subcontratistStaff;
      }
    }else if(orderType == 'MC' && !includeMeasures){
      let employees: EmployeesListResponse = await lastValueFrom(this._employeeService.getConsultOfEmployees(idUser, 1));
      if(employees.error){
        this._resourcesService.openSnackBar(employees.msg);
      }else{
        let internStaff: any[] = [];
        let subcontratistStaff: any[] = [];

        for(const item of employees.response){
          let idEmployeeDec = await this._encService.decrypt(item.ID_EMPLOYEE);

          let itemObj = {
            ID: item.ID_EMPLOYEE,
            NOMBRE: `${item.NAME} (${idEmployeeDec})`,
          };

          if(item.CONTRACT_TYPE == 'Interno'){
            internStaff.push(itemObj);
          }else{
            subcontratistStaff.push(itemObj);
          }
        }

        this.interns = internStaff;
        this.subcontratists = subcontratistStaff;
      }
    }
    
    this.loadingStaff = false;
    switch(value){
      case "Subcontratista": 
        this.formGroup.controls['denominationSubcontratist'].enable();
        this.formGroup.controls['denominationIntern'].disable();
        this.formGroup.controls['denominationIntern'].setValue(null);
      break;
      case "Interno":
        this.formGroup.controls['denominationSubcontratist'].disable();
        this.formGroup.controls['denominationSubcontratist'].setValue(null);
        this.formGroup.controls['denominationIntern'].enable();
      break;
      default: 
        this.formGroup.controls['denominationSubcontratist'].disable();
        this.formGroup.controls['denominationSubcontratist'].setValue(null);
        this.formGroup.controls['denominationIntern'].disable();
        this.formGroup.controls['denominationIntern'].setValue(null);
      break;
    }
  }

  public datesRange() {
    let minDate = this.formGroup.controls['startDate'].value;
    if(minDate != '' && minDate != null && minDate != undefined){
      this.minDate = new Date(minDate);
    }

    let maxDate = this.formGroup.controls['endDate'].value;
    if(maxDate != '' && maxDate != null && maxDate != undefined){
      this.maxDate = new Date(maxDate);
    }

    this.hoursRange();
  }

  public hoursRange() {
    let startHourControl = this.formGroup.controls['startHour']!;
    let validStartHour = startHourControl.value != '' && startHourControl.value != null && startHourControl.value != undefined;

    let endHourControl = this.formGroup.controls['endHour']!;
    let validEndHour = endHourControl.value != '' && endHourControl.value != null && endHourControl.value != undefined;

    let startDateControl = this.formGroup.controls['startDate']!;
    let validStartDate = startDateControl.value != '' && startDateControl.value != null && startDateControl.value != undefined;

    let endDateControl = this.formGroup.controls['endDate']!;
    let validEndDate = endDateControl.value != '' && endDateControl.value != null && endDateControl.value != undefined;

    if (validStartHour && validEndHour && validStartDate && validEndDate) {
      if (startDateControl.value.toString() == endDateControl.value.toString()){
        if(startHourControl.value > endHourControl.value){
          this._resourcesService.openSnackBar("La hora de fin es menor a la de inicio");
          endHourControl.setValue(null);
        }
      }
    }
  }

  checkFile(event: any) {
    let supportedFiles = ['pdf', 'doc', 'docx', 'jpg', 'png'];
    let extArr = event.target.files[0].name.split(".").reverse();
    let extStr = extArr[0];

    if(!supportedFiles.includes(extStr)){
      this._resourcesService.openSnackBar(`La extensión ${extStr} no está soportada para el registro de oficios.`);
      return;
    }
      
    let fileTypes = availableFiles;
    let sizes = Object.keys(fileTypes);
    let extensions = Object.values(fileTypes);
    let maxSizeMB = 0;

    let i = 0;
    extensions.forEach(ext => {
      let size = parseInt(sizes[i]);

      if(ext.includes(extStr)) maxSizeMB = size;
      i++;
    });

    if(maxSizeMB == 0){
      this._resourcesService.openSnackBar(`Los archivos ${extStr} no están soportados`);
    }else{
      let maxFileSize = 1048576 * maxSizeMB;
      let fileSize = event.target.files[0].size;

      if(fileSize > maxFileSize){
        this._resourcesService.openSnackBar(`El tamaño del archivo supera el límite de ${maxSizeMB} MB`);
      }else{
        let alreadyAttached = this.attached.filter(file => file.name == event.target.files[0].name && file.size == this.formatBytes(event.target.files[0].size));

        if(alreadyAttached.length > 0){
          this._resourcesService.openSnackBar("El archivo seleccionado ya fue adjuntado.");
        }else{
          this.isUploading = true;
          this.uploadTmp(event.target.files[0]);
        }
      }
    }
  }

  formatBytes(bytes: number, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  }

  async uploadTmp(fileData: any){
    try{
      let idUser = localStorage.getItem('idusuario');
      let formData = new FormData();

      formData.append('file', fileData);
      formData.append('id_user', idUser!);
      formData.append('linea', "1");

      let response = await lastValueFrom(this._gdelService.uploadTempFile(formData));

      if(response.error){
        this._resourcesService.openSnackBar(response.msg);
      }else{
        let uploadedFile: TempFileInfo = {
          id: response.response.idArchivo,
          name: fileData.name,
          size: this.formatBytes(fileData.size),
        };

        this.attached.push(uploadedFile);
        this.dataSource = new MatTableDataSource(this.attached);
      }

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

  async deleteFile(id: string){
    try{
      this.disableDelete = true;
      this._resourcesService.openSnackBar('Eliminando archivo...');

      let file = this.attached.filter(item => item.id == id);
      if(file.length == 0){
        this._resourcesService.openSnackBar('El archivo que desea eliminar no existe.');
        this.disableDelete = false;
      }else{
        let idUser = localStorage.getItem('idusuario')!;
        let response = await lastValueFrom(this._gdelService.deleteTempFile({
          'id_user': idUser,
          'id_file': id,
          'linea': 1,
        }));

        if(response.error){
          this._resourcesService.openSnackBar(response.msg);
        }else{
          let attachedAux: TempFileInfo[] = [];
          this.attached.forEach(file => {
            if(file.id != id) attachedAux.push(file);
          });
  
          this.attached = attachedAux;
          this.dataSource = new MatTableDataSource(this.attached);
          this._resourcesService.openSnackBar('El archivo se eliminó correctamente.');
        }
  
        this.disableDelete = false;
      }
    }catch(error: any){
      this.isUploading = false;
      let msg = "";
      if(error.error == undefined){
        msg = 'Ocurrió un error insperado.';
      }else if(error.error.msg == undefined){
        msg = 'Ocurrió un error insperado.';
      }else{
        msg = error.error.msg;
      }

      this._resourcesService.openSnackBar(msg);
      this.disableDelete = false;
    }
  }

  public alert() {
    if(this.attached.length <= 0){
      this._resourcesService.openSnackBar("Aún no se ha adjuntado ningún oficio.");
      return;
    }

    this._dialog.open(AlertComponent, {
      data: {
        title: 'Registrar Contrato',
        description: '¿Está seguro que desea registrar el contrato?',
        icon: 'warning',
      },
      disableClose: true,
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.storeContract();
      }
    });

  }

  private async storeContract() {
    try{
      this.isLoadingForm = true;

      if(this.formGroup.invalid){
        this._resourcesService.openSnackBar("Por favor complete todos los campos requeridos del formulario.");
        this.formGroup.markAllAsTouched();
      }else{
        let formValue = this.formGroup.getRawValue();
        let formData = new FormData();
        let idUser = localStorage.getItem('idusuario')!;
        let denomination = formValue.contractType == 'Interno' ? formValue.denominationIntern : formValue.denominationSubcontratist;

        let includeMeasures = formValue.includeMeasures ? 'S' : 'N';
        let workOrderStr = `${formValue.workOrder}|${formValue.orderType}|${includeMeasures}`;
        let workOrderEnc = await this._encService.encrypt(workOrderStr);

        formData.append('id_user', idUser);
        formData.append('linea', '1');
        formData.append('CONTRACT_NAME', formValue.name);
        formData.append('WORK_ORDER', workOrderEnc);
        formData.append('CONTRACT_TYPE', formValue.contractType);
        formData.append('DENOMINATION', denomination);

        let startMonth = formValue.startDate.getMonth() + 1;
        let startMonthStr = startMonth < 10 ? `0${startMonth}` : `${startMonth}`;
        let startDate = `${formValue.startDate.getFullYear()}-${startMonthStr}-${formValue.startDate.getDate()} ${formValue.startHour}`;

        let endMonth = formValue.endDate.getMonth() + 1;
        let endMonthStr = endMonth < 10 ? `0${endMonth}` : `${endMonth}`;
        let endDate = `${formValue.endDate.getFullYear()}-${endMonthStr}-${formValue.endDate.getDate()} ${formValue.endHour}`;
        let cost = await this._encService.encrypt(`${formValue.cost}`);

        formData.append('START_DATE', startDate);
        formData.append('END_DATE', endDate);
        formData.append('CONTRACT_COST', cost);

        let attachedStr = JSON.stringify(this.attached);
        formData.append('DOCUMENT', attachedStr);

        await lastValueFrom(this._interventionService.storeContract(formData));

        this._resourcesService.openSnackBar("¡Registro exitoso!");
        this.goBack(1);
      }
    }catch(error: any){
      let msg = "";
      if(error.error == undefined){
        msg = 'Ocurrió un error insperado.';
      }else if(error.error.msg == undefined){
        msg = 'Ocurrió un error insperado.';
      }else{
        msg = error.error.msg;
      }

      this._resourcesService.openSnackBar(msg);
      this.isLoadingForm = false;
    }
  }

  orderTypeChange(orderType: string){
    this.formGroup.controls['includeMeasures'].setValue(true);
    this.formGroup.controls['includeMeasures'].disable();
    this.formGroup.controls['workOrder'].setValue('');
    this.formGroup.controls['workOrder'].disable();
    this.formGroup.controls['contractType'].setValue('');
    this.formGroup.controls['denominationIntern'].setValue('');
    this.formGroup.controls['denominationIntern'].disable();
    this.formGroup.controls['denominationSubcontratist'].setValue('');
    this.formGroup.controls['denominationSubcontratist'].disable();

    this.interns = [];
    this.subcontratists = [];

    if(orderType == 'MP'){
      this.searchInterventions('P');
    }else if(orderType == 'MC'){
      this.formGroup.controls['includeMeasures'].enable();
      this.searchInterventions('C');
    }
  }

  includeMeasuresChange(event: any){
    this.formGroup.controls['workOrder'].setValue('');
    this.formGroup.controls['workOrder'].disable();
    this.formGroup.controls['contractType'].setValue('');
    this.formGroup.controls['denominationIntern'].setValue('');
    this.formGroup.controls['denominationIntern'].disable();
    this.formGroup.controls['denominationSubcontratist'].setValue('');
    this.formGroup.controls['denominationSubcontratist'].disable();

    this.interns = [];
    this.subcontratists = [];

    if(event.checked){
      this.searchInterventions('C');
    }else{
      this.searchNoMeasuresOrders();
    }
  }

  private async searchInterventions(orderType: string) {
    try{
      this.searchingOrders = true;

      let idUser = localStorage.getItem('idusuario')!;
      let orders: InterventionsListResponse = await lastValueFrom(this._interventionService.getConsultOfInterventions(idUser, 1));

      if(orders.error){
        this._resourcesService.openSnackBar(orders.msg);
      }else{
        let endedOrders: any[] = [];
        for(const intervention of orders.response){
          if(intervention.ORDER_TYPE == orderType && intervention.ACTION_TYPE == 'Finalizado'){
            let idOrder = await this._encService.decrypt(intervention.IDORDER);
            let interventionObj = {
              ID: intervention.IDREG,
              NAME: idOrder,
            };
            
            endedOrders.push(interventionObj);
          }else if(intervention.ORDER_TYPE == orderType && (intervention.ACTION_TYPE == 'CE' || intervention.ACTION_TYPE == 'CP')){
            let idOrder = await this._encService.decrypt(intervention.IDORDER);
            let interventionObj = {
              ID: intervention.IDREG,
              NAME: idOrder,
            };

            endedOrders.push(interventionObj);
          }
        }

        this.interventions = endedOrders;
        if(this.interventions.length > 0){
          this.formGroup.controls['workOrder'].enable();
        }
      }

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

      this.searchingOrders = false;
    }
  }

  private async searchNoMeasuresOrders(){
    try{
      this.searchingOrders = true;

      let idUser = localStorage.getItem('idusuario')!;
      let noMeasuresOrders: NoMeasuresOrdersListResponse = await lastValueFrom(this._correctiveMaintenanceService.getNoMeasuresOrders(idUser, 1));

      if(noMeasuresOrders.error){
        this._resourcesService.openSnackBar(noMeasuresOrders.msg);
      }else{
        let endedOrders: any[] = [];
        for(const order of noMeasuresOrders.response){
          if(order.ESTATUS == 'CV'){
            let idRegDec = await this._encService.decrypt(order.ID_REGISTRO);
            let orderObj = {
              ID: order.ID_REGISTRO,
              NAME: idRegDec,
            };

            endedOrders.push(orderObj);
          }
        }

        this.interventions = endedOrders;
        if(this.interventions.length > 0){
          this.formGroup.controls['workOrder'].enable();
        }
      }
      
      this.searchingOrders = false;
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
      
      this.searchingOrders = false;
    }
  }
}
