import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { PreventiveWorkOrdersActive, PreventiveWorkOrdersActiveResponse } from '../../../interfaces/preventive-work-orders-active.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { PreventiveMaintenanceService } from '../../../services/preventive-maintenance.service';
import { FunctionsService } from '../../../services/functions.service';
import { MatDialog } from '@angular/material/dialog';
import { SystemAdminService } from '../../../services/system-admin.service';
import { lastValueFrom } from 'rxjs';
import { SimulationDialogComponent } from './simulation-dialog/simulation-dialog.component';

@Component({
    selector: 'app-maintenance-simulation',
    templateUrl: './maintenance-simulation.component.html',
    styleUrl: './maintenance-simulation.component.css',
    standalone: false
})
export class MaintenanceSimulationComponent implements OnInit {
  btnSmall: boolean;
  txtBuscador:string;

  dataSource?: MatTableDataSource<PreventiveWorkOrdersActive>;
  displayedColumns = ['ID', 'EQUIP', 'FECINI', 'FECFIN', 'TIEEST', 'TIETOT', 'ACTI', 'PRIO', 'ACCIONES'];

  isLoading: boolean;
  hasError: boolean;
  errorStr: string; 

  @ViewChild(MatPaginator) paginator?: MatPaginator;
  @ViewChild(MatSort) sort?: MatSort;

  orderPriorities: PriorityInterface[];

  constructor(
    private _prevMaintService: PreventiveMaintenanceService,
    private _funcService: FunctionsService,
    private _dialog: MatDialog,
    private _sysAdminService: SystemAdminService,
  ) { 
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource();
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.orderPriorities = [];
  }

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

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

      if(priorities.error){
        this.hasError = true;
        this.errorStr = priorities.msg;
        this.isLoading = false;
      }else{
        this.orderPriorities = priorities.response.order_priorities;
        this.getWorkOrders();
      }
    }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 getWorkOrders(){
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = '';
      let idUser = localStorage.getItem('idusuario')!;
      let workOrders: PreventiveWorkOrdersActiveResponse = await lastValueFrom(this._prevMaintService.getActiveWorkOrders(idUser, 1));
      
      this.hasError = workOrders.error;
      this.errorStr = workOrders.msg;

      if(!this.hasError){
        this.dataSource = new MatTableDataSource(workOrders.response);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;
      }

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

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

  applyFilter(event: any, type: string){
    let filterValue:string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    }else{
      this.txtBuscador = event;
      filterValue = event;
    }
    this.dataSource!.filter = filterValue.trim().toLowerCase();

    if(this.dataSource?.paginator){
      this.dataSource.paginator.firstPage();
    }
  }

  getDateStr(dateTimeStr: string): string{
    let dateTimeArr = dateTimeStr.split(' ');
    if(dateTimeArr[0] == '0001-01-01'){
      return '-';
    }else{
      return this._funcService.orderDate(dateTimeStr)!;
    }
  }

  getFontColor(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "rgb(0, 0, 0)";
    
    let priority = priorityFiltered[0];
    return priority.color;
  }

  getPriorityStr(priorityStr: string): string{
    let priorityFiltered = this.orderPriorities.filter(item => item.value == priorityStr);
    if(priorityFiltered.length == 0) return "-";
    
    let priority = priorityFiltered[0];
    return priority.label;
  }

  openSimulationDialog(idOrder: number){
    this._dialog.open(SimulationDialogComponent, {
      width: '820px',
      maxWidth: '820px',
      data: {
        idOrder: idOrder,
      }
    })
  }
}
