import { HttpErrorResponse } from '@angular/common/http';
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 { lastValueFrom } from 'rxjs';
import { GetZoneLevelAreaWarehouse, InfoLevel, ResponseDataGetZoneLevelAreaWarehouse, TableZoneLevelAreaWarehouse } 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 { DataFormZone, ZoneFormComponent } from '../zone-form/zone-form.component';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { ResponseData } from 'src/app/interfaces/response-data';

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

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

  public dataSource: MatTableDataSource<TableZoneLevelAreaWarehouse>;
  public displayedColumns: Array<string>;
  public arrZones: Array<GetZoneLevelAreaWarehouse>;

  constructor(
    public resourcesService: ResourcesService,
    private _activatedRouter: ActivatedRoute,
    private _encService: EncService,
    private _router: Router,
    private _dialog: MatDialog,
    private _warehouseService: WarehouseService,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;

    this.dataSource = new MatTableDataSource<TableZoneLevelAreaWarehouse>();
    this.displayedColumns = ['CODIGO_ZONA','NOMBRE_ZONA','COMENTARIOS','USUARIO_REGISTRA','FECHA_REGISTRA','ESTADO','ACCIONES'];
    this.arrZones = [];
  }
  async ngOnInit() {
    this.isLoading = true;
    this.isLoadingForm = true;
    await this.getInfoZone();
    await this.getZoneByLevelAreaWarehouse();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

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

  public async getZoneByLevelAreaWarehouse() {
    this.isLoading = true;
    const encArea: string = await this._encService.encrypt(this.idArea);
    const encWarehouse: string = await this._encService.encrypt(this.idWarehouse);
    const encLevel: string = await this._encService.encrypt(this.idLevel);
    await lastValueFrom(this._warehouseService.getZoneByLevelAreaWarehouse(encWarehouse, encArea, encLevel)).then(
      (responseData: ResponseDataGetZoneLevelAreaWarehouse) => {
        if (!responseData.error) {
          this.arrZones = responseData.response;
          let arrZonesTemp: Array<TableZoneLevelAreaWarehouse> = [];
          responseData.response.map((getZoneLevelAreaWarehouse: GetZoneLevelAreaWarehouse) => {
            arrZonesTemp.push({
              CODIGO_ZONA: getZoneLevelAreaWarehouse.CODIGO_ZONA,
              NOMBRE_ZONA: getZoneLevelAreaWarehouse.NOMBRE_ZONA,
              COMENTARIOS: getZoneLevelAreaWarehouse.COMENTARIOS === null ? 'Sin comentarios' : this.resourcesService.resizeText(getZoneLevelAreaWarehouse.COMENTARIOS, 67),
              USUARIO_REGISTRA:  this.resourcesService.selectUser(getZoneLevelAreaWarehouse.USUARIO_REGISTRA, getZoneLevelAreaWarehouse.USUARIO_MODIFICA),
              FECHA_REGISTRA:  this.resourcesService.formatDate(getZoneLevelAreaWarehouse.FECHA_REGISTRA, getZoneLevelAreaWarehouse.FECHA_MODIFICA),
              ESTADO: getZoneLevelAreaWarehouse.ESTADO,
            });
          });
          this.dataSource.data = arrZonesTemp;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoading = false;
  }

  public goForm(typeForm: 'REG' | 'UPD', zoneLevelAreaWarehouse?: TableZoneLevelAreaWarehouse) {
    let dataFormArea: DataFormZone = { } as DataFormZone;

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

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

  public alert(typeAlert:'ELI', zoneLevelAreaWarehouse:TableZoneLevelAreaWarehouse) {
    if (typeAlert === 'ELI') {
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          title: `Confirmación de Eliminación`,
          description: `¿Está seguro de eliminar la zona ${zoneLevelAreaWarehouse.CODIGO_ZONA}?`,
          icon: `warning`
        }
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this.deleteZone(zoneLevelAreaWarehouse.CODIGO_ZONA)
        }
      });
    }
  }

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