import { Component } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetReplanishmentQuantities, GetReplenishmentSuggestion, RequestLine, RequestObjectRequestLine, ResponseDataGetReplanishmentQuantities, ResponseDataGetReplenismentSuggestion } from '../../../interfaces/inventory-management/replenishment-quantities.interface';
import { ResourcesService, ResponseData } from '../../../services/resources.service';
import { InventoryManagementService } from '../../../services/inventory-management/inventory-management.service';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-replenishment-quantities',
    templateUrl: './replenishment-quantities.component.html',
    styleUrl: './replenishment-quantities.component.css',
    standalone: false
})
export class ReplenishmentQuantitiesComponent {
  public isLoading: boolean;
  public isLoadingForm: boolean;

  public txtSearchReplanishmentQuantities: string;
  public txtSearchReplanishmentSuggestion: string;

  public dataSourceReplanishmentQuantities: MatTableDataSource<GetReplanishmentQuantities>;
  public dataSourceReplanishmentSuggestion: MatTableDataSource<GetReplenishmentSuggestion>;
  public arrReplanishmentQuantities: GetReplanishmentQuantities[];
  public arrReplenishmentSuggestion: GetReplenishmentSuggestion[];

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

    this.txtSearchReplanishmentQuantities = '';
    this.txtSearchReplanishmentSuggestion = '';

    this.dataSourceReplanishmentQuantities = new MatTableDataSource<GetReplanishmentQuantities>();
    this.arrReplanishmentQuantities = [];
    
    this.dataSourceReplanishmentSuggestion = new MatTableDataSource<GetReplenishmentSuggestion>();
    this.arrReplenishmentSuggestion = [];

  }

  public applyFilterReplanishmentQuantities() {
    
    const dataValue: string = this.txtSearchReplanishmentQuantities.toString().trim().toUpperCase();
    if (dataValue.length > 0) {
      let arrDataValue: GetReplanishmentQuantities[] = [];
      this.arrReplanishmentQuantities.forEach((replanishmentQuantities: GetReplanishmentQuantities) => {      

        let exists: boolean = false;
        const arrValues = Object.values(replanishmentQuantities);
        arrValues.forEach((value: string) => {
          value = value.toString().trim().toUpperCase();
          if (value.includes(dataValue)) {
            exists = true;
          }
        });

        if (exists) {
          arrDataValue.push(replanishmentQuantities);
        }
      });

      this.dataSourceReplanishmentQuantities.data = arrDataValue;
    } else {
      this.dataSourceReplanishmentQuantities.data = this.arrReplanishmentQuantities;
    }
  }

  public validateCreateRequestLineQuantities() {
    return this.dataSourceReplanishmentQuantities.data.some( (replanishmentQuantities: GetReplanishmentQuantities) => replanishmentQuantities.CANTIDAD > 0);
  }

  public alert(type: 'Q' | 'S') {
    if (!this.isLoading && !this.isLoadingForm && this.validateCreateRequestLineQuantities()) {
      this._dialog.open(AlertComponent, {
        disableClose: true,
        width: '400px',
        maxWidth: '400px',
        data: {
          title: `Confirmación`,
          description: `¿Está seguro de solicitar los artículos seleccionados?`,
          icon: `warning`,
        }
      }).afterClosed().subscribe(async (result) => {
        if (result && type === 'Q') {
          await this.createRequestLine(type);
  
        } else if (result && type === 'S') {
          await this.createRequestLine(type);
  
        }
      });
    }
  }

  private async createRequestLine( type: 'Q' | 'S' ) {

    let createRequestObject = {} as RequestObjectRequestLine;
    if (type === 'Q') {
      createRequestObject = this._createRequestObjectQuantities();

    } else if (type === 'S') {
      createRequestObject = this._createRequestObjectSuggestion();

    } else {
      this.resourcesService.openSnackBar('Opción no disponible.');
      return;
    }

    await lastValueFrom(this._inventoryManagementService.createRequestLine(createRequestObject)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar('¡Registro de Línea de Solicitud de Compra Exitosa!');
          this._router.navigate(['/sam/GEAD/ADQU/NSCO']);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.createRequestLine(type);
        }
      }
    );
  }

  private _createRequestObjectQuantities(): RequestObjectRequestLine {

    const arrStockSelected: GetReplanishmentQuantities[] = this.dataSourceReplanishmentQuantities.data.filter( (replanishmentQuantities: GetReplanishmentQuantities) => replanishmentQuantities.CANTIDAD > 0);
    const arrRequestLine: Array<RequestLine> = arrStockSelected.map((replanishmentQuantities: GetReplanishmentQuantities) => { 
      return { 
        ID_STOCK: replanishmentQuantities.ID_STOCK, 
        CANTIDAD: replanishmentQuantities.CANTIDAD
      } 
    });

    const REQUEST_OBJECT: RequestObjectRequestLine = {
      REQUEST_LINE: arrRequestLine,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
    
    return REQUEST_OBJECT;
  }

  private _createRequestObjectSuggestion(): RequestObjectRequestLine {
    const arrStockSelected: GetReplenishmentSuggestion[] = this.dataSourceReplanishmentSuggestion.data.filter(
      (replanishmentSuggestion: GetReplenishmentSuggestion) => replanishmentSuggestion.CANTIDAD_SUGERIDA > 0
    );
    const arrRequestLine: Array<RequestLine> = arrStockSelected.map((replanishmentSuggestion: GetReplenishmentSuggestion) => { 
      return { 
        ID_STOCK: replanishmentSuggestion.ID_STOCK, 
        CANTIDAD: replanishmentSuggestion.CANTIDAD_SUGERIDA
      } 
    });

    const REQUEST_OBJECT: RequestObjectRequestLine = {
      REQUEST_LINE: arrRequestLine,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
    
    return REQUEST_OBJECT;
  }

  public async getReplenishmentQuantities() {
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getReplenishmentQuantitiesService(USER, LINE)).then(
      (responseData: ResponseDataGetReplanishmentQuantities) => {
        if (!responseData.error) {
          this.dataSourceReplanishmentQuantities.data = responseData.response;
          this.arrReplanishmentQuantities = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getReplenishmentQuantities();
        }
      }
    );
  }

  public quantityProductsQuantities(accion: string, descriptionSheetStock: GetReplanishmentQuantities) {
    this.dataSourceReplanishmentQuantities.data.map( (element:GetReplanishmentQuantities) => {
      if (element.ID_STOCK === descriptionSheetStock.ID_STOCK && accion == 'suma') {
        element.CANTIDAD ++;
      }else if (element.ID_STOCK === descriptionSheetStock.ID_STOCK && accion == 'resta') {
        element.CANTIDAD --;
      }
    });
  }

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

  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 validateCreateRequestLineSuggestion() {
    return this.dataSourceReplanishmentSuggestion.data.some( (replenishmentSuggestion: GetReplenishmentSuggestion) => replenishmentSuggestion.CANTIDAD_SUGERIDA > 0);
  }
  
  public async getReplenishmentSuggestion() {
    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();
        }
      }
    );
  }
  
  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 --;
      }
    });
  }
}
