import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { GetWarehouse, InfoWarehouse, ResponseDataGetWarehouse, TableWarehouse } from 'src/app/interfaces/inventory-management/warehouse-management.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { WarehouseService } from 'src/app/services/inventory-management/warehouse.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { DataFormWarehouse } from './warehouse-form/warehouse-form.component';
import { RequestUserNumberLine, ResponseData } from 'src/app/interfaces/response-data';
import { MatDialog } from '@angular/material/dialog';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
  selector: 'app-warehouse-management',
  templateUrl: './warehouse-management.component.html',
  styleUrls: ['./warehouse-management.component.css']
})
export class WarehouseManagementComponent implements OnInit {

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public dataSource: MatTableDataSource<TableWarehouse>;
  public arrWarehouse: Array<GetWarehouse>;
  public displayedColumns: Array<string>;

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

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

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

  public async getWarehouse() {
    this.isLoading = true;
    await lastValueFrom( this._warehouseService.getWarehouse() ).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: this.resourcesService.selectUser( getWarehouse.USUARIO_REGISTRA, getWarehouse.USUARIO_MODIFICA ),
              FECHA_MODIFICACION: this.resourcesService.formatDate( getWarehouse.FECHA_REGISTRA, getWarehouse.FECHA_MODIFICA ),
            }
            return warehouse;
          });
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoading = false;
  }

  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 almacen ${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._warehouseService.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}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    )
  }  

  
  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 + ', ';
    address += getWarehouse.COLONIA + ', ';
    if ( getWarehouse.LOCALIDAD !== null ) {
      address += getWarehouse.LOCALIDAD + ', ';
    }
    address += getWarehouse.MUNICIPIO + ', ';
    address += getWarehouse.ENTIDAD_FEDERATIVA + ', ';
    address += getWarehouse.PAIS;
    return address;
  }
}
