import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetWarehouse, InfoWarehouse, ResponseDataGetWarehouse, TableWarehouse } from '../../../interfaces/inventory-management/warehouse-management.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ResourcesService, ResponseData } from '../../../services/resources.service';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../services/enc.service';
import { InventoryManagementService } from '../../../services/inventory-management/inventory-management.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-warehouse-management',
    templateUrl: './warehouse-management.component.html',
    styleUrl: './warehouse-management.component.css',
    standalone: false
})
export class WarehouseManagementComponent implements OnInit, AfterViewInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;
  public dataSource: MatTableDataSource<TableWarehouse>;
  public displayedColumns: Array<string>;
  public arrWarehouse: Array<GetWarehouse>;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

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

    this.dataSource = new MatTableDataSource<TableWarehouse>();
    this.displayedColumns = [
      'CODIGO_ALMACEN',
      'NOMBRE_ALMACEN',
      'CANTIDAD_STOCK',
      'RESPONSABLE',
      // 'DIRECCION_COMPLETA',
      'USUARIO_MODIFICACION',
      'FECHA_MODIFICACION',
      'ESTADO',
      'ACCIONES'
    ];
    this.arrWarehouse = [];
  }

  async ngOnInit() {
    this.isLoading = true;
    await this.getWarehouse();
    this.isLoading = false;
  }

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

  public async getWarehouse() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._inventoryManagementService.getWarehouse(user, line)).then(
      ( responseData: ResponseDataGetWarehouse ) => {
        if ( !responseData.error ) {
          this.arrWarehouse = [ ... responseData.response ];
          this.dataSource.data = responseData.response.map(( getWarehouse: GetWarehouse ) => {

            let warehouse: TableWarehouse = {
              CODIGO_ALMACEN: getWarehouse.CODIGO_ALMACEN,
              NOMBRE_ALMACEN: getWarehouse.NOMBRE_ALMACEN,
              RESPONSABLE: `${getWarehouse.NOMBRE_RESPONSABLE} ${getWarehouse.APELLIDO_PATERNO_RESPONSABLE} ${getWarehouse.APELLIDO_MATERNO_RESPONSABLE !== null ? getWarehouse.APELLIDO_MATERNO_RESPONSABLE : ''}`,
              DIRECCION_COMPLETA: this.generateAddress(getWarehouse),
              ESTADO: getWarehouse.ESTADO !== undefined ? getWarehouse.ESTADO : 'ERR',
              USUARIO_MODIFICACION: getWarehouse.USUARIO_MODIFICA !== undefined ? getWarehouse.USUARIO_MODIFICA:  'ERR',
              FECHA_MODIFICACION:  getWarehouse.FECHA_MODIFICA !== undefined ? getWarehouse.FECHA_MODIFICA:  'ERR',
              CANTIDAD_STOCK: getWarehouse.CANTIDAD_STOCK === 1 ? `${getWarehouse.CANTIDAD_STOCK} artículo` : `${getWarehouse.CANTIDAD_STOCK} artículos`,
            }
            return warehouse;
          });
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getWarehouse();
        }
      }
    );
    this.isLoading = false;
  }
  
  public generateAddress(getWarehouse: GetWarehouse) : string {
    let address:string = '';

    address += getWarehouse.CALLE + ', ';
    address += getWarehouse.NUMERO_EXTERIOR + ', ';
    if ( getWarehouse.NUMERO_INTERIOR !== null ) {
      address += getWarehouse.NUMERO_INTERIOR + ', ';
    }
    address += getWarehouse.CODIGO_POSTAL + ', ';


    getWarehouse.COLONIA = getWarehouse.COLONIA.split('(')[0];
    getWarehouse.COLONIA = getWarehouse.COLONIA.trim();
    address += getWarehouse.COLONIA + ', ';

    if ( getWarehouse.LOCALIDAD !== null ) {
      getWarehouse.LOCALIDAD = getWarehouse.LOCALIDAD.split('(')[0];
      getWarehouse.LOCALIDAD = getWarehouse.LOCALIDAD.trim();
      address += getWarehouse.LOCALIDAD + ', ';
    }

    getWarehouse.MUNICIPIO = getWarehouse.MUNICIPIO.split('(')[0];
    getWarehouse.MUNICIPIO = getWarehouse.MUNICIPIO.trim();
    address += getWarehouse.MUNICIPIO + ', ';

    getWarehouse.ENTIDAD_FEDERATIVA = getWarehouse.ENTIDAD_FEDERATIVA.split('(')[0];
    getWarehouse.ENTIDAD_FEDERATIVA = getWarehouse.ENTIDAD_FEDERATIVA.trim();
    address += getWarehouse.ENTIDAD_FEDERATIVA + ', ';

    getWarehouse.PAIS = getWarehouse.PAIS.split('(')[0];
    getWarehouse.PAIS = getWarehouse.PAIS.trim();
    address += getWarehouse.PAIS;

    return address;
  }

  public async goForm(typeForm: 'REG'|'UPD'|'ARE', getWarehouse?:GetWarehouse) : Promise<void> {
    if (typeForm === 'REG') {
      const dataForm: DataFormWarehouse = {
        typeForm: typeForm,
        idWarehouse: null,
      }
      const strDataForm: string = JSON.stringify(dataForm);
      const encDataForm: string = await this._encService.encrypt(strDataForm);
      this._router.navigate([`/sam/GIST/GEAL/form/${encDataForm}`]);


    } else if ( typeForm === 'UPD' && getWarehouse !== undefined) {
      const dataForm: DataFormWarehouse = {
        typeForm: typeForm,
        idWarehouse: getWarehouse.CODIGO_ALMACEN,
      }
      const strDataForm: string = JSON.stringify(dataForm);
      const encDataForm: string = await this._encService.encrypt(strDataForm);
      this._router.navigate([`/sam/GIST/GEAL/form/${encDataForm}`]);
      
    } else if ( typeForm === 'ARE' && getWarehouse !== undefined) {
      
      const info: InfoWarehouse = {
        idWarehouse: getWarehouse.CODIGO_ALMACEN,
      }
      const strInfo: string = JSON.stringify(info);
      const encInfo: string = await this._encService.encrypt(strInfo);
      this._router.navigate([`/sam/GIST/GEAL/areas/${encInfo}`]);
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
    }
  }

  public async alert(typeAlert: 'ELI', warehouse: TableWarehouse) {
    if (typeAlert === 'ELI') {
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          title: `Confirmación de Eliminación`,
          description: `¿Está seguro de eliminar el almacén ${warehouse.CODIGO_ALMACEN}?`,
          icon: `warning`
        }
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this.deleteWarehouse(warehouse.CODIGO_ALMACEN)
        }
      })
    }
  }

  private async deleteWarehouse(idWarehouse:string) {
    const encWarehouse: string = await this._encService.encrypt(idWarehouse);
    const objDelete = this.resourcesService.objectUserLine();
    await lastValueFrom(this._inventoryManagementService.deleteWarehouse(objDelete, encWarehouse)).then(
      async (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Eliminación Exitosa!`);
          await this.getWarehouse();
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deleteWarehouse(idWarehouse);
        }
      }
    )
  }  
}

export interface DataFormWarehouse {
  typeForm: 'REG'|'UPD';
  idWarehouse: string | null;
}