import { Component, OnInit } from '@angular/core';
import { CorrectiveMaintenanceOrderField, CustomSelectorOption, NoMeasuresFormFieldsListResponse } from '../../../interfaces/corrective-maintenance.interface';
import { FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms';
import { ResourcesService } from '../../../services/resources.service';
import { EncService } from '../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { validColorValidator } from 'ngx-colors';
import { SelectorOptionEditComponent } from './selector-option-edit/selector-option-edit.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { CorrectiveMaintenanceService } from '../../../services/corrective-maintenance.service';
import { lastValueFrom } from 'rxjs';
import { TimePickerComponent } from '../../resources/dialogs/time-picker/time-picker.component';
import moment from 'moment';
import { DeleteFormFieldSelectorComponent } from './delete-form-field-selector/delete-form-field-selector.component';

@Component({
    selector: 'app-corrective-work-order-form-fields',
    templateUrl: './corrective-work-order-form-fields.component.html',
    styleUrl: './corrective-work-order-form-fields.component.css',
    standalone: false
})
export class CorrectiveWorkOrderFormFieldsComponent implements OnInit {
  searchingNoMeasuresFormFields: boolean;
  noMeasuresFormFieldsHasError: boolean;
  noMeasuresFormFieldsErrorStr: string;
  noMeasuresFormFields: CorrectiveMaintenanceOrderField[];
  noMeasuresFormGroup: FormGroup;
  noMeasuresFormVisibilities: any;

  formType: string;
  savingForm: boolean;

  inputTypeSelector: number;
  obscurePreviewFieldText: boolean;
  selectorOptions: any[];
  addingOption: boolean;
  customFields: CorrectiveMaintenanceOrderField[];

  previewFieldControl: FormControl;
  previewColorFieldControl: FormControl;
  fieldConfigFormGroup: FormGroup;
  customFieldsFormGroup: FormGroup;
  customFieldPassVisibility: any;

  constructor(
    private _resourcesService: ResourcesService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
  ) {
    this.searchingNoMeasuresFormFields = false;
    this.noMeasuresFormFieldsHasError = false;
    this.noMeasuresFormFieldsErrorStr = '';
    this.noMeasuresFormFields = [];
    this.noMeasuresFormGroup = new FormGroup({});
    this.noMeasuresFormVisibilities = {};

    this.formType = 'RCM';
    this.savingForm = false;

    this.inputTypeSelector = 1;
    this.obscurePreviewFieldText = true;
    this.selectorOptions = [];
    this.addingOption = false;
    this.customFields = [];
    this.customFieldPassVisibility = {};

    this.previewFieldControl = new FormControl('');
    this.previewColorFieldControl = new FormControl("rgb(79, 195, 255)");
    this.fieldConfigFormGroup = new FormGroup({
      fieldTypeControl: new FormControl('TE-1', Validators.required),
      labelControl: new FormControl('', [Validators.required, Validators.minLength(4), Validators.maxLength(50)]),
      validatorsControl: new FormControl([]),
      minLengthControl: new FormControl({ value: 0, disabled: true }),
      maxLengthControl: new FormControl({ value: 0, disabled: true }),
      includeDecimalControl: new FormControl({ value: true, disabled: true }),
      allowResizeControl: new FormControl({ value: true, disabled: true }),
      defaultDateControl: new FormControl({ value: false, disabled: true }),
      enabledControl: new FormControl(true),
      defaultHourControl: new FormControl({ value: false, disabled: true }),
      colsControl: new FormControl({ value: 1, disabled: true }),
      rowsControl: new FormControl({ value: 1, disabled: true }),
      optionValueControl: new FormControl({ value: '', disabled: true }),
      optionTagControl: new FormControl({ value: '', disabled: true }),
      inlcudeEmptyOptionControl: new FormControl({ value: true, disabled: true }),
      isMultipleControl: new FormControl({ value: false, disabled: true }),
    });

    this.customFieldsFormGroup = new FormGroup({});
  }

  ngOnInit(): void {
    this.fieldConfigFormGroup.controls['includeDecimalControl'].valueChanges.subscribe((_) => {
      let previewValue = this.previewFieldControl.value;
      this.validateValue(previewValue);
    });
    
    this.previewFieldControl.valueChanges.subscribe((color) => {
      if(this.previewFieldControl.valid && this.inputTypeSelector == 5){
        this.previewColorFieldControl.setValue(color, {
          emitEvent: false,
        });
      }
    });

    this.previewColorFieldControl.valueChanges.subscribe((color) => {
      this.previewFieldControl.setValue(color, {
        emitEvent: false,
      })
    });
  }

  validateValue(value: string){
    let validators = this.fieldConfigFormGroup.controls['validatorsControl'].value;
    if(validators.includes('NUME')){
      let valueArr = value.split('');
      let validChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
      let includeDecimal = this.fieldConfigFormGroup.controls['includeDecimalControl'].value;
      let pointsCounter = 0;
      let validVal = '';

      for(const char of valueArr){
        if(char == '.' && pointsCounter < 1 && includeDecimal){
          validVal += '.';
          pointsCounter++;
        }else if(validChars.includes(char)){
          validVal += char;
        }
      }

      this.previewFieldControl.setValue(validVal);
    }

    this.previewFieldControl.markAsTouched();
  }

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

  inputTypeChange(value: string){
    this.fieldConfigFormGroup.controls['allowResizeControl'].disable();
    this.fieldConfigFormGroup.controls['defaultDateControl'].disable();
    this.fieldConfigFormGroup.controls['defaultHourControl'].setValue(false);
    this.fieldConfigFormGroup.controls['colsControl'].disable();
    this.fieldConfigFormGroup.controls['rowsControl'].disable();
    this.fieldConfigFormGroup.controls['optionValueControl'].disable();
    this.fieldConfigFormGroup.controls['optionTagControl'].disable();
    this.fieldConfigFormGroup.controls['inlcudeEmptyOptionControl'].disable();
    this.fieldConfigFormGroup.controls['isMultipleControl'].disable();

    let valueArr = value.split('-');
    if(valueArr.length > 1){
      this.inputTypeSelector = parseInt(valueArr[1]);
      switch(valueArr[0]){
        case "TE": 
          this.previewFieldControl = new FormControl('');
        break;
        case "FE":
          this.previewFieldControl = new FormControl('');
          this.fieldConfigFormGroup.controls['defaultDateControl'].enable();
        break;
        case "CT":
          this.previewFieldControl = new FormControl('');
          this.fieldConfigFormGroup.controls['allowResizeControl'].enable();
          this.fieldConfigFormGroup.controls['colsControl'].enable();
          this.fieldConfigFormGroup.controls['rowsControl'].enable();
        break;
        case "SE":
          this.previewFieldControl = new FormControl('');
          this.fieldConfigFormGroup.controls['optionValueControl'].enable();
          this.fieldConfigFormGroup.controls['optionTagControl'].enable();
          this.fieldConfigFormGroup.controls['inlcudeEmptyOptionControl'].enable();
          this.fieldConfigFormGroup.controls['isMultipleControl'].enable();
        break;
        case "NU":
          this.previewFieldControl = new FormControl('');
        break;
        case "CE":
          this.previewFieldControl = new FormControl('');
        break;
        case "CL":
          this.previewFieldControl = new FormControl("rgb(79, 195, 255)", [validColorValidator()]);
        break;
      }
    }

    this.fieldConfigFormGroup.controls['validatorsControl'].setValue([]);
  }

  validatorsChange(value: any[]){
    this.previewFieldControl.clearValidators();
    this.fieldConfigFormGroup.controls['minLengthControl'].disable();
    this.fieldConfigFormGroup.controls['maxLengthControl'].disable();
    this.fieldConfigFormGroup.controls['includeDecimalControl'].disable();

    let validatorsList: ValidatorFn[] = [];
    if(value.includes('CARE')){
      validatorsList.push(Validators.required);
    }
    
    if(value.includes('LOMI')){
      let minLengthValue = this.fieldConfigFormGroup.controls['minLengthControl'].value;
      this.fieldConfigFormGroup.controls['minLengthControl'].enable();
      validatorsList.push(Validators.minLength(parseInt(minLengthValue)));
    }
    
    if(value.includes('LOMA')){
      let maxLengthValue = this.fieldConfigFormGroup.controls['maxLengthControl'].value;
      this.fieldConfigFormGroup.controls['maxLengthControl'].enable();
      validatorsList.push(Validators.maxLength(parseInt(maxLengthValue)));
    }
    
    if(value.includes('NUME')){
      let numRegex = /^-?\d*[.,]?\d{0,2}$/;
      this.fieldConfigFormGroup.controls['includeDecimalControl'].enable();
      validatorsList.push(Validators.pattern(numRegex));
    }
    
    if(value.includes('COEL')){
      validatorsList.push(Validators.email);
    }
    
    if(value.includes('HORA')){
      this.fieldConfigFormGroup.controls['defaultHourControl'].enable();
    }else{
      this.fieldConfigFormGroup.controls['defaultHourControl'].disable();
    }

    this.previewFieldControl.setValidators(validatorsList);
    if(this.inputTypeSelector != 5){
      this.previewFieldControl.setValue('');
    }else{
      let currentColor = this.previewColorFieldControl.value;
      this.previewFieldControl.setValue(currentColor);
    }
  }

  lengthChange(control: string, value: string){
    let valueArr = value.split('');
    let validChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let validVal = '';

    for(const char of valueArr){
      if(validChars.includes(char)){
        validVal += char;
      }
    }

    let intVal = 0;
    if(validVal == ''){
      this.fieldConfigFormGroup.controls[control].setValue('0');
    }else{
      this.fieldConfigFormGroup.controls[control].setValue(validVal);
      intVal = parseInt(validVal);
    }

    if(control == 'minLengthControl'){
      this.previewFieldControl.setValidators(Validators.minLength(intVal));
    }else if(control == 'maxLengthControl'){
      this.previewFieldControl.setValidators(Validators.maxLength(intVal));
    }
  }

  sizeChange(control: string, value: string){
    let valueArr = value.split('');
    let validChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let validVal = '';

    for(const char of valueArr){
      if(validChars.includes(char)){
        validVal += char;
      }
    }

    if(validVal == ''){
      this.fieldConfigFormGroup.controls[control].setValue('1');
    }else{
      this.fieldConfigFormGroup.controls[control].setValue(validVal);
    }
  }

  async addSelectorOption(){
    this.addingOption = true;

    let optionValue = this.fieldConfigFormGroup.controls['optionValueControl'].value;
    if(optionValue == null || optionValue == undefined || optionValue == ''){
      this._resourcesService.openSnackBar('El valor de la opción no debe estar vacío.');
      this.addingOption = false;
      return;
    }

    let optionLabel = this.fieldConfigFormGroup.controls['optionTagControl'].value;
    if(optionLabel == null || optionLabel == undefined || optionLabel == ''){
      this._resourcesService.openSnackBar('La etiqueta de la opción no debe estar vacío.');
      this.addingOption = false;
      return;
    }

    let optionValueEnc = await this._encService.encrypt(optionValue);
    let optionFilt = this.selectorOptions.filter(option => option.valueDec == optionValue);
    if(optionFilt.length > 0){
      this._resourcesService.openSnackBar(`Ya existe una opción con valor '${optionValue}' registrada.`);
      this.addingOption = false;
      return;
    }

    this.selectorOptions.push({
      value: optionValueEnc,
      valueDec: optionValue,
      label: optionLabel,
    });

    this.addingOption = false;
    this.fieldConfigFormGroup.controls['optionValueControl'].setValue('');
    this.fieldConfigFormGroup.controls['optionTagControl'].setValue('');
  }

  openSelectorOptionEditor(value: string){
    let optionFilt = this.selectorOptions.filter(option => option.value == value);
    if(optionFilt.length > 0){
      let optionStr = JSON.stringify(optionFilt[0]);
      let dialogRef = this._dialog.open(SelectorOptionEditComponent, {
        width: '480px',
        maxWidth: '480px',
        disableClose: true,
        data: {
          option: optionStr,
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res != null && res != undefined && res != ''){
          this.updateSelectorOption(value, res);
        }
      });
    }
  }

  async updateSelectorOption(value: string, dataEnc: string){
    let selectorOptionsAux: any[] = [];
    for(const option of this.selectorOptions){
      if(option.value == value){
        let dataDec = await this._encService.decrypt(dataEnc);
        let dataObj = JSON.parse(dataDec);
        let idEnc = await this._encService.encrypt(dataObj.value);

        selectorOptionsAux.push({
          value: idEnc,
          valueDec: dataObj.value,
          label: dataObj.label
        });
      }else{
        selectorOptionsAux.push(option);
      }
    }

    this.selectorOptions = selectorOptionsAux;
  }

  openConfirmDelete(value: string){
    let optionFilt = this.selectorOptions.filter(option => option.value == value);
    if(optionFilt.length > 0){
      let dialogRef = this._dialog.open(AlertComponent, {
        width: '420px',
        maxWidth: '420px',
        disableClose: true,
        data: {
          title: '¡Cuidado!',
          icon: 'warning',
          description: `¿Está seguro de querer eliminar la opción '${optionFilt[0].label} (${optionFilt[0].valueDec})'`,
          description2: 'Esta acción no se puede deshacer.'
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res == true){
          let selectorOptionsAux: any[] = [];
          for(const option of this.selectorOptions){
            if(option.value != value){
              selectorOptionsAux.push(option);
            }
          }

          this.selectorOptions = selectorOptionsAux;
        }
      });
    }
  }

  async addFormField(){
    try{
      let formValue = this.fieldConfigFormGroup.getRawValue();
      if(formValue.fieldTypeControl == 'SE-4' && this.selectorOptions.length < 1){
        this._resourcesService.openSnackBar('El selector debe tener al menos una opción.');
        return;
      }

      let selectorOptions: CustomSelectorOption[] = [];
      for(const option of this.selectorOptions){
        let optionObj: CustomSelectorOption = {
          value: option.value,
          label: option.label
        };

        selectorOptions.push(optionObj);
      }

      let now = new Date();
      let fieldObj: CorrectiveMaintenanceOrderField = {
        fieldID: `${now.getTime()}`,
        allowResize: formValue.allowResizeControl,
        cols: formValue.colsControl,
        fieldType: formValue.fieldTypeControl,
        includeDecimal: formValue.includeDecimalControl,
        includeEmptyOption: formValue.inlcudeEmptyOptionControl,
        isMultiple: formValue.isMultipleControl,
        label: formValue.labelControl,
        maxLength: formValue.maxLengthControl,
        minLength: formValue.minLengthControl,
        rows: formValue.rowsControl,
        selectorOptions: selectorOptions,
        validators: JSON.stringify(formValue.validatorsControl),
        defaultDate: formValue.defaultDateControl,
        enabled: formValue.enabledControl,
        defaultHour: formValue.defaultHourControl
      };

      if(this.formType == 'RSM'){
        this.noMeasuresFormFields.push(fieldObj);
        this.resetNoMeasuresFormGroup();
      }

      this.inputTypeSelector = 1;
      this.fieldConfigFormGroup.controls['fieldTypeControl'].setValue('TE-1');
      this.fieldConfigFormGroup.controls['labelControl'].setValue('');
      this.fieldConfigFormGroup.controls['validatorsControl'].setValue([]);
      this.fieldConfigFormGroup.controls['minLengthControl'].setValue('0');
      this.fieldConfigFormGroup.controls['minLengthControl'].disable();

      this.fieldConfigFormGroup.controls['maxLengthControl'].setValue('0');
      this.fieldConfigFormGroup.controls['maxLengthControl'].disable();

      this.fieldConfigFormGroup.controls['includeDecimalControl'].setValue(true);
      this.fieldConfigFormGroup.controls['includeDecimalControl'].disable();

      this.fieldConfigFormGroup.controls['rowsControl'].setValue('1');
      this.fieldConfigFormGroup.controls['rowsControl'].disable();

      this.fieldConfigFormGroup.controls['colsControl'].setValue('1');
      this.fieldConfigFormGroup.controls['colsControl'].disable();

      this.fieldConfigFormGroup.controls['allowResizeControl'].setValue(true);
      this.fieldConfigFormGroup.controls['allowResizeControl'].disable();

      this.fieldConfigFormGroup.controls['optionValueControl'].setValue('');
      this.fieldConfigFormGroup.controls['optionValueControl'].disable();

      this.fieldConfigFormGroup.controls['optionTagControl'].setValue('');
      this.fieldConfigFormGroup.controls['optionTagControl'].disable();

      this.fieldConfigFormGroup.controls['inlcudeEmptyOptionControl'].setValue(true);
      this.fieldConfigFormGroup.controls['inlcudeEmptyOptionControl'].disable();

      this.fieldConfigFormGroup.controls['isMultipleControl'].setValue(false);
      this.fieldConfigFormGroup.controls['isMultipleControl'].disable();

      this.fieldConfigFormGroup.controls['enabledControl'].setValue(true);
      this.fieldConfigFormGroup.controls['defaultHourControl'].setValue(false);
      this.fieldConfigFormGroup.controls['defaultHourControl'].disable();

      this.fieldConfigFormGroup.controls['defaultDateControl'].setValue(false);
      this.fieldConfigFormGroup.controls['defaultDateControl'].disable();

      this.selectorOptions = [];

      this.previewFieldControl.clearValidators();
      this.previewFieldControl.enable();
      this.previewFieldControl.setValue(null);
    }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);
      }
    }
  }

  formTypeChange(value: string){
    this.formType = value;

    if(value == 'RSM'){
      this.searchingNoMeasuresFormFields = true;
      this.getNoMeasuresFormFields();
    }
  }

  private async getNoMeasuresFormFields() {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let noMeasuresFormFields: NoMeasuresFormFieldsListResponse = await lastValueFrom(this._correctiveMaintenanceService.getNoMeasuresFormFields(idUser, 1));

      this.noMeasuresFormFieldsHasError = noMeasuresFormFields.error;
      this.noMeasuresFormFieldsErrorStr = noMeasuresFormFields.msg;

      if(!this.noMeasuresFormFieldsHasError){
        let noMeasuresFormFieldsArr: CorrectiveMaintenanceOrderField[] = [];
        for(const field of noMeasuresFormFields.response.CAMPOS){
          field.fieldID = await this._encService.decrypt(field.fieldID);
          noMeasuresFormFieldsArr.push(field);
        }

        this.noMeasuresFormFields = noMeasuresFormFieldsArr;
        this.resetNoMeasuresFormGroup();
      }

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

      this.noMeasuresFormFieldsHasError = true;
      this.searchingNoMeasuresFormFields = false;
    }
  }

  resetNoMeasuresFormGroup(){
    this.noMeasuresFormGroup = new FormGroup({});

    for(const field of this.noMeasuresFormFields){
      let validatorsArr = JSON.parse(field.validators);
      let validators: ValidatorFn[] = [];

      for(const validator of validatorsArr){
        if(validator == 'CARE'){
          validators.push(Validators.required);
        }else if(validator == 'LOMI'){
          validators.push(Validators.minLength(field.minLength));
        }else if(validator == 'LOMA'){
          validators.push(Validators.maxLength(field.maxLength));
        }else if(validator == 'COEL'){
          validators.push(Validators.email);
        }else if(validator == 'CONT'){
          this.noMeasuresFormVisibilities[field.fieldID] = false;
        }
      }

      let initialVal: any = null;
      if(field.fieldType == 'TE-1' || field.fieldType == 'CT-3' || field.fieldType == 'SE-4') initialVal = '';
      else if(field.fieldType == 'FE-2') field.defaultDate ? initialVal = new Date() : initialVal = null;
      else if(field.fieldType == 'CL-5') { initialVal = "rgb(79, 195, 255)"; validators.push(validColorValidator()); }

      if(field.defaultHour){
        let date = new Date();
        let timestamp = date.getTime();
        let seconds = Math.trunc(timestamp / 1000);
        let minutesTmp = Math.trunc(seconds / 60) - date.getTimezoneOffset();
        let hoursTmp = Math.trunc(minutesTmp / 60);
        let daysTmp = Math.trunc(hoursTmp / 24);
        
        let overflowedHours = daysTmp * 24;
        let currentHour = hoursTmp - overflowedHours;
    
        let overflowedMinutes = (currentHour * 60) + (daysTmp * 24 * 60);
        let currentMinutes = minutesTmp - overflowedMinutes;
        let period = currentHour < 12 ? 'AM' : 'PM';
        let currentHourFn = currentHour > 12 ? currentHour - 12 : currentHour;
    
        let hourStr = currentHourFn < 10 ? `0${currentHourFn}` : `${currentHourFn}`;
        let minutesStr = currentMinutes < 10 ? `0${currentMinutes}` : `${currentMinutes}`;
        initialVal = `${hourStr}:${minutesStr} ${period}`;
      }

      this.noMeasuresFormGroup.addControl(`${field.fieldID}Control`, new FormControl({value: initialVal, disabled: !field.enabled}, validators));
      if(field.fieldType == 'CL-5'){
        this.noMeasuresFormGroup.addControl(`${field.fieldID}ColorControl`, new FormControl("rgb(79, 195, 255)", validators));
    
        this.noMeasuresFormGroup.controls[`${field.fieldID}Control`].valueChanges.subscribe((color) => {
          if(this.noMeasuresFormGroup.controls[`${field.fieldID}Control`].valid){
            this.noMeasuresFormGroup.controls[`${field.fieldID}ColorControl`].setValue(color, {
              emitEvent: false,
            });
          }
        });
    
        this.noMeasuresFormGroup.controls[`${field.fieldID}ColorControl`].valueChanges.subscribe((color) => {
          this.noMeasuresFormGroup.controls[`${field.fieldID}Control`].setValue(color, {
            emitEvent: false,
          })
        });
      }
    }
  }

  validateInput(value: string | string[], id: string){
    if(this.formType == 'RSM'){
      let fieldFilt = this.noMeasuresFormFields.filter(item => item.fieldID == id);
      if(fieldFilt.length > 0){
        let validVal: string | string[] = '';

        if(fieldFilt[0].fieldType == 'TE-1' || fieldFilt[0].fieldType == 'CT-3'){
          value = value as string;
          let validatorsArr = JSON.parse(fieldFilt[0].validators);

          if(validatorsArr.includes('NUME')){
            let validChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
            let valueArr = value.split('');
            let pointsCounter = 0;

            valueArr.forEach(char => {
              if(fieldFilt[0].includeDecimal && pointsCounter < 1 && char == '.'){
                validVal += '.';
                pointsCounter++;
              }else if(validChars.includes(char)){
                validVal += char;
              }
            });
          }else{
            validVal = value;
          }

          if(validatorsArr.includes('LOMA')){
            validVal = validVal.substring(0, fieldFilt[0].maxLength);
          }
        }else if(fieldFilt[0].fieldType == 'SE-4'){
          if(fieldFilt[0].isMultiple){
            value = value as string[];

            if(value.includes('N')){
              validVal = ['N'];
            }else{
              validVal = value;
            }
            console.log(validVal);
          }else{
            value = value as string;
            let optionFilt = fieldFilt[0].selectorOptions.filter(item => item.value == value);
            if(optionFilt.length > 0){
              validVal = optionFilt[0].value;
            }
          }
        }

        this.noMeasuresFormGroup.controls[`${fieldFilt[0].fieldID}Control`].setValue(validVal);
        console.log(fieldFilt[0].label);
        console.log(fieldFilt[0].fieldType);
        console.log(validVal);
      }
    }
  }

  defaultDateChange(event: any){
    let date = new Date();
    if(event.checked){
      this.previewFieldControl.setValue(date);
    }else{
      this.previewFieldControl.setValue(null);
    }
  }

  defaultHourChange(event: any){
    if(event.checked){
      let date = new Date();
      let timestamp = date.getTime();
      let seconds = Math.trunc(timestamp / 1000);
      let minutesTmp = Math.trunc(seconds / 60) - date.getTimezoneOffset();
      let hoursTmp = Math.trunc(minutesTmp / 60);
      let daysTmp = Math.trunc(hoursTmp / 24);
      
      let overflowedHours = daysTmp * 24;
      let currentHour = hoursTmp - overflowedHours;
  
      let overflowedMinutes = (currentHour * 60) + (daysTmp * 24 * 60);
      let currentMinutes = minutesTmp - overflowedMinutes;
      let period = currentHour < 12 ? 'AM' : 'PM';
      let currentHourFn = currentHour > 12 ? currentHour - 12 : currentHour;
  
      let hourStr = currentHourFn < 10 ? `0${currentHourFn}` : `${currentHourFn}`;
      let minutesStr = currentMinutes < 10 ? `0${currentMinutes}` : `${currentMinutes}`;
      let timeStr = `${hourStr}:${minutesStr} ${period}`;

      this.previewFieldControl.setValue(timeStr);
    }else{
      this.previewFieldControl.setValue(null);
    }
  }

  enabledChange(event: any){
    if(event.checked){
      this.previewFieldControl.enable();
    }else{
      this.previewFieldControl.disable();
    }
  }

  openPreviewHourSelector(value: string){
    let dialogRef = this._dialog.open(TimePickerComponent, {
      width: '320px',
      maxWidth: '320px',
      disableClose: true,
      data: {
        time: value,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.previewFieldControl.setValue(res);
      }
    });
  }

  openHourSelector(value: string, control: string){
    if(this.formType == 'RSM'){
      if(this.noMeasuresFormGroup.contains(control)){
        let dialogRef = this._dialog.open(TimePickerComponent, {
          width: '320px',
          maxWidth: '320px',
          disableClose: true,
          data: {
            time: value,
          }
        });
    
        dialogRef.afterClosed().subscribe(res => {
          if(res != null && res != undefined && res != ''){
            this.noMeasuresFormGroup.controls[control].setValue(res);
          }
        });
      }
    }
  }

  async saveFormFields(){
    try{
      this.savingForm = true;

      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');

      if(this.formType == 'RSM'){
        let noMeasuresFormFieldsStr = JSON.stringify(this.noMeasuresFormFields);
        let noMeasuresFormFieldsEnc = await this._encService.encrypt(noMeasuresFormFieldsStr);

        formData.append('form_fields', noMeasuresFormFieldsEnc);

        await lastValueFrom(this._correctiveMaintenanceService.saveNoMeasuresFormFields(formData));
      }

      this._resourcesService.openSnackBar('El formulario se actualizó correctamente.');
      this.goBack(1);
    }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.savingForm = false;
    }
  }

  openDeleteSelector(){
    let dialogRef = this._dialog.open(DeleteFormFieldSelectorComponent, {
      disableClose: true,
      width: '480px',
      maxWidth: '480px',
      data: {
        formFields: this.formType == 'RSM' ? this.noMeasuresFormFields : [],
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.alertDelteFormField(res);
      }
    });
  }

  private alertDelteFormField(fieldID: string) {
    let formFieldFilt = this.formType == 'RSM' ? 
    this.noMeasuresFormFields.filter(item => item.fieldID == fieldID) : 
    this.customFields.filter(item => item.fieldID == fieldID);

    if(formFieldFilt.length > 0){
      let formName = this.formType == 'RSM' ? 'Registro sin mediciones' : 'Registro con mediciones';
      let dialogRef = this._dialog.open(AlertComponent, {
        disableClose: true,
        width: '420px',
        maxWidth: '420px',
        data: {
          title: '¡Cuidado!',
          icon: 'warning',
          description: `¿Está seguro de eliminar el campo "${formFieldFilt[0].label} (${fieldID})" del formulario "${formName}"?`,
          description2: 'Esta acción no se puede deshacer.'
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res == true){
          let fieldsAux: CorrectiveMaintenanceOrderField[] = [];
          if(this.formType == 'RSM'){
            for(const field of this.noMeasuresFormFields){
              if(field.fieldID != fieldID){
                fieldsAux.push(field);
              }
            }

            this.noMeasuresFormFields = fieldsAux;
            this.resetNoMeasuresFormGroup();
          }else{
            console.log('PENDIENTE');
          }

          this._resourcesService.openSnackBar(`El campo "${formFieldFilt[0].label} (${fieldID})" fue eliminado correctamente.`);
        }
      });
    }
  }
}
