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

@Component({
    selector: 'app-orders-employee',
    templateUrl: './orders-employee.component.html',
    styleUrl: './orders-employee.component.css',
    standalone: false
})
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 async getData() {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      const LINE = this._resourcesService.getLineNumber();
      let orders: ResponseDataEmployeeInterventions = await lastValueFrom(this._employeeService.getInterventionsByEmployee(
        this.idEmployee,
        idUser,
        LINE
      ));

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

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