import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { DispatchData, RequestDeleteDispatch, ResponseDataDispatch } from '../../../../interfaces/acquisition-management/dispatch.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService, ResponseData } from '../../../../services/resources.service';
import { DispatchService } from '../../../../services/acquisition-management/dispatch.service';
import { EncService } from '../../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
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 { HttpErrorResponse } from '@angular/common/http';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { FunctionsService } from '../../../../services/functions.service';

const ID_MODULE = "S002V01M05GEAD";
@Component({
    selector: 'app-dispatch-management',
    templateUrl: './dispatch-management.component.html',
    styleUrl: './dispatch-management.component.css',
    standalone: false
})
export class DispatchManagementComponent implements AfterViewInit, OnInit {
  public displayedColumns: Array<string>;
  public dataSource: MatTableDataSource<DispatchData>;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  public isLoading: boolean;
  public isLoadingForm: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _dispatchService: DispatchService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _router: Router,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.displayedColumns = [
      'ID_DESPACHO',
      'NOMBRE_DESPACHO',
      'DIRECCION',
      'FECHA_MODIFICA',
      'USUARIO_MODIFICA',
      'ESTADO',
      'ACCIONES',
    ];
    this.dataSource = new MatTableDataSource();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

  async ngOnInit() {
    this.isLoading = true;
    this.isLoadingForm = true;
    await this.refreshPermissions();
    await this.getDistpach();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

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

  private async refreshPermissions() {
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      let idUser = localStorage.getItem('idusuario')!;
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesSevice.getUser(idUser, idUser, 1));
      let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);
      if(currentProfile != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }
      let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        let profile = localStorage.getItem('perfil')!;
        await lastValueFrom(this._usersProfilesSevice.getProfile( profile, idUser, 1 )).then(
          (responseData: ProfileInterface) => {
            if (!responseData.error) {
              let modPerm = responseData.response.PERMISOS.permissions.filter(item => item.id == 'S002V01M05GEAD')[0];
              let funPerm = modPerm.children.filter(item => item.id == 'S002V03S03DESP')[0];
              let panPerm = funPerm.children.filter(item => item.id == "S002V01F05MDDE")[0];
              if (panPerm.access === 0) {
                this._router.navigate(['/sam/home']);
              }
            } else {
              this.resourcesService.openSnackBar(`${responseData.msg}`);
            }
          }, async (httpErrorResponse: HttpErrorResponse) => {
            let response = this.resourcesService.checkErrors(httpErrorResponse)
            if (response !== null && response.reload) {
              await this.refreshPermissions();
            }
          }
        );
      }
    });

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

  public async getDistpach() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._dispatchService.getDistpach(user, line)).then(
      (responseData: ResponseDataDispatch) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getDistpach();
        }
      }
    );
    this.isLoading = false;
  }

  // Método para abrir el formulario
  public async openForm(typeForm: string, dispatchData?: DispatchData) {
    let strTypeRequest: string = '';
    if (typeForm === 'REG') {
      strTypeRequest = JSON.stringify({ typeForm: 'REG', idDispatch: null });
    } else {
      strTypeRequest = JSON.stringify({ typeForm: 'UPD', idDispatch: dispatchData?.ID_DESPACHO });
    }
    const encTypeRequest:string = await this._encService.encrypt(strTypeRequest);
    this._router.navigate([`/sam/GEAD/DESP/MDDE/form/${encTypeRequest}`]);
  }

  public setAddress( DESP_CALL:string, DESP_NUEX: string, DESP_NUIN: string, DESP_COPO: string, DESP_COLO: string, DESP_MUNI: string, DESP_ENTI: string ) {
    let address: string = '';
    DESP_NUIN = DESP_NUIN === null ? '': `No. Int ${DESP_NUIN}`;
    address = `${DESP_CALL} ${DESP_NUEX} ${DESP_NUIN} CP ${DESP_COPO} Col. ${DESP_COLO}, ${DESP_MUNI} ${DESP_ENTI}`;
    return address;
  }

  // Método para ejecutar una alerta
  public async alert(type: string, dataElement: any = null): Promise<void> {
    this.isLoadingForm = true;
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        icon: "warning",
        title: "Eliminar Despacho",
        description: "¿Está seguro de eliminar el despacho?"
      },
    }).afterClosed().subscribe((result) => {
      if (result && type === 'ELI') {
        this.deleteDispatch(dataElement);
      }
    });
    this.isLoadingForm = false;
  }

  private async deleteDispatch(dataElement:DispatchData) {
    this.isLoadingForm = true;
    const objRequest: RequestDeleteDispatch = {
      ID_DESPACHO: dataElement.ID_DESPACHO,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
    await lastValueFrom(this._dispatchService.deleteDispatch(objRequest)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar('¡Eliminación del Despacho Exitoso!');
          this.getDistpach();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deleteDispatch(dataElement);
        }
      }
    );
    this.isLoadingForm = false;
  }
}
