import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetZoneLevelAreaWarehouse, InfoLevel, ResponseDataGetZoneLevelAreaWarehouse, TableZoneLevelAreaWarehouse } from '../../../../interfaces/inventory-management/warehouse-management.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService, ResponseData } from '../../../../services/resources.service';
import { ActivatedRoute, Router } from '@angular/router';
import { EncService } from '../../../../services/enc.service';
import { MatDialog } from '@angular/material/dialog';
import { InventoryManagementService } from '../../../../services/inventory-management/inventory-management.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { DataDynamicForm } from '../../../../interfaces/forms-management/form-management.interface';
import { GenerateDynamicFormComponent } from '../../../forms-management-form/generate-dynamic-form/generate-dynamic-form.component';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-zone-management',
    templateUrl: './zone-management.component.html',
    styleUrl: './zone-management.component.css',
    standalone: false
})
export class ZoneManagementComponent implements OnInit, AfterViewInit {
  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>;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

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

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

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

  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 .`);
      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);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getZoneByLevelAreaWarehouse(encWarehouse, encArea, encLevel, user, line)).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_MODIFICA: getZoneLevelAreaWarehouse.USUARIO_MODIFICA,
              FECHA_MODIFICA: getZoneLevelAreaWarehouse.FECHA_MODIFICA,
              ESTADO: getZoneLevelAreaWarehouse.ESTADO,
              CANTIDAD_STOCK: getZoneLevelAreaWarehouse.CANTIDAD_STOCK === 1 ? `${getZoneLevelAreaWarehouse.CANTIDAD_STOCK} artículo` : `${getZoneLevelAreaWarehouse.CANTIDAD_STOCK} artículos`,
            });
          });
          this.dataSource.data = arrZonesTemp;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getZoneByLevelAreaWarehouse();
        }
      }
    );
    this.isLoading = false;
  }

  public goForm(typeForm: 'R' | 'M', 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();
      }
    }); */


    let arrDefaultValue  = [];
    if (typeForm === 'R') {
      arrDefaultValue.push({
        COLUMN: 'ZONA_COAL',
        TYPE: 'INPUT',
        VALUE: this.idWarehouse
      });
      arrDefaultValue.push({
        COLUMN: 'ZONA_COAR',
        TYPE: 'INPUT',
        VALUE: this.idArea
      });
      arrDefaultValue.push({
        COLUMN: 'ZONA_CONI',
        TYPE: 'INPUT',
        VALUE: this.idLevel
      });
    } else if (typeForm === 'M' && zoneLevelAreaWarehouse !== undefined) {
      arrDefaultValue.push({
        COLUMN: 'ZONA_COAL',
        TYPE: 'INPUT',
        VALUE: this.idWarehouse
      });
      arrDefaultValue.push({
        COLUMN: 'ZONA_COAR',
        TYPE: 'INPUT',
        VALUE: this.idArea
      });
      arrDefaultValue.push({
        COLUMN: 'ZONA_CONI',
        TYPE: 'INPUT',
        VALUE: this.idLevel
      });
      arrDefaultValue.push({
        COLUMN: 'ZONA_COZO',
        TYPE: 'INPUT',
        VALUE: zoneLevelAreaWarehouse.CODIGO_ZONA
      });
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
      return;
    }

    const DATA_DYNAMIC_FORM: DataDynamicForm = {
      TYPE_FORM: typeForm,
        TYPE_DIALOG: 'GENERATE',
        ID_FORM: '0000000003',
        DEFAULT_VALUE: arrDefaultValue,
    }

    this._dialog.open(GenerateDynamicFormComponent, {
      data: DATA_DYNAMIC_FORM,
      disableClose: true,
      width: '500px',
      maxWidth: '500px',
    }).afterClosed().subscribe( async (response) => {
      if (response) {
        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._inventoryManagementService.deleteZone(objDelete, encArea)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Eliminación Exitosa!`);
          this.getZoneByLevelAreaWarehouse();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deleteZone(idZone);
        }
      }
    );
  }
}
