import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { FamiliesListItem, FamiliesListResponse } from '../../../interfaces/equipment-management.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { ResourcesService } from '../../../services/resources.service';
import { EquipmentManagementService } from '../../../services/equipment-management.service';
import { FunctionsService } from '../../../services/functions.service';
import { Router } from '@angular/router';
import { SocketService } from '../../../services/socket.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { UserConsultResponse } from '../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';
import { Permissions } from '../../../interfaces/permissions.interface';
import { NewFamilyComponent } from './new-family/new-family.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

const ID_MODULE = "S002V01M07GEEQ";
@Component({
    selector: 'app-families-management',
    templateUrl: './families-management.component.html',
    styleUrl: './families-management.component.css',
    standalone: false
})
export class FamiliesManagementComponent implements OnInit {
  public btnSmall: boolean = false;
  public txtBuscador:string;

  dataSource?: MatTableDataSource<FamiliesListItem>;
  displayedColumns = ['CODIGO', 'NOMBRE', 'COLOR', 'SUBFAMILIAS', 'ESTADO', 'USRMOD', 'FECMOD', 'ACCIONES'];

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

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

  familyConsultEnabled: boolean;
  familyRegisterEnabled: boolean;

  constructor(
    private _dialog: MatDialog,
    private _encService: EncService,
    private _resourcesService: ResourcesService,
    private _equipmentManagementService: EquipmentManagementService,
    private _functionsService: FunctionsService,
    private _router: Router,
    private _socketService: SocketService,
    private _usersProfilesService: UsersProfilesService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';
    this.dataSource = new MatTableDataSource();
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";

    this.familyConsultEnabled = true;
    this.familyRegisterEnabled = true;
  }

