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

@Component({
  selector: 'app-artitle-list-reception',
  templateUrl: './artitle-list-reception.component.html',
  styleUrls: ['./artitle-list-reception.component.css']
})
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 _orderReceptionService: OrderReceptionService,
  ) {
    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() {    
    const encDataOrder:string = await this._encService.encrypt(this.orderNumber);
    await lastValueFrom(this._orderReceptionService.getListArtitleReception(encDataOrder)).then(
      (responseData: ResponseDataGetListArtitleReception) => {
        if (!responseData.error) {          
          this.arrListArtitleReception = responseData.response;
          let tempArr: Array<TableListArtitleReception> = [];
          console.log(responseData.response);
          
          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}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
  }

  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}`]);
  }

  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;
  }

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

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

  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;
}
