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

const ID_MODULE = "S002V01M07GEEQ";
@Component({
    selector: 'app-subfamilies-management',
    templateUrl: './subfamilies-management.component.html',
    styleUrl: './subfamilies-management.component.css',
    standalone: false
})
export class SubfamiliesManagementComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  familyCode: string;
  familyName: string;

  public btnSmall: boolean = false;
  public txtBuscador:string;

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

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

  subfamilyConsultEnabled: boolean;
  subfamilyRegisterEnabled: boolean;

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

    this.subfamilyConsultEnabled = true;
    this.subfamilyRegisterEnabled = true;
  }

  ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe(res => {
      let familyCode = res['family'];
      if(familyCode == null || familyCode == undefined || familyCode == ''){
        this._resourcesService.openSnackBar('No se envió información de la familia.');
        this.goBack(1);
      }else{
        this.init(familyCode);
      }
    });

    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 subfamilyConsultEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P03COSU');
                if(subfamilyConsultEnabled.length > 0){
                  this.subfamilyConsultEnabled = subfamilyConsultEnabled[0].access > 0;
                }
      
                let subfamilyRegisterEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P04RESU');
                if(subfamilyConsultEnabled.length > 0){
                  this.subfamilyRegisterEnabled = subfamilyRegisterEnabled[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));
  }

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

  async init(familyInfoEnc: string){
    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 subfamilyConsultEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P03COSU');
          if(subfamilyConsultEnabled.length > 0){
            this.subfamilyConsultEnabled = subfamilyConsultEnabled[0].access > 0;
          }

          let subfamilyRegisterEnabled = funPerm[0].children.filter(item => item.id == 'S002V01P04RESU');
          if(subfamilyConsultEnabled.length > 0){
            this.subfamilyRegisterEnabled = subfamilyRegisterEnabled[0].access > 0;
          }
        }
      }
    }

    let familyInfoDec = await this._encService.decrypt(familyInfoEnc);
    let familyInfoArr = familyInfoDec.split('|');

    if(familyInfoArr.length < 2){
      this._resourcesService.openSnackBar('La información enviada tiene un formato inválido.');
      this.goBack(1);
    }

    this.familyCode = await this._encService.encrypt(familyInfoArr[0]);
    this.familyName = familyInfoArr[1];

    this.getSubfamilies();
  }

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

      let idUser = localStorage.getItem('idusuario')!;
      let subfamilies: SubfamiliesListResponse = await lastValueFrom(this._equipmentManagementService.subfamilyConsult(this.familyCode, idUser, 1));

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

      if(!this.hasError){
        let subfamiliesArr: SubfamiliesListItem[] = [];
        for(const subfamily of subfamilies.response){
          let subfamilyCodeDec = await this._encService.decrypt(subfamily.CODIGOSUBFAMILIA);
          
          subfamily.CODIGOSUBFAMILIA = subfamilyCodeDec;
          subfamily.FECREG = this._functionsService.orderDate(subfamily.FECREG)!;

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

          subfamiliesArr.push(subfamily);
        }

        this.dataSource = new MatTableDataSource(subfamiliesArr);
        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 (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;
  }

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

  async openFamilyForm(action: string, subfamily: SubfamiliesListItem | null = null){
    let subfamilyObj: SubfamiliesListItem | null = null;
    if(subfamily != null){
      let subfamilyCodeEnc = await this._encService.encrypt(subfamily.CODIGOSUBFAMILIA);
      subfamilyObj = {
        CODIGOFAMILIA: subfamily.CODIGOFAMILIA,
        CODIGOSUBFAMILIA: subfamilyCodeEnc,
        NOMBRESUBFAMILIA: subfamily.NOMBRESUBFAMILIA,
        ICONO: subfamily.ICONO,
        ICONO_PERSONALIZADO: subfamily.ICONO_PERSONALIZADO,
        ARCHIVO_ICONO: subfamily.ARCHIVO_ICONO,
        ESTADO: subfamily.ESTADO,
        USRREG: subfamily.USRREG,
        FECREG: subfamily.FECREG,
        USRMOD: subfamily.USRMOD,
        FECMOD: subfamily.FECMOD,
        TIENE_HIJOS: subfamily.TIENE_HIJOS,
      };
    }

    let dialogRef = this._dialog.open(NewSubfamilyComponent, {
      width: '480px',
      maxWidth: '480px',
      data: {
        family: this.familyCode,
        action: action,
        subfamily: subfamilyObj,
      }
    });

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

  async saveSubfamily(dataEnc: string, action: string){
    try{
      let dataDec = await this._encService.decrypt(dataEnc);
      let dataObj = JSON.parse(dataDec);

      let familyCodeEnc = await this._encService.encrypt(dataObj.family);
      let subfamilyCodeEnc = 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('subfamily_code', subfamilyCodeEnc);
      formData.append('subfamily_name', dataObj.name);
      formData.append('subfamily_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.subfamilyRegister(formData));
        this._resourcesService.openSnackBar('La subfamilia se registró correctamente.');
      }else{
        await lastValueFrom(this._equipmentManagementService.subfamilyUpdate(formData));
        this._resourcesService.openSnackBar('La subfamilia se actualizó correctamente.');
      }

      this.getSubfamilies();
    }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);
      }
    }
  }
  
  alertDelete(subfamilyCode: string){
    let subfamilyFilt = this.dataSource!.data.filter(item => item.CODIGOSUBFAMILIA == subfamilyCode);
    if(subfamilyFilt.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 subfamilia ${subfamilyFilt[0].NOMBRESUBFAMILIA}?`,
          description2: 'Esta acción no se puede deshacer.'
        }
      });

      dialogRef.afterClosed().subscribe(res => {
        if(res == true){
          this.deleteSubfamily(subfamilyCode);
        }
      });
    }
  }

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

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

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

      this.getSubfamilies();
    }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);
      }
    }
  }
}
