import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { TableAreaWarehouse, GetAreaWarehouse, InfoArea, InfoWarehouse, ResponseDataGetAreaWarehouse } 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 { AreaFormComponent, DataFormArea } from '../area-form/area-form.component';
import { MatDialog } from '@angular/material/dialog';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { ResponseData } from 'src/app/interfaces/response-data';

@Component({
  selector: 'app-area-managemenet',
  templateUrl: './area-managemenet.component.html',
  styleUrls: ['./area-managemenet.component.css']
})
export class AreaManagemenetComponent implements OnInit {
  public dataSource: MatTableDataSource<TableAreaWarehouse>;
  public displayedColumns: Array<string>;
  public arrArea: Array<GetAreaWarehouse>;

  public isLoading: boolean;
  public isLoadingForm: boolean;
  
  public idWarehouse!: string;

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

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

  }

  async ngOnInit() {
    this.isLoading = true;
    this.isLoadingForm = true;
    await this.getInfoWarehouse();
    await this.getAreaByWarehouse();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

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

  public async getAreaByWarehouse() {
    this.isLoading = true;
    const encIdWarehouse: string = await this._encService.encrypt(this.idWarehouse);
    await lastValueFrom(this._warehouseService.getAreaByWarehouse(encIdWarehouse)).then(
      (responseData: ResponseDataGetAreaWarehouse) => {
        if (!responseData.error) {
          this.arrArea = responseData.response;
          let arrAreaTemp: Array<TableAreaWarehouse> = [];
          responseData.response.map(( getAreaWarehouse: GetAreaWarehouse ) => {
            arrAreaTemp.push({
              CODIGO_AREA: getAreaWarehouse.CODIGO_AREA,
              NOMBRE_AREA: getAreaWarehouse.NOMBRE_AREA,
              COMENTARIOS: getAreaWarehouse.COMENTARIOS === null ? 'Ninguno' : this.resourcesService.resizeText(getAreaWarehouse.COMENTARIOS, 40),
              FECHA_REGISTRA: this.resourcesService.formatDate( getAreaWarehouse.FECHA_REGISTRA, getAreaWarehouse.FECHA_MODIFICA ),
              USUARIO_REGISTRA: this.resourcesService.selectUser( getAreaWarehouse.USUARIO_REGISTRA, getAreaWarehouse.USUARIO_MODIFICA ),
              ESTADO: getAreaWarehouse.ESTADO,
            })
          });
          this.dataSource.data = arrAreaTemp;            
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoading = false;
  }

  public goForm(typeForm: 'REG' | 'UPD', areaWarehouse?: TableAreaWarehouse) {

    let dataFormArea: DataFormArea = { } as DataFormArea;

    if (typeForm === 'REG') {
      dataFormArea = {
        idWarehouse: this.idWarehouse,
        typeForm: typeForm,
        idArea: null,
      }
    } else if (typeForm === 'UPD' && areaWarehouse !== undefined) {
      let idArea: string = areaWarehouse.CODIGO_AREA.replace('#', '');
      idArea = idArea.trim();

      dataFormArea = {
        idWarehouse: this.idWarehouse,
        typeForm: typeForm,
        idArea: idArea,
      }
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
      return;
    }

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

  public async goLevelsManagement(areaWarehouse: TableAreaWarehouse) {
    let idArea: string = areaWarehouse.CODIGO_AREA.replace('#', '');
    idArea = idArea.trim();

    let validateExists:boolean = this.arrArea.some((getAreaWarehouse: GetAreaWarehouse) => getAreaWarehouse.CODIGO_AREA.toString() === idArea);
    if (validateExists) {
      let infoArea: InfoArea = {
        idArea: idArea,
        idWarehouse: this.idWarehouse
      }
      let strArea: string = JSON.stringify(infoArea);
      let encArea: string = await this._encService.encrypt(strArea);
      this._router.navigate([`/sam/GIST/GEAL/niveles/${encArea}`]);
    } else {
      this.resourcesService.openSnackBar(`El ID del Área no pudo ser encontrado en la lista de áreas.`);
    }
  }

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

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


