import { Component, Inject, OnInit } from '@angular/core';
import { PriorityInterface } from '../../../system-admin/system-params/system-params.component';
import { CorrectiveWorkOrderDetails, CorrectiveWorkOrderDetailsResponse } from '../../../../interfaces/corrective-maintenance.interface';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { CorrectiveMaintenanceService } from '../../../../services/corrective-maintenance.service';
import { EncService } from '../../../../services/enc.service';
import { FunctionsService } from '../../../../services/functions.service';
import { SystemAdminService } from '../../../../services/system-admin.service';
import { lastValueFrom } from 'rxjs';
import { CounterLastMeasuresListItem } from '../../../../interfaces/counters-activators.interface';
import { TempFileInfo } from '../../../../interfaces/temp-file-info.interface';
import { ResponseDataGetToolsAndSpare, ToolsAndSpare } from '../../../../interfaces/inventory-management/tools-and-spare.interface';
import { ResourcesService } from '../../../../services/resources.service';
import { InventoryManagementService } from '../../../../services/inventory-management/inventory-management.service';

@Component({
    selector: 'app-corrective-order-details',
    templateUrl: './corrective-order-details.component.html',
    styleUrl: './corrective-order-details.component.css',
    standalone: false
})
export class CorrectiveOrderDetailsComponent implements OnInit {
  idOrder: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  orderPriorities: PriorityInterface[];
  tools: ToolsAndSpare[];
  spareParts: ToolsAndSpare[];

  workOrder: CorrectiveWorkOrderDetails | null;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _encService: EncService,
    private _functionsService: FunctionsService,
    private _sysAdminService: SystemAdminService,
    private _resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
  ) {
    this.idOrder = '';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.orderPriorities = [];
    this.tools = [];
    this.spareParts = [];

    this.workOrder = null;
  }

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

  private async _getToolsAndSpare () {
    try{
      const USER: string = this._resourcesService.getUser();
      const LINE: number = this._resourcesService.getLineNumber();

      let responseData: ResponseDataGetToolsAndSpare = await lastValueFrom(this._inventoryManagementService.getToolsAndSpare(USER, LINE));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let toolsArr: ToolsAndSpare[] = [];
        for(const tool of responseData.response.HERRAMIENTAS){
          toolsArr.push(tool);
        }

        let sparePartsArr: ToolsAndSpare[] = [];
        for(const part of responseData.response.REFACCIONES){
          sparePartsArr.push(part);
        }

        this.tools = toolsArr;
        this.spareParts = sparePartsArr;
        this.getOrderPriorities();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (9).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (10).';
      }else{
        this.errorStr = error.error.msg;
      }
      
      this.hasError = true;
      this.isLoading = false;
    }
  }

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

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

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

          orderPriorities.push(priority);
        }

        this.orderPriorities = orderPriorities;
        this.getOrderDetails();
      }
    }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;
      }

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

  async getOrderDetails(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let order: CorrectiveWorkOrderDetailsResponse = await lastValueFrom(this._correctiveMaintenanceService.getWorkOrder(
        this._data.idOrder,
        idUser,
        1
      ));
      
      this.hasError = order.error;
      this.errorStr = order.msg;

      if(!this.hasError){
        order.response.ID_ORDEN = await this._encService.decrypt(order.response.ID_ORDEN);
        order.response.CONTADOR = await this._encService.decrypt(order.response.CONTADOR);

        let codeDec = await this._encService.decrypt(order.response.CODIGO_EQUIPAMIENTO);
        order.response.TIPO_EQUIPAMIENTO = `${codeDec} - ${order.response.TIPO_EQUIPAMIENTO}`;

        let idEquipmentDec = await this._encService.decrypt(order.response.ID_EQUIPAMIENTO);
        order.response.MODELO_EQUIPAMIENTO = `${order.response.MODELO_EQUIPAMIENTO} (${idEquipmentDec})`;

        let measureObj = JSON.parse(order.response.MEDIDAS);
        let measureObjKeys = Object.keys(measureObj);
        
        if(measureObjKeys.length > 0){
          let idSWDec = await this._encService.decrypt(measureObj.ID_SERVICIO_WEB);
          let measure: CounterLastMeasuresListItem = {
            ID_MEDIDA: await this._encService.decrypt (measureObj.ID_MEDIDA),
            CONTADOR: measureObj.CONTADOR,
            VALOR: measureObj.VALOR,
            ID_SERVICIO_WEB: measureObj.ID_SERVICIO_WEB,
            URL_SERVICIO_WEB: `${measureObj.URL_SERVICIO_WEB} (${idSWDec})`,
            HORA_REGISTRO: this._functionsService.orderDate(measureObj.HORA_REGISTRO)!
          };
          order.response.MEDIDAS_OBJ = measure;
        }
        
        let priorityDec = await this._encService.decrypt(order.response.PRIORIDAD);
        for(const priority of this.orderPriorities){
          let valDec = await this._encService.decrypt(priority.value);
          if(valDec == priorityDec){
            order.response.PRIORIDAD_OBJ = priority;
          }
        }

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

        let resourcesArr = JSON.parse(order.response.RECURSOS);
        let resourcesSelected: string[] = [];

        for(const resource of resourcesArr){
          if(resource.ID != 'SH'){
            let idDec = await this._encService.decrypt(resource.ID);
            resourcesSelected.push(`${idDec}-${resource.TYPE}`);
          }
        }

        let resourcesArrFn: any[] = [];
        for(const tool of this.tools){
          let toolID = await this._encService.decrypt(tool.ID);
          if(resourcesSelected.includes(`${toolID}-T`)){
            resourcesArrFn.push({
              label: `${tool.NOMB} - ${tool.MODE} (${toolID})`,
              type: tool.TYPE,
              unit: tool.UNIT,
              required: tool.CANTDISP
            });
          }
        }

        for(const part of this.spareParts){
          let partID = await this._encService.decrypt(part.ID);
          if(resourcesSelected.includes(`${partID}-S`)){
            resourcesArrFn.push({
              label: `${part.NOMB} - ${part.MODE} (${partID})`,
              type: part.TYPE,
              unit: part.UNIT,
              required: part.CANTDISP
            });
          }
        }

        let staffArr = JSON.parse(order.response.PERSONAL);
        let staffArrFn: any[] = [];
        for(const item of staffArr){
          staffArrFn.push({
            ID: item.ID,
            NAME: item.NAME,
            CANT: item.CANT
          });
        }

        order.response.RECURSOS_ARR = resourcesArrFn;
        order.response.PERSONAL_ARR = staffArrFn;

        let documentsArr = JSON.parse(order.response.DOCUMENTOS_RELACIONADOS);
        let documentsArrFn: TempFileInfo[] = [];
        for(const document of documentsArr as TempFileInfo[]){
          let idDec = await this._encService.decrypt(document.id);
          let file: TempFileInfo = {
            id: document.id,
            name: idDec,
            size: this._functionsService.formatBytes(parseInt(document.size)),
          };

          documentsArrFn.push(file);
        }

        order.response.DOCUMENTOS_RELACIONADOS_ARR = documentsArrFn;
        order.response.FECHA_INICIO = this._functionsService.orderDate(order.response.FECHA_INICIO)!;
        order.response.FECREG = this._functionsService.orderDate(order.response.FECREG)!;

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

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

        this.workOrder = order.response;
      }

      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;
    }
  }
}
