import { Component, Inject, OnInit } from '@angular/core';
import { EquipmentDetails } from '../../../interfaces/equipment-management.interface';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { MatTableDataSource } from '@angular/material/table';
import { PreventiveWorkOrders, PreventiveWorkOrdersResponse } from '../../../interfaces/preventive-work-orders.interface';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { FunctionsService } from '../../../services/functions.service';
import { SystemAdminService } from '../../../services/system-admin.service';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { PreventiveMaintenanceService } from '../../../services/preventive-maintenance.service';

@Component({
    selector: 'app-equipment-maintenance-plains',
    templateUrl: './equipment-maintenance-plains.component.html',
    styleUrl: './equipment-maintenance-plains.component.css',
    standalone: false
})
export class EquipmentMaintenancePlainsComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  equipment: EquipmentDetails | null;
  priorities: PriorityInterface[];

  preventiveOrders: MatTableDataSource<PreventiveWorkOrders>;
  preventiveDisplayedColumns = ['ID', 'FECINI', 'FECFIN', 'ACTI', 'PRIO', 'ESTADO'];
  correctiveMaintenancePlains: any[];

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _encService: EncService,
    private _preventiveMaintenaceService: PreventiveMaintenanceService,
    private _functionsService: FunctionsService,
    private _systemAdminService: SystemAdminService,
    private _router: Router,
    private _dialogRef: MatDialogRef<EquipmentMaintenancePlainsComponent>,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.equipment = null;
    this.priorities = [];
    this.preventiveOrders = new MatTableDataSource();
    this.correctiveMaintenancePlains = [];
  }

  ngOnInit(): void {
    this.equipment = this._data.equipment;
    console.log(this.equipment);
    
    this.getOrderPriorities();
  }

  async getOrderPriorities(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let priorities = await lastValueFrom(this._systemAdminService.getOrderPriorities(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let prioritiesArr: PriorityInterface[] = [];
        for(const priority of priorities.response.order_priorities as PriorityInterface[]){
          priority.label = `${priority.label} (${priority.value})`;
          priority.value = await this._encService.encrypt(priority.value);

          prioritiesArr.push(priority);
        }

        this.priorities = prioritiesArr;
        this.getPreventiveMaintenancePlains();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (1).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (2).';
      }else{
        this.errorStr = error.error.msg ;
      }
    }
  }

  async getPreventiveMaintenancePlains(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let equipmentCodeEnc = await this._encService.encrypt(this.equipment!.CODIGO);

      let preventiveOrders: PreventiveWorkOrdersResponse = await lastValueFrom(this._preventiveMaintenaceService.getWorkOrdersByEquipment(
        equipmentCodeEnc,
        idUser,
        1
      ));

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

      if(!this.hasError){
        let preventiveOrdersArr: PreventiveWorkOrders[] = [];
        for(const order of preventiveOrders.response){
          order.IDORDEN = await this._encService.decrypt(order.IDORDEN);
          order.FECHAINICIO = this._functionsService.orderDate(order.FECHAINICIO);
          order.ACTIVADOR = await this._encService.decrypt(order.ACTIVADOR!);
          order.ESTATUS = this.getStatusText(order.ESTATUS);

          if(order.FECHAFINAL != null){
            order.FECHAFINAL = this._functionsService.orderDate(order.FECHAFINAL);
          }

          let orderPriorityDec = await this._encService.decrypt(order.PRIORIDAD!);
          for(const priority of this.priorities){
            let valueDec = await this._encService.decrypt(priority.value);
            if(orderPriorityDec == valueDec){
              order.PRIORIDAD_OBJ = priority;
            }
          }

          preventiveOrdersArr.push(order);
        }
        
        this.preventiveOrders = new MatTableDataSource(preventiveOrdersArr);
        this.isLoading = false; 
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (3).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (4).';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  getStatusText(status: string): string{
    if(status == 'B'){
      return "Borrador";
    }else if(status == 'R'){
      return "Revisión";
    }else if(status == 'A'){
      return "Activo";
    }else if(status == 'E'){
      return "Eliminado";
    }
    return "";
  }

  async navigateToModule(module: string){
    let equipmentCodeEnc = await this._encService.encrypt(this.equipment!.CODIGO);
    console.log(equipmentCodeEnc);
    if(module == 'preventive'){
      this._dialogRef.close();
      this._router.navigate(['sam/GMPR/ORTR/COTP'], {
        queryParams: {
          data: equipmentCodeEnc,
        }
      });
    }
  }
}
