import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetLevelAreaWarehouse, InfoArea, InfoLevel, ResponseDataGetLevelAreaWarehouse, TableLevelAreaWarehouse } 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-level-management',
    templateUrl: './level-management.component.html',
    styleUrl: './level-management.component.css',
    standalone: false
})
export class LevelManagementComponent implements OnInit, AfterViewInit {
  public dataSource: MatTableDataSource<TableLevelAreaWarehouse>;
  public displayedColumns: Array<string>;
  public arrLevel: Array<GetLevelAreaWarehouse>;

  public isLoading: boolean;
  public isLoadingForm: boolean;

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

  @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.dataSource = new MatTableDataSource<TableLevelAreaWarehouse>();
    this.displayedColumns = [
      'CODIGO_NIVEL',
      'NOMBRE_NIVEL',
      'CANTIDAD_STOCK',
      'COMENTARIOS',
      'USUARIO_MODIFICA',
      'FECHA_MODIFICA',
      '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;
  }

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

  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 almacén.`);
      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);

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

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

    let arrDefaultValue  = [];
    if (typeForm === 'R') {
      arrDefaultValue.push({
        COLUMN: 'NIVE_COAL',
        TYPE: 'INPUT',
        VALUE: this.idWarehouse
      });
      arrDefaultValue.push({
        COLUMN: 'NIVE_COAR',
        TYPE: 'INPUT',
        VALUE: this.idArea
      });
    } else if (typeForm === 'M' && levelAreaWarehouse !== undefined) {
      arrDefaultValue.push({
        COLUMN: 'NIVE_COAL',
        TYPE: 'INPUT',
        VALUE: this.idWarehouse
      });
      arrDefaultValue.push({
        COLUMN: 'NIVE_COAR',
        TYPE: 'INPUT',
        VALUE: this.idArea
      });
      arrDefaultValue.push({
        COLUMN: 'NIVE_CONI',
        TYPE: 'INPUT',
        VALUE: levelAreaWarehouse.CODIGO_NIVEL
      });
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
      return;
    }

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

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