import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute } from '@angular/router';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { NewSubfamilyComponent } from './new-subfamily/new-subfamily.component';
import { lastValueFrom } from 'rxjs';
import { EquipmentManagementService } from 'src/app/services/equipment-management.service';
import { SubfamiliesListItem, SubfamiliesListResponse } from 'src/app/interfaces/equipment-management.interface';
import { FunctionsService } from 'src/app/services/functions.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';

@Component({
  selector: 'app-subfamilies-management',
  templateUrl: './subfamilies-management.component.html',
  styleUrls: ['./subfamilies-management.component.css']
})
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;

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _resourcesService: ResourcesService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _equipmentManagementService: EquipmentManagementService,
    private _functionsService: FunctionsService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
    this.familyCode = "";
    this.familyName = "";
    this.txtBuscador = '';
  }

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

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

  async init(familyInfoEnc: string){
    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.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

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

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

  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,
        ESTADO: subfamily.ESTADO,
        USRREG: subfamily.USRREG,
        FECREG: subfamily.FECREG,
        USRMOD: subfamily.USRMOD,
        FECMOD: subfamily.FECMOD
      };
    }

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

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

  async deleteSubfamily(id: string){
    try{
      let codeEnc = await this._encService.encrypt(id);
      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.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }

  async saveSubfamily(dataEnc: string, action: string){
    try{
      let dataDec = await this._encService.decrypt(dataEnc);
      let dataArr = dataDec.split('|');

      if(dataArr.length < 3){
        this._resourcesService.openSnackBar('La información de la subfamilia tiene un formato inválido.');
        return;
      }

      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('family_code', dataArr[0]);
      formData.append('subfamily_code', dataArr[1]);
      formData.append('subfamily_name', dataArr[2]);

      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.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
