import { HttpErrorResponse } from '@angular/common/http';
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 { MatTabGroup } from '@angular/material/tabs';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
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';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public changeOnTab: boolean = false;

  public btnSmall: boolean;

  // Para Empleados
  public txtBuscadorEmployees: string;
  public displayedColumnsEmployees: Array<string>;
  public dataSourceEmployees: MatTableDataSource<any>;

  // Para Contratos
  public txtBuscadorContracts: string;
  public displayedColumnsContracts: Array<string>;
  public dataSourceContracts: MatTableDataSource<any>;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  @ViewChild('MatPaginator2') paginator2!: MatPaginator;
  @ViewChild('MatSort2') sort2!: MatSort;
  @ViewChild('TabGroup') tabGroup!: MatTabGroup;

  constructor(
    private _employeeService: EmployeeService,
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _router: Router,
    private _encService: EncService
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.btnSmall = false;

    this.txtBuscadorEmployees = '';
    this.displayedColumnsEmployees = [
      'NAME',
      'CONTRACT_TYPE',
      'SPECIALITY',
      'WORKTEAMS',
      'REGISTER_DATE',
      'REGISTERED_BY_USER',
      'UPDATE_DATE',
      'UPDATED_BY_USER',
      'STATUS',
      'ACCIONES']
    this.dataSourceEmployees = new MatTableDataSource<any>();

    this.txtBuscadorContracts = '';
    this.displayedColumnsContracts = [
      'NAME',
      'CONTRACTS_COUNT',
      'ACCIONES']
    this.dataSourceContracts = new MatTableDataSource<any>();
  }

  ngAfterViewInit() {
    this.dataSourceEmployees.paginator = this.paginator;
    this.dataSourceEmployees.sort = this.sort;
    this.dataSourceContracts.paginator = this.paginator2;
    this.dataSourceContracts.sort = this.sort2;
  }

  ngOnInit(): void {
    this.getEmployees();
    this.getContractsByEmployees();
  }

  public tabChange(tab: any) {
    console.log("hola " + tab.index);
    if (tab.index == 0) {
      this.changeOnTab = false;
    } else {
      this.changeOnTab = true;
    }
  }

  public async openDialog(typeForm: string, element?: any) {
    if (typeForm === 'REG') {
      const id = await this._encService.encriptar("0");
      this._router.navigate(['sam/GPRS/employee/form/' + id + '/1']);
    } else if (typeForm === 'UPD') {
      const id = await this._encService.encriptar(element.ID_EMPLOYEE);
      this._router.navigate(['sam/GPRS/employee/form/' + id + '/1']);
    } else if (typeForm === 'HIS') {
      const id = await this._encService.encriptar(element.ID_EMPLOYEE);
      this._router.navigate(['sam/GPRS/employee/contracts-history/' + id]);
    } else if (typeForm === 'TAH') {
      const id = await this._encService.encriptar(element.ID_EMPLOYEE);
      this.resourcesService.openSnackBar('Función para la vista de Tasa horaria');
      // this._router.navigate(['sam/GPRS/employee/contracts/' + id]);
    } else if (typeForm === 'DOC') {
      const id = await this._encService.encriptar(element.ID_EMPLOYEE);
      this._router.navigate(['sam/GPRS/employee/documents/' + id]);
    } else if (typeForm === 'ORD') {
      const id = await this._encService.encriptar(element.ID_EMPLOYEE);
      this._router.navigate(['sam/GPRS/employee/orders/' + id]);
    } else if (typeForm === 'DET') {
      const id = await this._encService.encriptar(element.ID_EMPLOYEE);
      this._router.navigate(['sam/GPRS/employee/form/' + id + '/0']);
    } else if (typeForm === 'DEL') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Eliminación de Empleado',
          description: '¿Está seguro que desea eliminar al empleado?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteEmployee(element!.ID_EMPLOYEE);
        }
      });
    }
  }

  public async getEmployees() {
    this.isLoading = true;
    await lastValueFrom(this._employeeService.getConsultOfEmployees()).then(
      (responseData: any) => {
        this.dataSourceEmployees.data = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  private async deleteEmployee(employeeId: string) {
    await lastValueFrom(this._employeeService.updateToInactiveStatus({
      EMPLOYEE_ID: employeeId,
      LINE_NUMBER: '01',
      SAVED_BY_USER: this.resourcesService.getUser()
    })).then(
      (responseData: any) => {
        this.getEmployees();
        this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  public async getContractsByEmployees() {
    this.isLoading = true;
    await lastValueFrom(this._employeeService.getContractsOfEveryEmployee()).then(
      (responseData: any) => {
        this.dataSourceContracts.data = responseData.response;
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  // Método de filtrado de datos
  public applyFilterEmployees(event: any, type: string): void {
    let filterValue: string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    } else {
      this.txtBuscadorEmployees = event;
      filterValue = event;
    }
    console.log(filterValue);
    this.dataSourceEmployees.filter = filterValue.trim().toLowerCase();
    if (this.dataSourceEmployees.paginator) {
      this.dataSourceEmployees.paginator.firstPage();
    }
  }

  // Método de filtrado de datos
  public applyFilterContracts(event: any, type: string): void {
    let filterValue: string;
    if (type == 'INP') {
      filterValue = (event.target as HTMLInputElement).value;
    } else {
      this.txtBuscadorContracts = event;
      filterValue = event;
    }
    console.log(filterValue);
    this.dataSourceContracts.filter = filterValue.trim().toLowerCase();
    if (this.dataSourceContracts.paginator) {
      this.dataSourceContracts.paginator.firstPage();
    }
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize(): void {
    this.btnSmall = window.innerWidth <= 1405;
  }

}
