import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { PriorityInterface } from 'src/app/components/system-admin/system-params/system-params.component';
import { CorrectiveWorkOrderDetails, CorrectiveWorkOrderDetailsResponse } from 'src/app/interfaces/corrective-maintenance.interface';
import { CounterLastMeasuresListItem } from 'src/app/interfaces/counters-activators.interface';
import { TempFileInfo } from 'src/app/interfaces/temp-file-info.interface';
import { CorrectiveMaintenanceService } from 'src/app/services/corrective-maintenance.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { FunctionsService } from 'src/app/services/functions.service';
import { SystemAdminService } from 'src/app/services/system-admin.service';

interface ToolInfo{
  ID: string;
  NOMB: string;
  MODE: string;
  CANTDISP: number;
  TYPE: string;
  UNIT: string;
}
const TOOLS_TMP: ToolInfo[] = [
  {ID: 'H1', NOMB: 'Pinzas eléctricas', MODE: 'PE-862', CANTDISP: 35, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H2', NOMB: 'Pinzas mecánicas', MODE: 'M985', CANTDISP: 27, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H3', NOMB: 'Pinzas de presión', MODE: 'RG-12', CANTDISP: 30, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H4', NOMB: 'Juego de llaves Allen', MODE: 'ALL88', CANTDISP: 75, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H5', NOMB: 'Extractor de rodamientos', MODE: 'EX-ROD-1500', CANTDISP: 3, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H6', NOMB: 'Kit llaves inglesas', MODE: '5530S', CANTDISP: 7, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H7', NOMB: 'Kit llaves españolas', MODE: '964F', CANTDISP: 8, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H8', NOMB: 'Juego de llaves Torx', MODE: 'TORX3423W', CANTDISP: 42, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H9', NOMB: 'Cautín de lápiz 33W', MODE: '33WCL', CANTDISP: 15, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H10', NOMB: 'Juego de dados milimétricos', MODE: 'DMM450', CANTDISP: 6, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H11', NOMB: 'Juego de dados pulgadas', MODE: 'DIN865', CANTDISP: 9, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H12', NOMB: 'Probador de corriente', MODE: '569', CANTDISP: 33, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H13', NOMB: 'Multímetro', MODE: 'TGH885', CANTDISP: 17, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H14', NOMB: 'Planta generadora para soldadura', MODE: 'PLAGEN-589', CANTDISP: 1, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H15', NOMB: 'Amperímetro de gancho', MODE: 'A0032', CANTDISP: 4, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H16', NOMB: 'Rotomartillo', MODE: '551', CANTDISP: 2, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H17', NOMB: 'Kit taladro inalámbrico', MODE: 'FP581', CANTDISP: 12, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H18', NOMB: 'Kit taládro alámbrico', MODE: 'HG862', CANTDISP: 10, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H19', NOMB: 'Juego de desarmadores', MODE: '8913-KSOA', CANTDISP: 5, TYPE: 'Herramienta', UNIT: 'Pieza'},
  {ID: 'H20', NOMB: 'Martillo', MODE: 'TS438', CANTDISP: 23, TYPE: 'Herramienta', UNIT: 'Pieza'},
];
const SPARE_PARTS_TMP: ToolInfo[] = [
  {ID: 'S1', NOMB: 'Neumático para NM-16', MODE: 'NM16NEU235', CANTDISP: 45, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S2', NOMB: 'Neumático para NM-22', MODE: 'NM22NEU652', CANTDISP: 51, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S3', NOMB: 'Rodamiento cónico', MODE: 'RC-4265', CANTDISP: 84, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S4', NOMB: 'Rodamiento axial', MODE: 'RA-5130', CANTDISP: 96, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S5', NOMB: 'Rodamiento angular', MODE: 'RN-3541', CANTDISP: 79, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S6', NOMB: 'Grasa 1-310', MODE: 'G1.310', CANTDISP: 9, TYPE: 'Refaccción', UNIT: 'Kilogramo'},
  {ID: 'S7', NOMB: 'Aceite 10W-40', MODE: 'A10W40', CANTDISP: 16, TYPE: 'Refaccción', UNIT: 'Litro'},
  {ID: 'S8', NOMB: 'Soldadura de estaño', MODE: 'LDA-913', CANTDISP: 39, TYPE: 'Refaccción', UNIT: 'Metro'},
  {ID: 'S9', NOMB: 'Soldadura de plata', MODE: 'BDA-516', CANTDISP: 21, TYPE: 'Refaccción', UNIT: 'Metro'},
  {ID: 'S10', NOMB: 'Pastilla de frenado', MODE: '754SSV', CANTDISP: 25, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S11', NOMB: 'Cable de cobre calibre 0', MODE: 'CC0-884', CANTDISP: 120, TYPE: 'Refaccción', UNIT: 'Metro'},
  {ID: 'S12', NOMB: 'Rosetas de cable Ethernet', MODE: '165-BFS', CANTDISP: 12, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S13', NOMB: 'Pintura', MODE: '53469', CANTDISP: 250, TYPE: 'Refaccción', UNIT: 'Litro'},
  {ID: 'S14', NOMB: 'Solvente de pintura', MODE: '2516', CANTDISP: 310, TYPE: 'Refaccción', UNIT: 'Litro'},
  {ID: 'S15', NOMB: 'Lámina galvanizada', MODE: 'SFAS-320', CANTDISP: 38, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S16', NOMB: 'Botón de freno de emergencia', MODE: 'B-51321', CANTDISP: 14, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S17', NOMB: 'Disco duro de estado sólido 512GB', MODE: 'SSD-512', CANTDISP: 22, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S18', NOMB: 'Mouse óptico', MODE: 'MO1165', CANTDISP: 26, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S19', NOMB: 'Teclado para PC', MODE: '5413', CANTDISP: 24, TYPE: 'Refaccción', UNIT: 'Pieza'},
  {ID: 'S20', NOMB: 'Cable HDMI 2m', MODE: 'ASD-181', CANTDISP: 6, TYPE: 'Refaccción', UNIT: 'Pieza'},
];
@Component({
  selector: 'app-corrective-order-details',
  templateUrl: './corrective-order-details.component.html',
  styleUrls: ['./corrective-order-details.component.css']
})
export class CorrectiveOrderDetailsComponent implements OnInit {
  idOrder: string;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

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

  workOrder: CorrectiveWorkOrderDetails | null;

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

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

    this.workOrder = null;
  }

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

  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.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }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 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 resourcesArrFn: any[] = [];
        for(const resource of resourcesArr){
          let toolFilt = this.tools.filter(item => item.ID == resource.ID);
          let sparePartFilt = this.spareParts.filter(item => item.ID == resource.ID);

          if(toolFilt.length > 0){
            let tool = toolFilt[0];
            resourcesArrFn.push({
              label: `${tool.NOMB} - ${tool.MODE} (${tool.ID})`,
              type: tool.TYPE,
              unit: tool.UNIT,
              required: resource.REQ
            });
          }

          if(sparePartFilt.length > 0){
            let sparePart = sparePartFilt[0];
            resourcesArrFn.push({
              label: `${sparePart.NOMB} - ${sparePart.MODE} (${sparePart.ID})`,
              type: sparePart.TYPE,
              unit: sparePart.UNIT,
              required: resource.REQ
            });
          }
        }

        let staffArr = JSON.parse(order.response.PERSONAL);
        let staffArrFn: any[] = [];
        for(const item of staffArr){
          let type = '';
          if(item.TYPE == 'EQ') type = 'Equipo de trabajo';
          else if(item.TYPE == 'SU') type = 'Subcontratista';
          else if(item.TYPE == 'EM') type = 'Empleado';

          staffArrFn.push({
            ID: item.ID,
            TYPE: type,
            NAME: item.NAME
          });
        }

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

        console.log(order.response);
        this.workOrder = order.response;
      }

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