import { Component, Inject, OnInit } from '@angular/core';
import { InterventionsListItem } from '../../../../interfaces/personal-managment/intervention.interface';
import { OrderExecutionDetails, OrderExecutionDetailsResponse } from '../../../../interfaces/preventive-order-execution.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { FunctionsService } from '../../../../services/functions.service';
import { PreventiveMaintenanceService } from '../../../../services/preventive-maintenance.service';
import { lastValueFrom } from 'rxjs';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { CorrectiveWorkOrderDetails, CorrectiveWorkOrderDetailsResponse } from '../../../../interfaces/corrective-maintenance.interface';

@Component({
    selector: 'app-intervention-details',
    templateUrl: './intervention-details.component.html',
    styleUrl: './intervention-details.component.css',
    standalone: false
})
export class InterventionDetailsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  intervention: InterventionsListItem;
  title: string;
  preventiveOrder: OrderExecutionDetails | null;
  correctiveOrder: CorrectiveWorkOrderDetails | null;
  orderType: string;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: InterventionsListItem,
    private _encService: EncService,
    private _functionsService: FunctionsService,
    private _prevMaintService: PreventiveMaintenanceService,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.intervention = this._data;
    this.title = "";
    this.preventiveOrder = null;
    this.correctiveOrder = null;
    this.orderType = "";
  }

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

  async init(){
    let orderType = this._data.ORDER_TYPE == 'P' ? 'preventivo' : 'correctivo';
    this.title = `Orden de mantenimiento ${orderType} #${this._data.IDORDER}`;

    this.getExecutionDetails();
  }

  async getExecutionDetails(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let execution: OrderExecutionDetailsResponse | CorrectiveWorkOrderDetailsResponse | null = null;

      if(this._data.ORDER_TYPE == 'P'){
        let idRegDec = await this._encService.decrypt(this._data.IDREG);
        let idRegArr = idRegDec.split('|');
        let idRegStr = `${idRegArr[0]}|1|${this._data.IDORDER}|${idRegArr[1]}`;
        let idRegEnc = await this._encService.encrypt(idRegStr);

        execution = await lastValueFrom(this._prevMaintService.getOrderExecutionDetails(idRegEnc, idUser, 1));
      }else{
        execution = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrder(this._data.IDREG, idUser, 1));
      }


      if(execution == null){
        this.hasError = true;
        this.errorStr = 'No se encontró el registro de la orden de mantenimiento solicitada.';
      }else{
        this.hasError = execution.error;
        this.errorStr = execution.msg;

        if(!this.hasError){
          if(this._data.ORDER_TYPE == 'P'){
            let preventiveOrder = execution.response as OrderExecutionDetails;
            
            preventiveOrder.IDREGISTRO = await this._encService.decrypt(preventiveOrder.IDREGISTRO);
            preventiveOrder.IDORDEN = await this._encService.decrypt(preventiveOrder.IDORDEN);
            preventiveOrder.FECHAPROGRAMACION = this._functionsService.buildHumanDateWithDay(preventiveOrder.FECHAPROGRAMACION);
            preventiveOrder.FECHAEJECUCION = this._functionsService.orderDate(preventiveOrder.FECHAEJECUCION);

            if(preventiveOrder.FECHAFINALIZACION != null){
              preventiveOrder.FECHAFINALIZACION = this._functionsService.orderDate(preventiveOrder.FECHAFINALIZACION);
            }

            this.preventiveOrder = preventiveOrder;
          }else{
            let correctiveOrder = execution.response as CorrectiveWorkOrderDetails;
            correctiveOrder.ID_ORDEN = await this._encService.decrypt(correctiveOrder.ID_ORDEN);
            correctiveOrder.FECHA_INICIO = this._functionsService.orderDate(correctiveOrder.FECHA_INICIO);

            if(correctiveOrder.FECHA_FINAL != null){
              correctiveOrder.FECHA_FINAL = this._functionsService.orderDate(correctiveOrder.FECHA_FINAL);
            }

            this.correctiveOrder = correctiveOrder;
          }
        }
      }

      this.orderType = this._data.ORDER_TYPE;
      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;
      }
    }
  }
}
