import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { EmployeesListItem, EmployeesListResponse } from '../../../interfaces/personal-managment/employee.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { EmployeeService } from '../../../services/personal-management/employee.service';
import { ResourcesService, ResponseData } from '../../../services/resources.service';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { EncService } from '../../../services/enc.service';
import { lastValueFrom } from 'rxjs';
import { DocumentsEmployeeComponent } from './documents-employee/documents-employee.component';
import { EmployeeDetailsDialogComponent } from './employee-details-dialog/employee-details-dialog.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { HttpErrorResponse } from '@angular/common/http';

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

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

  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<EmployeesListItem>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  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.displayedColumns = [
      'NAME',
      'CONTRACT_TYPE',
      'SPECIALITY',
      'TEAM_NAME',
      'STATUS',
      'ACCIONES'
    ];
    this.dataSource = new MatTableDataSource<EmployeesListItem>();
  }

  async ngOnInit() {
    await this.getEmployees();
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  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, 1));
      
      this.hasError = employees.error;
      this.errorStr = employees.msg;

      if(!this.hasError){
        let employeesArr: EmployeesListItem[] = [];
        
        for(const employee of employees.response){
          let idEmployeeDec = await this._encService.decrypt(employee.ID_EMPLOYEE);
          let specialtiesArr: string[] = JSON.parse(employee.SPECIALITY);
          let specialtiesStr = '';
          for(const specialty of specialtiesArr){
            let specialtyDec = await this._encService.decrypt(specialty);
            specialtiesStr += `${specialtyDec}, `;
          }

          specialtiesStr = specialtiesStr.substring(0, specialtiesStr.length - 2);

          employee.SPECIALITY = specialtiesStr;
          employee.SPECIALITY_ARR = specialtiesArr;
          if(employee.TEAM_ID != null){
            let idTeamDec = await this._encService.decrypt(employee.TEAM_ID);
            employee.TEAM_NAME = `${employee.TEAM_NAME} (${idTeamDec})`;
          }

          employee.NAME = `${employee.NAME} (${idEmployeeDec})`;
          employeesArr.push(employee);
        }

        this.dataSource = new MatTableDataSource(employeesArr);
        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 (1).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (2).';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  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 === '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',
        maxWidth: '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',
        maxWidth: '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);
        }
      });
    }
  }

  private async deleteEmployee(employeeId: string) {
    try{
      let formData = new FormData();

      const USER: string = this.resourcesService.getUser();
      formData.append('id_user', USER);
      const LINE: number = this.resourcesService.getLineNumber();
      formData.append('linea', `${LINE}`);
      formData.append('id_employee', employeeId);

      await lastValueFrom(this._employeeService.updateToInactiveStatus(formData)).then(
        async (responseData: ResponseData) => {
          if (!responseData.error) {
            this.resourcesService.openSnackBar('El usuario se eliminó correctamente.');
            await this.getEmployees();
          } else {
            this.resourcesService.openSnackBar(`${responseData.msg}`);
          }
        }, async (httpErrorResponse: HttpErrorResponse) => {
          let response = this.resourcesService.checkErrors(httpErrorResponse)
          if (response !== null && response.reload) {
            await this.deleteEmployee(employeeId);
          }
        }
      );
    }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);
      }
    }
  }
}
