import { Component, Inject, OnInit } from '@angular/core';
import { PreventiveWorkOrder, PreventiveWorkOrderResponse } from '../../../../interfaces/preventive-work-order.interface';
import { FormControl } from '@angular/forms';
import { DOCUMENT } from '@angular/common';
import { PreventiveMaintenanceService } from '../../../../services/preventive-maintenance.service';
import { EncService } from '../../../../services/enc.service';
import { ActivatedRoute } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { ResourcesService } from '../../../../services/resources.service';
import { lastValueFrom } from 'rxjs';
import { HourSelectorComponent } from '../../../resources/hour-selector/hour-selector.component';
import { OrderDetailsComponent } from '../order-details/order-details.component';

@Component({
    selector: 'app-budget-analysis',
    templateUrl: './budget-analysis.component.html',
    styleUrl: './budget-analysis.component.css',
    standalone: false
})
export class BudgetAnalysisComponent implements OnInit {
  btnSmall: boolean = false;

  idOrder: number;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  workOrder: PreventiveWorkOrder | null;
  
  extraComments = new FormControl('');
  toolsArr: any[];
  sparePartsArr: any[];
  staffArr: any[];

  constructor(
    @Inject(DOCUMENT) private _document: Document,
    private _prevMaintService: PreventiveMaintenanceService,
    private _encService: EncService,
    private _router: ActivatedRoute,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
  ) { 
    this.idOrder = 0;
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.workOrder = null;
    this.btnSmall = window.innerWidth <= 1405;
    this.toolsArr = [];
    this.sparePartsArr = [];
    this.staffArr = []
  }

  ngOnInit(): void {
    this._router.queryParams.subscribe(res => {
      let idOrderEnc = res['data'];
      if(idOrderEnc == undefined || idOrderEnc == null || idOrderEnc == ''){
        this._resourcesService.openSnackBar('No se envió información.');
        this.goBack(1);
      }else{
        this.getWorkOrder(idOrderEnc);
      }
    });
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  async getWorkOrder(idOrderEnc: string){
    try{
      let idOrderDec = await this._encService.decrypt(idOrderEnc);
      this.idOrder = parseInt(idOrderDec);
      let idUser = localStorage.getItem('idusuario')!;

      let order: PreventiveWorkOrderResponse = await lastValueFrom(this._prevMaintService.getWorkOrder(
        idOrderEnc,
        idUser,
        1
      ));

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

      if(!this.hasError){
        this.workOrder = order.response;
        this.staffArr = await this.getStaffObj(this.workOrder.OPERARIOS);
      }
      
      this.isLoading = false;
      setTimeout(() => this.initAnalysis(), 100)
    }catch(error: any){
      console.log(error);
      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 getStaffObj(staffStr: string): Promise<Array<any>>{
    let staffArr = JSON.parse(staffStr);
    let objTmp: any[] = [];

    for(const item of staffArr){
      objTmp.push({
        ID: item.ID,
        NAME: item.NAME,
        CANT: item.CANT,
        PREC: 0.0,
        HORA: 0.0,
        TOTA: 0.0,
      });
    }
    
    return Promise.resolve(objTmp);
  }

  async initAnalysis(){
    if(this.workOrder != null && this.workOrder.ANALISIS != null){
      let analysisArr = JSON.parse(this.workOrder.ANALISIS);

      this.extraComments.setValue(analysisArr.extraComments);
      let teamsConfDec = [];
      for(const item of analysisArr.teamsConf){
        item.ID = await this._encService.decrypt(item.ID);
        teamsConfDec.push(item);
      }

      for(const item of this.staffArr){
        let idDec = await this._encService.decrypt(item.ID);
        let itemFilt = teamsConfDec.filter(item2 => item2.ID == idDec);

        if(itemFilt.length > 0){
          item.CANT = itemFilt[0].CANT;
          item.HORA = itemFilt[0].HORA;
          item.NAME = itemFilt[0].NAME;
          item.PREC = itemFilt[0].PREC;
          item.TOTA = itemFilt[0].TOTA;
        }
      }
    }
  }

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  validateNumber(value: string, id: string){
    let validChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let valueArr = value.split('');
    let dotCounter = 0;
    let validVal = '';

    for(const char of valueArr){
      if(char == '.' && dotCounter < 1){
        validVal += '.';
        dotCounter++;
      }else if(validChars.includes(char)){
        validVal += char;
      }
    }

    let input = this._document.getElementById(`cost-${id}`) as HTMLInputElement;
    input.value = validVal;

    let hours = this._document.getElementById(`hour-${id}`) as HTMLInputElement;
    let hoursVal = isNaN(parseFloat(hours.value)) ? 0 : parseFloat(hours.value);
    let itemFilt = this.staffArr.filter(item => item.ID == id);
    if(itemFilt.length > 0){
      itemFilt[0].TOTA = hoursVal * parseFloat(validVal);
    }
  }

  openDurationPicker(value: string, id: string){
    let dialogRef = this._dialog.open(HourSelectorComponent, {
      disableClose: true,
      width: '320px',
      maxWidth: '320px',
      data: {
        value: value,
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        let dataArr = res.split('|');
        let hours = parseInt(dataArr[0]);
        let minutes = parseInt(dataArr[1]);

        let floatMinutes = parseFloat((minutes / 60).toFixed(2));
        let duration = hours + floatMinutes;

        if(duration > this.workOrder!.DURACIONTOTAL){
          this._resourcesService.openSnackBar("Las horas del contrato de una especialidad u oficio no pueden ser mayores a la duración total de la orden");
        }else{
          let input = this._document.getElementById(`hour-${id}`) as HTMLInputElement;
          input.value = `${duration}`;
          
          let itemFilt = this.staffArr.filter(item => item.ID == id);
          let cost = this._document.getElementById(`cost-${id}`) as HTMLInputElement;
          if(itemFilt.length > 0){
            itemFilt[0].TOTA = duration * parseFloat(cost.value);
          }
        }
      }
    });
  }

  openOrderDetails(){
    this._dialog.open(OrderDetailsComponent, {
      width: '820px',
      maxWidth: '820px',
      data: {
        idOrder: this.idOrder,
      }
    })
  }

  async asignAnalysis(){
    try{
      let idUser = localStorage.getItem('idusuario');
      for(const item of this.staffArr){
        let contractHoursIpunt = this._document.getElementById(`hour-${item.ID}`) as HTMLInputElement;
        if(contractHoursIpunt != null){
          item.HORA = parseFloat(contractHoursIpunt.value);
        }else{
          item.HORA = 0;
        }

        let hourCostInput = this._document.getElementById(`cost-${item.ID}`) as HTMLInputElement;
        if(hourCostInput != null){
          item.PREC = parseFloat(hourCostInput.value);
        }else{
          item.PREC = 0;
        }
      }

      let idOrder = await this._encService.encrypt(`${this.idOrder}`);
      let formData = new FormData();
      let finalObj = {
        teamsConf: this.staffArr,
        extraComments: this.extraComments.value,
      };
    
      formData.append('id_user', idUser!);
      formData.append('linea', '1');
      formData.append('id_order', idOrder!);
      formData.append('analysis', JSON.stringify(finalObj));
    
      await lastValueFrom(this._prevMaintService.setBudgetAnalysis(formData));
      this._resourcesService.openSnackBar('El análisis presupuestario se asignó correctamente.');
      this.goBack(1);
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