  ngOnInit(): void {
    this.getData();

    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      try{
        let idUser = localStorage.getItem('idusuario')!;
        let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
        
        if(usrInfo.error){
          this._resourcesService.openSnackBar('Ocurrió un error inesperado (1).');
        }else{
          let idProfDec = await this._encService.decrypt(usrInfo.response.PERFIL);
          let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

          if(idProfDec != currentProfile){
            this._router.navigate(['/sam/home']);
            return;
          }
          
          let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
          if(profileUpdated == currentProfile){
            let profile = localStorage.getItem('perfil')!;
            let profInfo: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(
              profile,
              idUser,
              1
            ));

            let permArr = await this._functionsService.processPermissions(profInfo.response.PERMISOS.permissions);
            let modPerm = permArr.filter(item => item.id == 'S002V01M07GEEQ');
            if(modPerm.length > 0){
              let funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F02DFSU');
              if(funPerm.length > 0){
                let familyConsultEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01COFA');
                if(familyConsultEnabled.length > 0){
                  this.familyConsultEnabled = familyConsultEnabled[0].access > 0;
                }
  
                let familyRegisterEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02REFA');
                if(familyRegisterEnabled.length > 0){
                  this.familyRegisterEnabled = familyRegisterEnabled[0].access > 0;
                }
              }
            }
          }
        }
      }catch(error: any){
        if(error.error == undefined){
          this._resourcesService.openSnackBar('Ocurrió un error inesperado (2).');
        }else if(error.error.msg == undefined){
          this._resourcesService.openSnackBar('Ocurrió un error inesperado (3).');
        }else{
          this._resourcesService.openSnackBar(error.error.msg);
        }
      }
    });

    this._socketService.refreshModules().subscribe(async () => this._functionsService.consultModuleStatus(ID_MODULE));
  } 

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

      let idUser = localStorage.getItem('idusuario')!;
      let families: FamiliesListResponse = await lastValueFrom(this._equipmentManagementService.familyConsult(idUser, 1));

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

      if(!this.hasError){
        let familiesArr: FamiliesListItem[] = [];
        for(const family of families.response){
          let idEnc = await this._encService.decrypt(family.CODIGOFAMILIA);

          family.CODIGOFAMILIA = idEnc;
          family.FECREG = this._functionsService.orderDate(family.FECREG)!;

          if(family.FECMOD != null){
            family.FECMOD = this._functionsService.orderDate(family.FECMOD)!;
          }

          familiesArr.push(family);
        }

        this.dataSource = new MatTableDataSource(familiesArr);
        this.dataSource.paginator = this.paginator!;
        this.dataSource.sort = this.sort!;

        let permissionsEnc = localStorage.getItem('permisos');
        let permissionsDec = '';
        if(permissionsEnc == '' || permissionsEnc == undefined || permissionsEnc == null){
          permissionsDec = '[]';
        }else{
          permissionsDec = await this._encService.decrypt(permissionsEnc!);
        }
  
        let permissionsArr: Permissions = JSON.parse(permissionsDec);
        if(permissionsArr.permissions != undefined){
          let modPerm = permissionsArr.permissions.filter(item => item.id == 'S002V01M07GEEQ');
          if(modPerm.length > 0){
            let funPerm = modPerm[0].children.filter(item => item.id == 'S002V01F02DFSU');
            if(funPerm.length > 0){
              let familyConsultEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P01COFA');
              if(familyConsultEnabled.length > 0){
                this.familyConsultEnabled = familyConsultEnabled[0].access > 0;
              }

              let familyRegisterEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P02REFA');
              if(familyRegisterEnabled.length > 0){
                this.familyRegisterEnabled = familyRegisterEnabled[0].access > 0;
              }
            }
          }
        }
      }
      
      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado (4).';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado (5).';
      }else{
        this.errorStr = error.error.msg;
      }

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

  public onResize():void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  applyFilter(event: any, type: string){
    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();
    }
  }

  openFamilyForm(action: string, family: FamiliesListItem | null = null){
    let dialogRef = this._dialog.open(NewFamilyComponent, {
      width: '480px',
      maxWidth: '480px',
      data: {
        action: action,
        family: family
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.saveFamily(res, action);
      }
    });
  }

  async saveFamily(dataEnc: string, action: string){
    try{
      let dataDec = await this._encService.decrypt(dataEnc);
      let dataObj = JSON.parse(dataDec);
      
      let familyCodeEnc = await this._encService.encrypt(dataObj.code);
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('family_code', familyCodeEnc);
      formData.append('family_name', dataObj.name);
      formData.append('family_color', dataObj.color);
      formData.append('family_icon', dataObj.icon);
      formData.append('custom_icon', dataObj.customIcon);

      if(dataObj.customIcon == 'S'){
        formData.append('icon_file', dataObj.iconFile);
      }

      if(action == 'new'){
        await lastValueFrom(this._equipmentManagementService.familyRegister(formData));
        this._resourcesService.openSnackBar('La familia se registró correctamente.');
      }else{
        await lastValueFrom(this._equipmentManagementService.familyUpdate(formData));
        this._resourcesService.openSnackBar('La familia se actualizó correctamente.');
      }

      this.getData();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (6).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (7).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async manageSubfamilies(id: string, name: string){
    let codeEnc = await this._encService.encrypt(`${id}|${name}`);
    this._router.navigate(['sam/GEEQ/DFSU/subfamilias'], {
      queryParams: {
        family: codeEnc,
      }
    });
  }

  alertDelete(familyCode: string){
    let familyFilt = this.dataSource!.data.filter(item => item.CODIGOFAMILIA == familyCode);
    if(familyFilt.length > 0){
      let dialogRef = this._dialog.open(AlertComponent, {
        width: '420px',
        minWidth: '420px',
        disableClose: true,
        data:{
          title: '¡Cuidado!',
          icon: 'warning',
          description: `¿Está seguro de continuar con la eliminación de la familia ${familyFilt[0].NOMBREFAMILIA}?`,
          description2: 'Esta acción no se puede deshacer.'
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res == true){
          this.deleteFamily(familyCode);
        }
      });
    }
  }

  private async deleteFamily(familyCode: string){
    try{
      let codeEnc = await this._encService.encrypt(familyCode);
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('family_code', codeEnc);

      await lastValueFrom(this._equipmentManagementService.familyDelete(formData));
      this._resourcesService.openSnackBar('La familia se eliminó correctamente.');

      this.getData();
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (8).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (9).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
