import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { GetWarehouse, ResponseDataGetWarehouse } from '../../../interfaces/inventory-management/warehouse-management.interface';
import { MatTableDataSource } from '@angular/material/table';
import { GetArticleClassificate, ResponseDataGetClassificate } from '../../../interfaces/inventory-management/inventory-management.inerface';
import { FormControl, Validators } from '@angular/forms';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
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-article-clasification',
    templateUrl: './article-clasification.component.html',
    styleUrl: './article-clasification.component.css',
    standalone: false
})
export class ArticleClasificationComponent implements OnInit, AfterViewInit {
  public arrWarehouse: GetWarehouse[];
  public dataSource: MatTableDataSource<GetArticleClassificate>;
  public displayedColumns: string[];
  public isLoading: boolean;
  public formControl: FormControl;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  constructor (
    public resourcesService: ResourcesService,
    private _inventoryManagementService: InventoryManagementService,
  ) {
    this.arrWarehouse = [];
    this.dataSource = new MatTableDataSource<GetArticleClassificate>();
    this.displayedColumns = [
      'ID_INFORMACION',
      'PROVEEDOR',
      'TIPO_EQUIPAMIENTO',
      'MODELO_EQUIPAMIENTO',
      'PRECIO',
      'CANTIDAD',
      'TASA_ROTACION_MENSUAL',
      'TASA_ROTACION_SEMESTRAL',
      'TASA_ROTACION_ANUAL',
    ];
    this.isLoading = false;
    this.formControl = new FormControl(null, Validators.required);
  }
  
  async ngOnInit() {
    this.isLoading = true;
    await this._getWarehouseActives();
    await this.getArticleClassificateByWarehouse();
    this.isLoading = false;
  }

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

  private async _getWarehouseActives() {
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getWarehouseActives(USER, LINE)).then(
      async (responseData: ResponseDataGetWarehouse) => {
        if (!responseData.error) {
          this.arrWarehouse = responseData.response;
          if (this.arrWarehouse.length === 0) {
            this.resourcesService.openSnackBar(`No existen almacenes.`);
            this.resourcesService.goBack();
          }
          if (this.formControl.value === null || this.formControl.value === undefined || this.formControl.value === '') {
            this.formControl.setValue(this.arrWarehouse[0].CODIGO_ALMACEN);
          } 
        } else {
          this.resourcesService.openSnackBar(`${ responseData.msg }`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse);
        if (response !== null && response.reload) {
          await this._getWarehouseActives();
        }
      }
    );
  }

  public async getArticleClassificateByWarehouse() {
    this.isLoading = true;    
    if (this.formControl.value === null || this.formControl.value === undefined || this.formControl.value === '') {
      this.resourcesService.openSnackBar(`Seleccione un almacen para continuar`);
      this.isLoading = false
      return;
    }
    const ID_WAREHOUSE: string = this.formControl.value;
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getArticleClassificateByWarehouse(ID_WAREHOUSE, USER, LINE)).then(
      (responseData: ResponseDataGetClassificate) => {
        if (!responseData.error) {
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse);
        if (response !== null && response.reload) {
          await this.getArticleClassificateByWarehouse();
        }
      }
    );
    this.isLoading = false;
  }
}
