import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { FormGroupValue, RequestFormSearch, ResponseDataSearch, SearchResult } from '../../../interfaces/inventory-management/multi-criteria-search.interface';
import { ResourcesService } from '../../../services/resources.service';
import { InventoryManagementService } from '../../../services/inventory-management/inventory-management.service';
import { MatDialog } from '@angular/material/dialog';
import { FormSearchComponent } from './form-search/form-search.component';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
    selector: 'app-multi-criteria-search',
    templateUrl: './multi-criteria-search.component.html',
    styleUrl: './multi-criteria-search.component.css',
    standalone: false
})
export class MultiCriteriaSearchComponent implements OnInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public dataSource: MatTableDataSource<SearchResult>;
  public arrSearchResult: SearchResult[];
  public formGroupValue: FormGroupValue | null;
  public txtSearch: string;

  constructor (
    public resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.dataSource = new MatTableDataSource<SearchResult>();
    this.arrSearchResult = [];
    this.formGroupValue = null;
    this.txtSearch = '';
  }

  async ngOnInit() {
    this.openDialogDetails('search')
  }

  public openDialogDetails(typeDialog: 'readonly' | 'search', searchResult?: SearchResult) {
    let idStockTemp = null;
    if (typeDialog === 'readonly' && searchResult !== undefined) {
      idStockTemp = searchResult.ID_STOCK;
    }
    
    this._dialog.open(FormSearchComponent, {
      disableClose: true,
      width: '1400px',
      maxWidth: '1400px',
      data: {
        typeForm: typeDialog,
        idStock: idStockTemp,
        infoForm: this.formGroupValue,
      }
    }).afterClosed().subscribe((result: boolean | any) => {
      if (typeof result !== 'boolean') {
        this.formGroupValue = result;        
        this.search(result);
      }
    })
  }

  public async search(objectForm: any) {
    this.isLoading = true;
    this.dataSource.data = [];

    let arrForm = Object.keys(objectForm).map((key) => [key, objectForm[key]]);
    let mapForm = new Map<string, string>();
    let isEmpty: boolean = true;
    arrForm.forEach((form: Array<any>) => {
      if (form[1] !== null && (form[0] !== 'FAMILIA' && form[0] !== 'SUBFAMILIA')) {
        form[1] = form[1].toString().trim();
        isEmpty = false;
      } else if (form[1] !== null && form[0] === 'FAMILIA') {
        form[1] = form[1]['ID_FAMILIA'];
        isEmpty = false;
      } else if (form[1] !== null && form[0] === 'SUBFAMILIA') {
        form[1] = form[1]['ID_SUBFAMILIA'];
        isEmpty = false;
        
      }
      mapForm.set(form[0], form[1]);
    });

    if (isEmpty) {
      this.resourcesService.openSnackBar(`Debe seleccionar al menos un campo para continuar.`);
      return;
    }
    mapForm.set('USUARIO', this.resourcesService.getUser());
    mapForm.set('NUMERO_LINEA', this.resourcesService.getLineNumber().toString());

    const strRequest: string = JSON.stringify(Object.fromEntries(mapForm));
    const jsonRequest: RequestFormSearch = JSON.parse(strRequest);


    await lastValueFrom(this._inventoryManagementService.search(jsonRequest)).then(
      (responseData: ResponseDataSearch) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
          this.arrSearchResult = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.search(objectForm);
        }
      }
    );
    this.isLoading = false;
  }

  public applyFilter() {
    
    const dataValue: string = this.txtSearch.toString().trim().toUpperCase();
    if (dataValue.length > 0) {
      let arrDataValue: SearchResult[] = [];
      this.arrSearchResult.forEach((searchResult: SearchResult) => {      

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

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

      this.dataSource.data = arrDataValue;
    } else {
      this.dataSource.data = this.arrSearchResult;
    }
  }
}
