import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetAreaWarehouse, InfoArea, InfoWarehouse, ResponseDataGetAreaWarehouse, TableAreaWarehouse } 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-area-managemenet',
    templateUrl: './area-managemenet.component.html',
    styleUrl: './area-managemenet.component.css',
    standalone: false
})
export class AreaManagemenetComponent implements OnInit, AfterViewInit {
  public dataSource: MatTableDataSource<TableAreaWarehouse>;
  public displayedColumns: Array<string>;
  public arrArea: Array<GetAreaWarehouse>;

  public isLoading: boolean;
  public isLoadingForm: boolean;
  
  public idWarehouse!: 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<TableAreaWarehouse>();
    this.displayedColumns = ['CODIGO_AREA','NOMBRE_AREA','CANTIDAD_STOCK','COMENTARIOS','FECHA_MODIFICA','USUARIO_MODIFICA','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;
  }

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

  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 almacén.`);
      this._router.navigate(['/sam/GIST/GEAL']);
    }
  }

  public async getAreaByWarehouse() {
    this.isLoading = true;
    const encIdWarehouse: string = await this._encService.encrypt(this.idWarehouse);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getAreaByWarehouse(encIdWarehouse, user, line)).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, 100),
              FECHA_MODIFICA: getAreaWarehouse.FECHA_MODIFICA,
              USUARIO_MODIFICA: getAreaWarehouse.USUARIO_MODIFICA,
              ESTADO: getAreaWarehouse.ESTADO,
              CANTIDAD_STOCK: getAreaWarehouse.CANTIDAD_STOCK === 1 ? `${getAreaWarehouse.CANTIDAD_STOCK} artículo` : `${getAreaWarehouse.CANTIDAD_STOCK} artículos`,
            })
          });
          this.dataSource.data = arrAreaTemp;            
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getAreaByWarehouse();
        }
      }
    );
    this.isLoading = false;
  }

  public goForm(typeForm: 'R' | 'M', areaWarehouse?: TableAreaWarehouse) {

    let arrDefaultValue  = [];
    if (typeForm === 'R') {
      arrDefaultValue.push({
        COLUMN: 'AREA_COAL',
        TYPE: 'INPUT',
        VALUE: this.idWarehouse
      });
    } else if (typeForm === 'M' && areaWarehouse !== undefined) {
      arrDefaultValue.push({
        COLUMN: 'AREA_COAL',
        TYPE: 'INPUT',
        VALUE: this.idWarehouse
      });
      arrDefaultValue.push({
        COLUMN: 'AREA_COAR',
        TYPE: 'INPUT',
        VALUE: areaWarehouse.CODIGO_AREA
      });
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
      return;
    }

    const DATA_DYNAMIC_FORM: DataDynamicForm = {
      TYPE_FORM: typeForm,
        TYPE_DIALOG: 'GENERATE',
        ID_FORM: '0000000001',
        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.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();
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.deleteArea(objDelete, encArea, user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Eliminación Exitosa!`);
          this.getAreaByWarehouse();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deleteArea(idArea);
        }
      }
    );
  }
}
