import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetReplenishmentSuggestion, ResponseDataGetReplenismentSuggestion } from '../../../interfaces/inventory-management/replenishment-quantities.interface';
import { ResourcesService } from '../../../services/resources.service';
import { InventoryManagementService } from '../../../services/inventory-management/inventory-management.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-reset-articles',
    templateUrl: './reset-articles.component.html',
    styleUrl: './reset-articles.component.css',
    standalone: false
})
export class ResetArticlesComponent implements OnInit {
  public isLoading: boolean;
  public txtSearchReplanishmentSuggestion: string;
  public dataSourceReplanishmentSuggestion: MatTableDataSource<GetReplenishmentSuggestion>;
  public arrReplenishmentSuggestion: GetReplenishmentSuggestion[];

  constructor (
    public resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
  ) {
    this.isLoading = false;
    this.txtSearchReplanishmentSuggestion = '';
    this.dataSourceReplanishmentSuggestion = new MatTableDataSource<GetReplenishmentSuggestion>();
    this.arrReplenishmentSuggestion = [];
  }

  async ngOnInit() {
    this.isLoading = true;
    await this.getReplenishmentSuggestion();
    this.isLoading = false;
  }

  public async getReplenishmentSuggestion() {
    this.isLoading = true;
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getReplenishmentSuggestion(USER, LINE)).then(
      (responseData: ResponseDataGetReplenismentSuggestion) => {
        if (!responseData.error) {
          this.dataSourceReplanishmentSuggestion.data = responseData.response;
          this.arrReplenishmentSuggestion = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getReplenishmentSuggestion();
        }
      }
    );
    this.isLoading = false;
  }

  public applyFilterReplanishmentSuggestion () {
    const dataValue: string = this.txtSearchReplanishmentSuggestion.toString().trim().toUpperCase();
    if (dataValue.length > 0) {
      let arrDataValue: GetReplenishmentSuggestion[] = [];
      this.arrReplenishmentSuggestion.forEach((replenishmentSuggestion: GetReplenishmentSuggestion) => {      
        let exists: boolean = false;
        const arrValues = Object.values(replenishmentSuggestion);
        arrValues.forEach((value: any) => {
          if (typeof value === 'string' || typeof value === 'number') {
            value = value.toString().trim().toUpperCase();
            if (value.includes(dataValue)) {
              exists = true;
            }
          }
        });
        if (exists) {
          arrDataValue.push(replenishmentSuggestion);
        }
      });
      this.dataSourceReplanishmentSuggestion.data = arrDataValue;
    } else {
      this.dataSourceReplanishmentSuggestion.data = this.arrReplenishmentSuggestion;
    }
  }

  public quantityProductsSuggestion(accion: string, descriptionSheetStock: GetReplenishmentSuggestion) {
    this.dataSourceReplanishmentSuggestion.data.map( (element:GetReplenishmentSuggestion) => {
      if (element.ID_INFORMACION_STOCK === descriptionSheetStock.ID_INFORMACION_STOCK && accion == 'suma') {
        element.CANTIDAD_SUGERIDA ++;
      }else if (element.ID_INFORMACION_STOCK === descriptionSheetStock.ID_INFORMACION_STOCK && accion == 'resta') {
        element.CANTIDAD_SUGERIDA --;
      }
    });
  }

  public validateQuantity(cantidad: number, data: any){
    if (cantidad < 0 ) {
      this.dataSourceReplanishmentSuggestion.data.map((element:any) => {
        if (element.NUMERO_INFORMACION === data.NUMERO_INFORMACION) {
          element.CANTIDAD = 0;
        }
      });
    }
  }
}
