import { Component, OnInit, ViewChild } from '@angular/core';
import { PriorityInterface } from '../../system-admin/system-params/system-params.component';
import { MatTableDataSource } from '@angular/material/table';
import { BlockRegistersListItem, BlockRegistersListResponse, SecurityManagementListItem, SecurityManagementListResponse } from '../../../interfaces/corrective-maintenance.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { CorrectiveMaintenanceService } from '../../../services/corrective-maintenance.service';
import { ResourcesService } from '../../../services/resources.service';
import { EncService } from '../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { FunctionsService } from '../../../services/functions.service';
import { lastValueFrom } from 'rxjs';
import { SecurityManagementFormComponent } from './security-management-form/security-management-form.component';
import { SecurityManagementDialogComponent } from './security-management-dialog/security-management-dialog.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { BlockDialogComponent } from './block-dialog/block-dialog.component';

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

  isLoadingSecMan: boolean;
  hasErrorSecMan: boolean;
  errorStrSecMan: string;

  isLoadingBlock: boolean;
  hasErrorBlock: boolean;
  errorStrBlock: string;

  displayedScreen: string;
  priorities: PriorityInterface[];

  dataSource: MatTableDataSource<SecurityManagementListItem>;
  displayedColumns = ['ID', 'GERENTE', 'ORDENES', 'ESTADO', 'ACCIONES'];

  dataSourceBlock: MatTableDataSource<BlockRegistersListItem>;
  displayedColumnsBlock = ['ID', 'BLOQUEADO', 'TIPOBLOQUEO', 'ESTADO', 'USRREG', 'FECREG', 'ACCIONES'];

  @ViewChild(MatPaginator) paginator?: MatPaginator;
  @ViewChild(MatSort) sort?: MatSort;
  @ViewChild('MatPaginator2') paginator2!: MatPaginator;
  @ViewChild('MatSort2') sort2!: MatSort;

  constructor(
    private _correctiveMaintenanceService: CorrectiveMaintenanceService,
    private _resourcesService: ResourcesService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _functionsService: FunctionsService,
  ) {
    this.btnSmall = window.innerWidth <= 1405;
    this.txtBuscador = '';

    this.isLoadingSecMan = true;
    this.hasErrorSecMan = false;
    this.errorStrSecMan = '';

    this.isLoadingBlock = true;
    this.hasErrorBlock = false;
    this.errorStrBlock = '';

    this.displayedScreen = "GESSEG";
    this.priorities = [];

    this.dataSource = new MatTableDataSource();
    this.dataSourceBlock = new MatTableDataSource();
  }

  ngOnInit(): void {
    if(this.displayedScreen == 'GESSEG'){
      this.getSecurityManagements();
    }else{
      this.getBlockRegisters();
    }
  }

  async getSecurityManagements(){
    try{
      this.isLoadingSecMan = true;
      this.hasErrorSecMan = false;
      this.errorStrSecMan = '';

      let idUser = localStorage.getItem('idusuario')!;
      let securityManagements: SecurityManagementListResponse = await lastValueFrom(this._correctiveMaintenanceService.getSecurityManagements(idUser, 1));

      this.hasErrorSecMan = securityManagements.error;
      this.errorStrSecMan = securityManagements.msg;

      if(!this.hasErrorSecMan){
        let securityManagementsArr: SecurityManagementListItem[] = [];
        for(const management of securityManagements.response){
          let idDec = await this._encService.decrypt(management.ID_GERENCIA_SEGURIDAD);
          management.ID_GERENCIA_SEGURIDAD = idDec;

          securityManagementsArr.push(management);
        }

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

      this.isLoadingSecMan = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStrSecMan = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStrSecMan = 'Ocurrió un error inesperado.';
      }else{
        this.errorStrSecMan = error.error.msg;
      }

      this.hasErrorSecMan = true;
      this.isLoadingSecMan = false;
    }
  }

  async getBlockRegisters(){
    try{
      this.isLoadingBlock = true;
      this.hasErrorBlock = false;
      this.errorStrBlock = '';

      let idUser = localStorage.getItem('idusuario')!;
      let blockRegisters: BlockRegistersListResponse = await lastValueFrom(this._correctiveMaintenanceService.getBlockRegisters(idUser, 1));

      this.hasErrorBlock = blockRegisters.error;
      this.errorStrBlock = blockRegisters.msg;

      if(!this.hasErrorBlock){
        let blockRegistersArr: BlockRegistersListItem[] = [];
        for(const register of blockRegisters.response){
          register.ID_BLOQUEO = await this._encService.decrypt(register.ID_BLOQUEO);
          register.FECREG = this._functionsService.orderDate(register.FECREG);

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

          blockRegistersArr.push(register);
        }

        this.dataSourceBlock = new MatTableDataSource(blockRegistersArr);
        this.dataSourceBlock.sort = this.sort2;
        this.dataSourceBlock.paginator = this.paginator2;
      }

      this.isLoadingBlock = false;
    }catch(error: any){
      console.log(error);
      if(error.error == undefined){
        this.errorStrBlock = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStrBlock = 'Ocurrió un error inesperado.';
      }else{
        this.errorStrBlock = error.error.msg;
      }

      this.hasErrorBlock = true;
      this.isLoadingBlock = false;
    }
  }

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

  screenChange(event: any){
    if(event != undefined){
      this.displayedScreen = event;
      if(this.displayedScreen == 'GESSEG'){
        this.getSecurityManagements();
      }else{
        this.getBlockRegisters();
      }
    }
  }

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

  openSecurityManagementForm(type: string, idSecManage: string | null){
    let dialogRef = this._dialog.open(SecurityManagementFormComponent, {
      width: '720px',
      maxWidth: '720px',
      disableClose: true,
      data: {
        type: type,
        idSecManage: idSecManage,
      }
    });

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

  private async saveSecurityManagement(dataEnc: string, type: string, idSecManage: string | null){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let dataDec = await this._encService.decrypt(dataEnc);
      let dataObj = JSON.parse(dataDec);
      let formData = new FormData();

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

      let lada1Arr = dataObj.phoneLada1Control.split('-');
      formData.append('lada1', lada1Arr[0]);
      formData.append('phone1', dataObj.phone1Control);

      if(dataObj.phone1ExtensionControl != null && dataObj.phone1ExtensionControl != undefined && dataObj.phone1ExtensionControl != ''){
        formData.append('ext1', dataObj.phone1ExtensionControl);
      }

      if(dataObj.phoneLada2Control != null && dataObj.phoneLada2Control != undefined && dataObj.phoneLada2Control != ''){
        let lada2Arr = dataObj.phoneLada2Control.split('-');
        formData.append('lada2', lada2Arr[0]);
        formData.append('phone2', dataObj.phone2Control);

        if(dataObj.phone2ExtensionControl != null && dataObj.phone2ExtensionControl != undefined && dataObj.phone2ExtensionControl != ''){
          formData.append('ext2', dataObj.phone2ExtensionControl);
        }
      }

      let managerArr = dataObj.managerControl.split('(').reverse();
      let managerStr = managerArr[0].replace(')', '');
      let managerEnc = await this._encService.encrypt(managerStr);

      formData.append('email', dataObj.managementEmailControl);
      formData.append('id_manager', managerEnc);

      if(type == 'Registrar'){
        await lastValueFrom(this._correctiveMaintenanceService.registerSecurityManagement(formData));

        this._resourcesService.openSnackBar('La gerencia de seguridad se guardó correctamente.');
        this.getSecurityManagements();
      }else{
        let idSecManageEnc = await this._encService.encrypt(idSecManage!);
        formData.append('id_management', idSecManageEnc);

        await lastValueFrom(this._correctiveMaintenanceService.updateSecurityManagement(formData));

        this._resourcesService.openSnackBar('La gerencia de seguridad se actualizó correctamente.');
        this.getSecurityManagements();
      }
    }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 openSecurityManagementDetails(idSecManage: string){
    let idSecManageEnc = await this._encService.encrypt(idSecManage);
    this._dialog.open(SecurityManagementDialogComponent, {
      width: '480px',
      maxWidth: '480px',
      data: {
        idSecManage: idSecManageEnc,
      }
    });
  }

  openDeleteConfirm(idSecManage: string){
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '420px',
      maxWidth: '420px',
      disableClose: true,
      data: {
        title: 'Confirmación',
        icon: 'warning',
        description: `¿Está seguro de querer eliminar la gerencia de seguridad #${idSecManage}?`,
        description2: 'Esta acción no se puede deshacer.'
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        this.deleteSecurityManagement(idSecManage);
      }
    });
  }

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

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_management', idSecManageEnc);

      await lastValueFrom(this._correctiveMaintenanceService.deleteSecurityManagement(formData));

      this._resourcesService.openSnackBar('La gerencia se eliminó correctamente.');
      this.getSecurityManagements();
    }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);
      }
    }
  }

  openBlockDialog(){
    let dialogRef = this._dialog.open(BlockDialogComponent, {
      width: '480px',
      maxWidth: '480px',
      disableClose: true,
    });

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

  async registerBlock(data: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let dataArr = data.split('|');
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('blocked', dataArr[0]);
      formData.append('type', dataArr[1]);

      await lastValueFrom(this._correctiveMaintenanceService.registerBlock(formData));

      this._resourcesService.openSnackBar('El bloqueo se agregó correctamente.');
      this.getBlockRegisters();
    }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);
      }
    }
  }

  confirmUnblock(idBlock: string){
    let registerFilt = this.dataSourceBlock.data.filter(item => item.ID_BLOQUEO == idBlock);
    if(registerFilt.length < 1){
      this._resourcesService.openSnackBar('El registro que intenta desbloquear no existe.');
      return;
    }

    let blockName = registerFilt[0].BLOQUEADO;
    let blockType = registerFilt[0].TIPO_BLOQUEADO;
    let dialogRef = this._dialog.open(AlertComponent, {
      width: '420px',
      disableClose: true,
      data: {
        title: 'Confirmación',
        icon: 'warning',
        description: `¿Está seguro de levantar el bloqueo al ${blockType} ${blockName}?`
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res == true){
        this.unblock(idBlock);
      }
    });
  }

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

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_register', idRegisterEnc);

      await lastValueFrom(this._correctiveMaintenanceService.unblockRegister(formData));

      this._resourcesService.openSnackBar('El registro se actualizó correctamente.');
      this.getBlockRegisters();
    }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);
      }
    }
  }
}
