import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { lastValueFrom } from 'rxjs';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { CorrectiveMaintenanceOrderField, NoMeasuresOrderResponse } from '../../../../interfaces/corrective-maintenance.interface';
import { NoMeasuresOrderDetailsField } from '../no-measures-order-details/no-measures-order-details.component';
import { FunctionsService } from '../../../../services/functions.service';
import { CloseActivity } from '../close-no-measures-order/close-no-measures-order.component';
import { GdelService } from '../../../../services/gdel.service';
import { FormControl, Validators } from '@angular/forms';

@Component({
    selector: 'app-no-measures-order-close-validation',
    templateUrl: './no-measures-order-close-validation.component.html',
    styleUrl: './no-measures-order-close-validation.component.css',
    standalone: false
})
export class NoMeasuresOrderCloseValidationComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  idOrder: string;
  displayedData: NoMeasuresOrderDetailsField[];
  activities: CloseActivity[];
  evidence: string[];
  validatedByControl: FormControl;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _functionsService: FunctionsService,
    private _gdelService: GdelService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.idOrder = '';
    this.displayedData = [];
    this.activities = [];
    this.evidence = [];
    this.validatedByControl = new FormControl('', Validators.required);
  }

  ngOnInit(): void {
    this.getOrderDetails();
  }

  private async getOrderDetails(){
    try{
      this.idOrder = await this._encService.decrypt(this._data.idOrder);

      let idUser = localStorage.getItem('idusuario')!;
      let order: NoMeasuresOrderResponse = await lastValueFrom(this._correctiveMaintenanceService.getNoMeasuresOrder(
        this._data.idOrder,
        idUser,
        1
      ));

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

      if(!this.hasError){
        let formFields: CorrectiveMaintenanceOrderField[] = [];
        for(const field of order.response.FORMULARIO.CAMPOS){
          field.fieldID = await this._encService.decrypt(field.fieldID);
          formFields.push(field);
        }

        let dataDec = await this._encService.decrypt(order.response.DATOS.DATOS);
        let dataObj = JSON.parse(dataDec);
        let dataKeys = Object.keys(dataObj);

        let formValues: NoMeasuresOrderDetailsField[] = [];
        for(const key of dataKeys){
          let fieldFilt = formFields.filter(item => item.fieldID == key);
          if(fieldFilt.length > 0){
            let fieldVal = dataObj[key];
            if(fieldFilt[0].fieldType == 'SE-4'){
              let selectedOptionDec = await this._encService.decrypt(fieldVal);
              let selectedOptionFilt = fieldFilt[0].selectorOptions.filter(option => option.value == fieldVal);
              if(selectedOptionFilt.length > 0){
                fieldVal = `${selectedOptionFilt[0].label} (${selectedOptionDec})`;
              }else{
                fieldVal = selectedOptionDec;
              }
            }else if(fieldFilt[0].fieldType == 'FE-2'){
              fieldVal = this._functionsService.buildHumanDate(fieldVal);
            }else if(fieldFilt[0].validators.includes('HORA')){
              fieldVal = this._functionsService.convertFullHourToHumanHour(fieldVal);
            }
            
            let formField: NoMeasuresOrderDetailsField = {
              label: fieldFilt[0].label,
              value: fieldVal,
            };

            formValues.push(formField);
          }
        }

        this.displayedData = formValues;
        if(order.response.DATOS.ACTIVIDADES != null){
          this.activities = order.response.DATOS.ACTIVIDADES;
        }
        
        if(order.response.DATOS.EVIDENCIA != null){
          let evidence: string[] = [];
          for(const file of order.response.DATOS.EVIDENCIA){
            let publicURL = await lastValueFrom(this._gdelService.getPublicDocumentUrl(file, idUser, 1));
            if(!publicURL.error){
              evidence.push(publicURL.response.public_uri);
            }
          }

          this.evidence = evidence;
        }
      }
      
      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;
    }
  }
}
