import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { OrderDetailsComponent } from 'src/app/components/preventive-maintenance/work-orders/order-details/order-details.component';
import { Interventions, ResponseDataEmployeeInterventions } from 'src/app/interfaces/personal-managment/employee.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { EmployeeService } from 'src/app/services/personal-management/employee.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-orders-employee',
  templateUrl: './orders-employee.component.html',
  styleUrls: ['./orders-employee.component.css']
})
export class OrdersEmployeeComponent implements OnInit {
  public isLoading: boolean;
  public hasError: boolean;
  public errorStr: string;

  public txtBuscador: string;
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<Interventions>;
  public idEmployee: string;
  public employeeName: string;

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

  constructor(
    private _employeeService: EmployeeService,
    public _resourcesService: ResourcesService,
    private _activatedRoute: ActivatedRoute,
    private _encService: EncService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";

    this.idEmployee = "";
    this.employeeName = "";
    this.txtBuscador = '';
    this.displayedColumns = [
      'IDORDEN',
      'TIPOORDEN',
      'DESCRIPCION',
      'ACCIONES'
    ];
    this.dataSource = new MatTableDataSource();
  }

  ngOnInit(): void {
    this.idEmployee = this._activatedRoute.snapshot.paramMap.get('id')!;
    this.init();
  }

  async init(){
    let nameEnc = this._activatedRoute.snapshot.paramMap.get('name')!;
    this.employeeName = await this._encService.decrypt(nameEnc);

    this.getData();
  }

  public openDetails(element: Interventions){
    let idOrderArr = element.IDORDEN.split('#').reverse();
    let idOrderStr = idOrderArr[0];
    
    this._dialog.open(OrderDetailsComponent, {
      width: '820px',
      data: {
        idOrder: idOrderStr,
      }
    });
  }

  public async getData() {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let orders: ResponseDataEmployeeInterventions = await lastValueFrom(this._employeeService.getInterventionsByEmployee(
        this.idEmployee,
        idUser
      ));

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

      if(!this.hasError){
        let interventions: Interventions[] = [];
        for(const order of orders.response){
          let idDec = await this._encService.decrypt(order.IDORDEN);

          order.IDORDEN = `Orden #${idDec}`;
          interventions.push(order);
        }
        
        this.dataSource = new MatTableDataSource(interventions);
        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;
    }
  }

  // Método de filtrado de datos
  public applyFilter(event: any, type: string): void {
    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();
    }
  }

}
