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';
import { EmployeesListItem, EmployeesListResponse } from 'src/app/interfaces/personal-managment/employee.interface';
import { EmployeeDetailsDialogComponent } from './employee-details-dialog/employee-details-dialog.component';
import { DocumentsEmployeeComponent } from './documents-employee/documents-employee.component';
import { ContractsBySubcontratists, ContractsBySubcontratistsResponse } from 'src/app/interfaces/personal-managment/subcontratists.interface';
import { ContractHistoryComponent } from '../subcontratist/contract-history/contract-history.component';
import { ContractsHistoryEmployeeComponent } from './contracts-history-employee/contracts-history-employee.component';

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

  public isLoading: boolean;
  public hasError: boolean;
  public errorStr: string;
  public isLoadingForm: boolean;
  public changeOnTab: boolean = false;

  public btnSmall: boolean;
  public cardSmall: boolean;

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

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

  @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.screenMode = 'employees';
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    
    this.isLoadingForm = false;
    this.btnSmall = false;
    this.cardSmall = false;

    this.txtBuscadorEmployees = '';
    this.displayedColumnsEmployees = [
      'NAME',
      'CONTRACT_TYPE',
      'SPECIALITY',
      'WORKTEAMS',
      '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 {
    let routeStr = this._router.url;
    let routeArr = routeStr.split('/').reverse();

    if(routeArr[0] == 'GEPE'){
      this.screenMode = 'employees';
      this.getEmployees();
    }else{
      this.screenMode = 'contracts';
      this.getContractsByEmployees();
    }
    
    this.onResize();
  }

  public tabChange(tab: any) {
    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.encrypt("0");
      this._router.navigate(['sam/GPRS/GEPE/GEPE/employee/form/' + id + '/2']);
    } else if (typeForm === 'UPD') {
      this._router.navigate(['sam/GPRS/GEPE/GEPE/employee/form/' + element!.ID_EMPLOYEE + '/1']);
    } else if (typeForm === 'HIS') {
      this._dialog.open(ContractsHistoryEmployeeComponent, {
        width: '640px',
        data: element
      });
      /*const id = await this._encService.encrypt(element.ID_EMPLOYEE);
      this._router.navigate(['sam/GPRS/GEPE/GEPE/employee/contracts-history/' + id]);*/
    } else if (typeForm === 'TAH') {      
      this._router.navigate([`/sam/GPRS/GEPE/GEPE/tasa-horaria/${element.ID_EMPLOYEE}`]);
    } else if (typeForm === 'CRA') {      
      this._router.navigate([`/sam/GPRS/GEPE/GEPE/cronograma-actividades/${element.ID_EMPLOYEE}`]);
    } else if (typeForm === 'DOC') {
      let employeeNameEnc = await this._encService.encrypt(element!.NAME);
      this._dialog.open(DocumentsEmployeeComponent, {
        width: '580px',
        data: {
          idEmployee: element!.ID_EMPLOYEE,
          employeeName: employeeNameEnc
        }
      });
    } else if (typeForm === 'ORD') {
      let nameEnc = await this._encService.encrypt(element.NAME);
      this._router.navigate([`sam/GPRS/GEPE/GEPE/employee/orders/${element.ID_EMPLOYEE}/${nameEnc}`]);
    } else if (typeForm === 'DET') {
      let employeeNameEnc = await this._encService.encrypt(element!.NAME);
      this._dialog.open(EmployeeDetailsDialogComponent, {
        width: '640px',
        data: {
          idEmployee: element!.ID_EMPLOYEE,
          employeeName: employeeNameEnc
        }
      });
    } 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}`);
        }
      });
    } else if (typeForm === 'ACT') {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Activación de Empleado',
          description: '¿Está seguro que desea activar al empleado?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          //this.activateEmployee(element!.ID_EMPLOYEE);
        }
      });
    }
  }

  public async getEmployees() {
    try{
      this.isLoading = true;
      this.hasError = false;
      this.errorStr = "";

      let idUser = localStorage.getItem('idusuario')!;
      let employees: EmployeesListResponse = await lastValueFrom(this._employeeService.getConsultOfEmployees(idUser));
      
      this.hasError = employees.error;
      this.errorStr = employees.msg;

      if(!this.hasError){
        let employeesArr: EmployeesListItem[] = [];
        for(const employee of employees.response){
          let idEnc = await this._encService.encrypt(`${employee.ID_EMPLOYEE}`);

          employee.NAME = `${employee.NAME} (${employee.ID_EMPLOYEE})`;
          employee.ID_EMPLOYEE = idEnc;

          employeesArr.push(employee);
        }

        this.dataSourceEmployees = new MatTableDataSource(employeesArr);
        this.dataSourceEmployees.paginator = this.paginator!;
        this.dataSourceEmployees.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;
    }
  }

  private async deleteEmployee(employeeId: string) {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();
    
      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_employee', employeeId);

      await lastValueFrom(this._employeeService.updateToInactiveStatus(formData));

      this.resourcesService.openSnackBar('El usuario se eliminó correctamente.');
      this.getEmployees();
    }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);
      }
    }
  }

  public async getContractsByEmployees() {
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let contracts: ContractsBySubcontratistsResponse = await lastValueFrom(this._employeeService.getContractsOfEveryEmployee(idUser));
      
      this.hasError = contracts.error;
      this.errorStr = contracts.msg;

      if(!this.hasError){
        this.dataSourceContracts = new MatTableDataSource(contracts.response);
        this.dataSourceContracts.paginator = this.paginator2;
        this.dataSourceContracts.sort = this.sort2;
      }

      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;
    }
    /*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;
    }
    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;
    }
    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 <= 1825;
    this.cardSmall = window.innerWidth >= 722;
  }

}
