import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { ResourcesService } from '../../../../services/resources.service';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { lastValueFrom } from 'rxjs';
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 { DataSelectorComponent } from '../no-measures-order-details/data-selector/data-selector.component';

@Component({
    selector: 'app-no-measures-order-report',
    templateUrl: './no-measures-order-report.component.html',
    styleUrl: './no-measures-order-report.component.css',
    standalone: false
})
export class NoMeasuresOrderReportComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  idOrder: string;
  reportType: string;
  reportTypeInd: string;

  orderData: NoMeasuresOrderDetailsField[];
  orderFormData: NoMeasuresOrderDetailsField[];
  reportData: NoMeasuresOrderDetailsField[];

  trainInterventionReport: Map<string, string | null>;
  fixedInstalationReport: Map<string, string | null>;
  failAttentionRegister: Map<string, string | null>;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _dialogRef: MatDialogRef<NoMeasuresOrderReportComponent>,
    private _resourcesService: ResourcesService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _functionsService: FunctionsService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.idOrder = '';
    this.reportType = '';
    this.reportTypeInd = '';

    this.orderData = [];
    this.orderFormData = [];
    this.reportData = [];

    this.trainInterventionReport = new Map();
    this.fixedInstalationReport = new Map();
    this.failAttentionRegister = new Map();
  }

  ngOnInit(): void {
    this.trainInterventionReport.set('fecha_de_emision', null);
    this.trainInterventionReport.set('record_number', null);
    this.trainInterventionReport.set('tren_m1_m2', null);
    this.trainInterventionReport.set('carro', null);
    this.trainInterventionReport.set('kms', null);
    this.trainInterventionReport.set('motivo_intervencion_f', null);
    this.trainInterventionReport.set('motivo_intervencion_m', null);
    this.trainInterventionReport.set('motivo_intervencion_s', null);
    this.trainInterventionReport.set('motivo_intervencion_ma', null);
    this.trainInterventionReport.set('descripcion_de_la_falla_moti', null);
    this.trainInterventionReport.set('fecha_entrega_del_tren_stc_a', null);
    this.trainInterventionReport.set('hora_stc', null);
    this.trainInterventionReport.set('entrega_por_stc_nombre', null);
    this.trainInterventionReport.set('recibe_por_mexirrc_nombre', null);
    this.trainInterventionReport.set('intervencion_realizada', null);
    this.trainInterventionReport.set('numero_de_serie_equipo_retir', null);
    this.trainInterventionReport.set('numero_de_serie_equipo_instal', null);
    this.trainInterventionReport.set('atendio', null);
    this.trainInterventionReport.set('firma_mexirrc:dateonly', null);
    this.trainInterventionReport.set('firma_mexirrc:timeonly', null);
    this.trainInterventionReport.set('entrega_por_mexirrc_nombre', null);
    this.trainInterventionReport.set('firma_mexirrc-110x30', null);
    this.trainInterventionReport.set('recibe_por_stc_nombre', null);
    this.trainInterventionReport.set('firma_stc_csft-110x30', null);
    this.trainInterventionReport.set('comentarios_u_observaciones', null);

    this.fixedInstalationReport.set('record_number', null);
    this.fixedInstalationReport.set('semana_num', null);
    this.fixedInstalationReport.set('fecha_del_reporte', null);
    this.fixedInstalationReport.set('turno', null);
    this.fixedInstalationReport.set('ubicacion', null);
    this.fixedInstalationReport.set('tecnicos', null);
    this.fixedInstalationReport.set('num_incidencia', null);
    this.fixedInstalationReport.set('comunica_la_incidencia', null);
    this.fixedInstalationReport.set('incidencia_abierta_el', null);
    this.fixedInstalationReport.set('tecnica', null);
    this.fixedInstalationReport.set('sistema', null);
    this.fixedInstalationReport.set('subsistema', null);
    this.fixedInstalationReport.set('local_tecnico', null);
    this.fixedInstalationReport.set('gabinete', null);
    this.fixedInstalationReport.set('p_k', null);
    this.fixedInstalationReport.set('via', null);
    this.fixedInstalationReport.set('elemento', null);
    this.fixedInstalationReport.set('descripcion', null);
    this.fixedInstalationReport.set('estado_inicial', null);
    this.fixedInstalationReport.set('accion_correctora', null);
    this.fixedInstalationReport.set('fecha_hora_disponible_del_e', null);
    this.fixedInstalationReport.set('fecha_y_hora1', null);
    this.fixedInstalationReport.set('observaciones', null);
    this.fixedInstalationReport.set('dias', null);
    this.fixedInstalationReport.set('horas', null);
    this.fixedInstalationReport.set('fecha_y_hora2', null);
    this.fixedInstalationReport.set('observaciones1', null);
    this.fixedInstalationReport.set('dias1', null);
    this.fixedInstalationReport.set('horas1', null);
    this.fixedInstalationReport.set('fecha_y_hora3', null);
    this.fixedInstalationReport.set('observaciones2', null);
    this.fixedInstalationReport.set('dias2', null);
    this.fixedInstalationReport.set('horas2', null);
    this.fixedInstalationReport.set('fecha_y_hora4', null);
    this.fixedInstalationReport.set('observaciones3', null);
    this.fixedInstalationReport.set('dias3', null);
    this.fixedInstalationReport.set('horas3', null);
    this.fixedInstalationReport.set('dias4', null);
    this.fixedInstalationReport.set('horas4', null);
    this.fixedInstalationReport.set('fecha_y_hora5', null);
    this.fixedInstalationReport.set('observaciones4', null);
    this.fixedInstalationReport.set('fecha_y_hora6', null);
    this.fixedInstalationReport.set('observaciones5', null);
    this.fixedInstalationReport.set('fecha_y_hora7', null);
    this.fixedInstalationReport.set('observaciones6', null);
    this.fixedInstalationReport.set('estado_de_averia', null);
    this.fixedInstalationReport.set('fecha_y_hora8', null);
    this.fixedInstalationReport.set('observaciones7', null);
    this.fixedInstalationReport.set('descripcion1', null);
    this.fixedInstalationReport.set('codigo1', null);
    this.fixedInstalationReport.set('n_s_averiado1', null);
    this.fixedInstalationReport.set('n_s_nuevo1', null);
    this.fixedInstalationReport.set('unids1', null);
    this.fixedInstalationReport.set('descripcion2', null);
    this.fixedInstalationReport.set('codigo2', null);
    this.fixedInstalationReport.set('n_s_averiado2', null);
    this.fixedInstalationReport.set('n_s_nuevo2', null);
    this.fixedInstalationReport.set('unids2', null);
    this.fixedInstalationReport.set('descripcion3', null);
    this.fixedInstalationReport.set('codigo3', null);
    this.fixedInstalationReport.set('n_s_averiado3', null);
    this.fixedInstalationReport.set('n_s_nuevo3', null);
    this.fixedInstalationReport.set('unids3', null);
    this.fixedInstalationReport.set('descripcion4', null);
    this.fixedInstalationReport.set('codigo4', null);
    this.fixedInstalationReport.set('n_s_averiado4', null);
    this.fixedInstalationReport.set('n_s_nuevo4', null);
    this.fixedInstalationReport.set('unids4', null);
    this.fixedInstalationReport.set('descripcion5', null);
    this.fixedInstalationReport.set('codigo5', null);
    this.fixedInstalationReport.set('n_s_averiado5', null);
    this.fixedInstalationReport.set('n_s_nuevo5', null);
    this.fixedInstalationReport.set('unids5', null);
    this.fixedInstalationReport.set('descripcion6', null);
    this.fixedInstalationReport.set('codigo6', null);
    this.fixedInstalationReport.set('n_s_averiado6', null);
    this.fixedInstalationReport.set('n_s_nuevo6', null);
    this.fixedInstalationReport.set('unids6', null);
    this.fixedInstalationReport.set('descripcion7', null);
    this.fixedInstalationReport.set('codigo7', null);
    this.fixedInstalationReport.set('n_s_averiado7', null);
    this.fixedInstalationReport.set('n_s_nuevo7', null);
    this.fixedInstalationReport.set('unids7', null);
    this.fixedInstalationReport.set('descripcion8', null);
    this.fixedInstalationReport.set('codigo8', null);
    this.fixedInstalationReport.set('n_s_averiado8', null);
    this.fixedInstalationReport.set('n_s_nuevo8', null);
    this.fixedInstalationReport.set('unids8', null);
    this.fixedInstalationReport.set('observaciones_generales', null);

    this.failAttentionRegister.set('fecha', null);
    this.failAttentionRegister.set('reporto', null);
    this.failAttentionRegister.set('record_number', null);
    this.failAttentionRegister.set('recibio_por_mexirrc', null);
    this.failAttentionRegister.set('hora_en_que_recibe_reporte', null);
    this.failAttentionRegister.set('descripcion_del_reporte', null);
    this.failAttentionRegister.set('actividad_desarrollada', null);
    this.failAttentionRegister.set('la_falla_se_debio_a', null);
    this.failAttentionRegister.set('inicio', null);
    this.failAttentionRegister.set('termino', null);
    this.failAttentionRegister.set('total', null);
    this.failAttentionRegister.set('situacion_del_reporte1-TE', null);
    this.failAttentionRegister.set('se_le_comunico_al_sr', null);
    this.failAttentionRegister.set('situacion_del_reporte1-A', null);
    this.failAttentionRegister.set('del_pdc_a_las', null);
    this.failAttentionRegister.set('situacion_del_reporte1-PE', null);
    this.failAttentionRegister.set('reporto_por_vias', null);
    this.failAttentionRegister.set('situacion_del_reporte1-T', null);
    this.failAttentionRegister.set('personal_de_vias_que_atendio', null);
    this.failAttentionRegister.set('tipo_de_averia-R', null);
    this.failAttentionRegister.set('tipo_de_averia-F', null);
    this.failAttentionRegister.set('tipo_de_averia-C', null);
    this.failAttentionRegister.set('observaciones', null);
    this.failAttentionRegister.set('responsable_mexirrc_s_a_de', null);
    this.failAttentionRegister.set('firma_mexirrc-130x30', null);
    this.failAttentionRegister.set('por_el_s_t_c', null);
    this.failAttentionRegister.set('firma_stc-130x30', null);

    this.init();
  }

  async init(){
    this.idOrder = await this._encService.decrypt(this._data.idOrder);
    if(this._data.reportType == 'RITR'){
      this.reportType = 'REPORTE DE INTERVENCIÓN PARA TRENES MODELO NM16 / NM22, CONTRATO STC-CNCS-195/2022';
    }else if(this._data.reportType == 'RIIF'){
      this.reportType = 'Reporte de Incidencias Instalación Fija';
    }else if(this._data.reportType == 'RAAV'){
      this.reportType = 'REGISTRO DE ATENCIÓN DE AVERIAS';
    }else{
      this._resourcesService.openSnackBar('El tipo de reporte seleccionado es inválido.');
      this._dialogRef.close('');
      return;
    }

    this.reportTypeInd = this._data.reportType;
    this.getNoMeasuresOrder();
  }

  private async getNoMeasuresOrder(){
    try{
      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 idReg = await this._encService.decrypt(order.response.DATOS.ID_REGISTRO);
        this.orderData.push({
          label: 'ID Registro',
          value: idReg
        });
        
        this.orderData.push({
          label: 'Validado por',
          value: order.response.DATOS.VALIDADO_POR!,
        });
        
        this.orderData.push({
          label: 'Expediente',
          value: order.response.DATOS.EXPEDIENTE!,
        });
        
        this.orderData.push({
          label: 'Fecha de registro',
          value: this._functionsService.orderDate(order.response.DATOS.FECHA_REGISTRO),
        });
        
        this.orderData.push({
          label: 'Usuario que registró',
          value: order.response.DATOS.USUARIO_REGISTRO!,
        });
        
        this.orderData.push({
          label: 'Fecha de actualización',
          value: this._functionsService.orderDate(order.response.DATOS.FECHA_ACTUALIZACION!),
        });
        
        this.orderData.push({
          label: 'Usuario que actualizó',
          value: order.response.DATOS.USUARIO_ACTUALIZACION!,
        });

        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.orderFormData = formValues;
      }

      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;
    }
  }
  
  openDataSelector(keyData: string, reportType: string){
    if(reportType == 'RITR' && this.trainInterventionReport.has(keyData)){
      let valueData = this.trainInterventionReport.get(keyData);
      let dialogRef = this._dialog.open(DataSelectorComponent, {
        width: '420px',
        maxWidth: '420px',
        disableClose: true,
        data: {
          keyData: keyData,
          valueData: valueData,
          orderData: this.orderData,
          orderFormData: this.orderFormData,
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res != null && res != undefined && res != ''){
          this.trainInterventionReport.set(keyData, res);
        }
      });
    }else if(reportType == 'RIIF' && this.fixedInstalationReport.has(keyData)){
      let valueData = this.fixedInstalationReport.get(keyData);
      let dialogRef = this._dialog.open(DataSelectorComponent, {
        width: '420px',
        maxWidth: '420px',
        disableClose: true,
        data: {
          keyData: keyData,
          valueData: valueData,
          orderData: this.orderData,
          orderFormData: this.orderFormData,
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res != null && res != undefined && res != ''){
          this.fixedInstalationReport.set(keyData, res);
        }
      });
    }else if(reportType == 'RAAV' && this.failAttentionRegister.has(keyData)){
      let valueData = this.failAttentionRegister.get(keyData);
      let dialogRef = this._dialog.open(DataSelectorComponent, {
        width: '420px',
        maxWidth: '420px',
        disableClose: true,
        data: {
          keyData: keyData,
          valueData: valueData,
          orderData: this.orderData,
          orderFormData: this.orderFormData,
        }
      });

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

  async printReport(reportType: string){
    let reportDataObj: any = {};

    if(reportType == 'RITR'){
      for(const key of this.trainInterventionReport.keys()){
        reportDataObj[key] = this.trainInterventionReport.get(key);
      }
    }else if(reportType == 'RIIF'){
      for(const key of this.fixedInstalationReport.keys()){
        reportDataObj[key] = this.fixedInstalationReport.get(key);
      }
    }else if(reportType == 'RAAV'){
      for(const key of this.failAttentionRegister.keys()){
        reportDataObj[key] = this.failAttentionRegister.get(key);
      }
    }
    
    let reportDataStr = JSON.stringify(reportDataObj);
    let reportDataEnc = await this._encService.encrypt(reportDataStr);

    this._dialogRef.close(reportDataEnc);
  }
}
