import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { GetLevelAreaWarehouse, InfoArea, ResponseDataGetLevelAreaWarehouse, ResponseDataGetAreaWarehouse, TableLevelAreaWarehouse, InfoLevel } from 'src/app/interfaces/inventory-management/warehouse-management.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { WarehouseService } from 'src/app/services/inventory-management/warehouse.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { DataFormLevel, LevelFormComponent } from '../level-form/level-form.component';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { ResponseData } from 'src/app/interfaces/response-data';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';

@Component({
  selector: 'app-level-management',
  templateUrl: './level-management.component.html',
  styleUrls: ['./level-management.component.css']
})
export class LevelManagementComponent implements OnInit {

  public dataSource: MatTableDataSource<TableLevelAreaWarehouse>;
  public displayedColumns: Array<string>;
  public arrLevel: Array<GetLevelAreaWarehouse>;

  public isLoading: boolean;
  public isLoadingForm: boolean;

  public idWarehouse!: string;
  public idArea!: string;

  constructor(
    public resourcesService: ResourcesService,
    private _activatedRouter: ActivatedRoute,
    private _encService: EncService,
    private _router: Router,
    private _dialog: MatDialog,
    private _warehouseService: WarehouseService,
  ) {
    this.dataSource = new MatTableDataSource<TableLevelAreaWarehouse>();
    this.displayedColumns = ['CODIGO_NIVEL','NOMBRE_NIVEL','COMENTARIOS','USUARIO_REGISTRA','FECHA_REGISTRA', 'ESTADO', 'ACCIONES'];
    this.arrLevel = [];

    this.isLoading = false;
    this.isLoadingForm = false;
  }

  async ngOnInit() {
    this.isLoading = true;
    this.isLoadingForm = true;
    await this.getInfoLevel();
    await this.getLevelByAreaWarehouse();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

  private async getInfoLevel() {
    let infoURL = this._activatedRouter.snapshot.paramMap.get('info');
    if (infoURL !== null) {
      const decInfoUrl: string = await this._encService.decrypt(infoURL);
      const infoUrl: InfoArea = JSON.parse(decInfoUrl);
      this.idWarehouse = infoUrl.idWarehouse.toString();
      this.idArea = infoUrl.idArea.toString();
    } else {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener la información del almacen.`);
      this._router.navigate(['/sam/GIST/GEAL']);
    }
  }

  public async getLevelByAreaWarehouse() {
    this.isLoading = true;
    const encWarehouse: string = await this._encService.encrypt(this.idWarehouse);
    const encArea: string = await this._encService.encrypt(this.idArea);

    await lastValueFrom(this._warehouseService.getLevelByAreaWarehouse(encWarehouse, encArea)).then(
      (responseData: ResponseDataGetLevelAreaWarehouse) => {
        if (!responseData.error) {
          this.arrLevel = responseData.response;
          let arrLevelTemp: Array<TableLevelAreaWarehouse> = [];
          responseData.response.map((getLevelAreaWarehouse: GetLevelAreaWarehouse) => {
            arrLevelTemp.push({
              CODIGO_NIVEL: getLevelAreaWarehouse.CODIGO_NIVEL,
              NOMBRE_NIVEL: getLevelAreaWarehouse.NOMBRE_NIVEL,
              COMENTARIOS: getLevelAreaWarehouse.COMENTARIOS === null ? 'Sin comentarios' : this.resourcesService.resizeText(getLevelAreaWarehouse.COMENTARIOS, 67),
              USUARIO_REGISTRA: this.resourcesService.selectUser(getLevelAreaWarehouse.USUARIO_REGISTRA, getLevelAreaWarehouse.USUARIO_MODIFICA),
              FECHA_REGISTRA: this.resourcesService.formatDate(getLevelAreaWarehouse.FECHA_REGISTRA, getLevelAreaWarehouse.FECHA_MODIFICA),
              ESTADO: getLevelAreaWarehouse.ESTADO,
            });
          });
          console.log(arrLevelTemp);
          
          this.dataSource.data = arrLevelTemp;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoading = false;
  }

  public async goForm(typeForm: 'REG' | 'UPD', levelAreaWarehouse?:TableLevelAreaWarehouse) {
    let dataFormArea: DataFormLevel = { } as DataFormLevel;

    if (typeForm === 'REG') {
      dataFormArea = {
        idWarehouse: this.idWarehouse,
        idArea: this.idArea,
        idLevel: null,
        typeForm: typeForm,
      }
    } else if (typeForm === 'UPD' && levelAreaWarehouse !== undefined) {
      dataFormArea = {
        idWarehouse: this.idWarehouse,
        idArea: this.idArea,
        idLevel: levelAreaWarehouse.CODIGO_NIVEL,
        typeForm: typeForm,
      }
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
      return;
    }

    this._dialog.open(LevelFormComponent, {
      disableClose: true,
      width: '600px',
      data: dataFormArea,
    }).afterClosed().subscribe(async (result) => {
      if (result) {
        await this.getLevelByAreaWarehouse();
      }
    });
  }

  public async goZoneManagement(levelAreaWarehouse:TableLevelAreaWarehouse) {
    let idLevel: string = levelAreaWarehouse.CODIGO_NIVEL.replace('#', '');
    idLevel = idLevel.trim();

    let validateExists:boolean = this.arrLevel.some((getLevelAreaWarehouse: GetLevelAreaWarehouse) => getLevelAreaWarehouse.CODIGO_NIVEL.toString() === idLevel);
    if (validateExists) {
      let infoArea: InfoLevel = {
        idWarehouse: this.idWarehouse,
        idArea: this.idArea,
        idLevel: idLevel
      }
      let strArea: string = JSON.stringify(infoArea);
      let encArea: string = await this._encService.encrypt(strArea);
      this._router.navigate([`/sam/GIST/GEAL/zonas/${encArea}`]);
    } else {
      this.resourcesService.openSnackBar(`El ID del Nivel no pudo ser encontrado en la lista de niveles.`);
    }
  }

  public alert(typeAlert:'ELI', levelAreaWarehouse:TableLevelAreaWarehouse) {
    if (typeAlert === 'ELI') {
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          title: `Confirmación de Eliminación`,
          description: `¿Está seguro de eliminar el nivel ${levelAreaWarehouse.CODIGO_NIVEL}?`,
          icon: `warning`
        }
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this.deleteLevel(levelAreaWarehouse.CODIGO_NIVEL)
        }
      });
    }
  }

  private async deleteLevel(idLevel: string) {
    const encArea: string = await this._encService.encrypt(idLevel);
    const objDelete = this.resourcesService.objectUserLine();
    await lastValueFrom(this._warehouseService.deleteLevel(objDelete, encArea)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Eliminación Exitosa!`);
          this.getLevelByAreaWarehouse();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
  }
}
