import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { GetListArtitleReception, ResponseDataGetListArtitleReception, TableListArtitleReception } from '../../../../../interfaces/acquisition-management/order-reception.interface';
import { SelectionModel } from '@angular/cdk/collections';
import { ResourcesService } from '../../../../../services/resources.service';
import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../../../services/enc.service';
import { DispatchService } from '../../../../../services/acquisition-management/dispatch.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { GetDataRegisterArtitle } from '../move-stock/move-stock.component';

@Component({
    selector: 'app-artitle-list-reception',
    templateUrl: './artitle-list-reception.component.html',
    styleUrl: './artitle-list-reception.component.css',
    standalone: false
})
export class ArtitleListReceptionComponent implements OnInit, AfterViewInit {
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public dataSource: MatTableDataSource<TableListArtitleReception>;
  public displayedColumns: Array<string>;
  public selection:SelectionModel<TableListArtitleReception>;
  public arrListArtitleReception: Array<GetListArtitleReception>;
  public isLoading: boolean;
  public isLoadingForm: boolean;

  public orderNumber!: string;

  constructor(
    public resourcesService: ResourcesService,
    private _router: Router,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _activatedRouter: ActivatedRoute,
    private _dispatchService: DispatchService,
  ) {
    this.dataSource = new MatTableDataSource<TableListArtitleReception>();
    this.arrListArtitleReception = [];
    this.selection = new SelectionModel<TableListArtitleReception>(true, []);
    this.displayedColumns = [
      'SELECT',
      'IMAGEN',
      'CODIGO_ARTICULO',
      'NOMBRE_ARTICULO',
      'CODIGO_INFORMACION',
      'MODELO_INFORMACION',
      // 'ACCIONES'
    ];
    this.isLoading = false;
    this.isLoadingForm = false;
  }
  
  async ngOnInit() {
    this.isLoading = true;
    this.isLoadingForm = true;
    this.getDataOrder();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

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

  private async getDataOrder() {
    const strDataArtitleList = this._activatedRouter.snapshot.paramMap.get('form');
    if (strDataArtitleList !== null && strDataArtitleList !== '') {
      const decDataOrder:string = await this._encService.decrypt(strDataArtitleList);
      const dataOrder: DataOrder = JSON.parse(decDataOrder);
      this.orderNumber = dataOrder.ORDER;
      await this.getListArtitleReception();
    } else {
      this.resourcesService.openSnackBar('Ocurrió un error al obtener la información del número de orden de compra.');
    }
  }

  public async getListArtitleReception() {
    this.isLoading = true;
    this.isLoadingForm = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    const encDataOrder:string = await this._encService.encrypt(this.orderNumber);
    await lastValueFrom(this._dispatchService.getListArtitleReception(encDataOrder, user, line)).then(
      (responseData: ResponseDataGetListArtitleReception) => {
        if (!responseData.error) {          
          this.arrListArtitleReception = responseData.response;
          let tempArr: Array<TableListArtitleReception> = [];
          
          responseData.response.map((getListArtitleReception: GetListArtitleReception) => {
            tempArr.push({
              ID_INFORMACION: getListArtitleReception.ID_INFORMACION,
              IMAGEN: getListArtitleReception.IMAGENES[0],
              CODIGO_ARTICULO: getListArtitleReception.CODIGO_ARTICULO,
              NOMBRE_ARTICULO: getListArtitleReception.NOMBRE_ARTICULO,
              CODIGO_INFORMACION: getListArtitleReception.CODIGO_INFORMACION,
              MODELO_INFORMACION: getListArtitleReception.MODELO_INFORMACION,
            });
          })
          this.dataSource.data = tempArr;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getListArtitleReception();
        }
      }
    );
    this.isLoading = false;
    this.isLoadingForm = false;
  }

  public validateRegister() {
    let arrInformation: Array<number> = [];
    this.selection.selected.map((tableListArtitleReception: TableListArtitleReception) => {
      if (!(arrInformation.includes(tableListArtitleReception.ID_INFORMACION))) {
        arrInformation.push(tableListArtitleReception.ID_INFORMACION);
      }
    });    
    return arrInformation.length !== 1;
  }

  checkSelected() {
    let arrInformation: Array<number> = [];
    const ID_INFORMACION = this.selection.selected[0].ID_INFORMACION;
    let arrSelected: TableListArtitleReception[] = [];
    for (const element of this.dataSource.data)  {
      if (element.ID_INFORMACION === ID_INFORMACION) {
        arrSelected.push(element);
      }
    }
    this.selection.select(...arrSelected);
    
    return arrInformation.length !== 1;
  }

  public async registerArtitlesToEquipment() {
    const arrInformation: Array<number> = this.selection.selected.map((tableListArtitleReception:TableListArtitleReception) => tableListArtitleReception.ID_INFORMACION);
    const contentForm: GetDataRegisterArtitle = {
      action: 'new',
      order: this.orderNumber,
      info: this.selection.selected[0].ID_INFORMACION,
      cantidad: arrInformation.length,
    }
    const strContentForm:string = JSON.stringify(contentForm);
    const encContentForm:string = await this._encService.encrypt(strContentForm);

    this._router.navigate([`/sam/GEAD/DESP/REPE/register-equipment/${encContentForm}`]);
  }

  toggleAllRows() {
    if (this.isAllSelected()) {
      this.selection.clear();
      return;
    }
    this.selection.select(...this.dataSource.data);
  }

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  checkboxLabel(row?: TableListArtitleReception): string {
    if (!row) {
      return `${this.isAllSelected() ? 'deselect' : 'select'} all`;
    }
    return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.CODIGO_INFORMACION + 1}`;
  }
}

export interface DataOrder {
  ORDER: string;
}
