import { HttpErrorResponse } from '@angular/common/http';
import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { ExchangeArticles } from 'src/app/interfaces/inventory-management/exchange-articles.interface';
import { GetAreaWarehouse, GetLevelAreaWarehouse, GetWarehouse, GetZoneLevelAreaWarehouse, ResponseDataGetAreaWarehouse, ResponseDataGetLevelAreaWarehouse, ResponseDataGetWarehouse, ResponseDataGetZoneLevelAreaWarehouse } from 'src/app/interfaces/inventory-management/warehouse-management.interface';
import { EncService } from 'src/app/services/enc/enc.service';
import { ExchangeArticlesService } from 'src/app/services/inventory-management/exchange-articles.service';
import { WarehouseService } from 'src/app/services/inventory-management/warehouse.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

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

  public isLoading: boolean;
  public isLoadingForm: boolean;
  public formGroup: FormGroup;

  public arrWarehouse: Array<GetWarehouse>;
  public arrAreas: Array<GetAreaWarehouse>;
  public arrLevel: Array<GetLevelAreaWarehouse>;
  public arrZone: Array<GetZoneLevelAreaWarehouse>;

  public searchingArea: boolean;
  public searchingLevel: boolean;
  public searchingZone: boolean;

  constructor(
    @Inject(MAT_DIALOG_DATA) public exchangeArticles: ExchangeArticles,
    public resourcesService: ResourcesService,
    private _warehouseService: WarehouseService,
    private _exchangeArticlesService: ExchangeArticlesService,
    private _encService: EncService,
    private _dialog: MatDialog,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;
    this.formGroup = this.createFormGroup();

    this.arrWarehouse = [];
    this.arrAreas = [];
    this.arrLevel = [];
    this.arrZone = [];

    this.searchingArea = false;
    this.searchingLevel = false;
    this.searchingZone = false;
  }
  async ngOnInit() {
    await this.getDataDialog();
  }

  private createFormGroup() {
    return new FormGroup({
      'ALMACEN': new FormControl('', Validators.required),
      'AREA': new FormControl({value: '', disabled: true}, Validators.required),
      'NIVEL': new FormControl({value: '', disabled: true}, Validators.required),
      'ZONA': new FormControl({value: '', disabled: true}, Validators.required),
    });
  }

  private async getDataDialog() {
    this.isLoading = true;

    let almacen: string = this.exchangeArticles.NOMBRE_ALMACEN;
    if (!almacen.includes('(') || !almacen.includes(')')) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el nombre del almacen.`);
      return;
    }
    almacen = almacen.split('(')[1].split(')')[0];

    let area: string = this.exchangeArticles.NOMBRE_AREA;
    if (!area.includes('(') || !area.includes(')')) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el nombre del area.`);
      return;
    }
    area = area.split('(')[1].split(')')[0];

    let nivel: string = this.exchangeArticles.NOMBRE_NIVEL;
    if (!nivel.includes('(') || !nivel.includes(')')) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el nombre del nivel.`);
      return;
    }
    nivel = nivel.split('(')[1].split(')')[0];

    let zona: string = this.exchangeArticles.NOMBRE_ZONA;
    if (!zona.includes('(') || !zona.includes(')')) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el nombre de la zona.`);
      return;
    }
    zona = zona.split('(')[1].split(')')[0];

    await this.getWarehouseActives();

    this.formGroup.controls['ALMACEN'].setValue(almacen);
    await this.searchArea();
    this.formGroup.controls['AREA'].setValue(area);
    await this.searchLevel();
    this.formGroup.controls['NIVEL'].setValue(nivel);
    await this.searchZone();
    this.formGroup.controls['ZONA'].setValue(zona);

    this.isLoading = false;
  }

  private async getWarehouseActives() {
    await lastValueFrom(this._warehouseService.getWarehouseActives()).then(
      async (responseData: ResponseDataGetWarehouse) => {
        if (!responseData.error) {
          this.arrWarehouse = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }
    ), (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
  }

  public async searchArea() {
    this.searchingArea = true;
    this.isLoadingForm = true;
    const warehouse = this.formGroup.controls['ALMACEN'].value;
    const encWarehouse: string = await this._encService.encrypt(warehouse); 
    await lastValueFrom(this._warehouseService.getAreaByWarehouse(encWarehouse)).then(
      async (responseData: ResponseDataGetAreaWarehouse) => {
        if (!responseData.error && responseData.response.length > 0) {
          this.arrAreas = responseData.response;
          this.formGroup.controls['AREA'].enable();
        } else if (!responseData.error && responseData.response.length === 0) {
          this.resourcesService.openSnackBar(`No existen áreas registradas para este almacen.`);
          this.formGroup.controls['AREA'].disable();
          this.formGroup.controls['AREA'].setValue('');
          this.formGroup.controls['NIVEL'].disable();
          this.formGroup.controls['NIVEL'].setValue('');
          this.formGroup.controls['ZONA'].disable();
          this.formGroup.controls['ZONA'].setValue('');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse) 
    );
    this.searchingArea = false;
    this.isLoadingForm = false;
  }

  public async searchLevel() {
    this.searchingLevel = true;
    this.isLoadingForm = true;
    const warehouse = this.formGroup.controls['ALMACEN'].value;
    const encWarehouse: string = await this._encService.encrypt(warehouse); 

    const area = this.formGroup.controls['AREA'].value;
    const encArea: string = await this._encService.encrypt(area); 

    await lastValueFrom(this._warehouseService.getLevelByAreaWarehouse(encWarehouse, encArea)).then(
      async (responseData: ResponseDataGetLevelAreaWarehouse) => {
        if (!responseData.error && responseData.response.length > 0) {
          this.arrLevel = responseData.response;
          this.formGroup.controls['NIVEL'].enable();
        } else if (!responseData.error && responseData.response.length === 0) {
          this.resourcesService.openSnackBar(`No existen niveles registrados para esta área.`);
          this.formGroup.controls['NIVEL'].disable();
          this.formGroup.controls['NIVEL'].setValue('');
          this.formGroup.controls['ZONA'].disable();
          this.formGroup.controls['ZONA'].setValue('');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse) 
    );
    this.searchingLevel = false;
    this.isLoadingForm = false;
  }

  public async searchZone() {
    this.searchingZone = true;
    this.isLoadingForm = true;
    const warehouse = this.formGroup.controls['ALMACEN'].value;
    const encWarehouse: string = await this._encService.encrypt(warehouse); 

    const area = this.formGroup.controls['AREA'].value;
    const encArea: string = await this._encService.encrypt(area); 
   
    const level = this.formGroup.controls['NIVEL'].value;
    const encLevel: string = await this._encService.encrypt(level); 
    
    await lastValueFrom(this._warehouseService.getZoneByLevelAreaWarehouse(encWarehouse, encArea, encLevel)).then(
      async (responseData: ResponseDataGetZoneLevelAreaWarehouse) => {
        if (!responseData.error && responseData.response.length > 0) {
          this.arrZone = responseData.response;
          this.formGroup.controls['ZONA'].enable();
        } else if (!responseData.error && responseData.response.length === 0) {
          this.resourcesService.openSnackBar(`No existen zonas registradas para este nivel.`);
          this.formGroup.controls['ZONA'].disable();
          this.formGroup.controls['ZONA'].setValue('');
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse) 
    );
    this.searchingZone = false;
    this.isLoadingForm = false;
  }

  public validateRepeatedValues(): boolean {
    let almacen: string = this.exchangeArticles.NOMBRE_ALMACEN;
    if (!almacen.includes('(') || !almacen.includes(')')) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el nombre del almacen.`);
      return true;
    }
    almacen = almacen.split('(')[1].split(')')[0];

    let area: string = this.exchangeArticles.NOMBRE_AREA;
    if (!area.includes('(') || !area.includes(')')) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el nombre del area.`);
      return true;
    }
    area = area.split('(')[1].split(')')[0];

    let nivel: string = this.exchangeArticles.NOMBRE_NIVEL;
    if (!nivel.includes('(') || !nivel.includes(')')) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el nombre del nivel.`);
      return true;
    }
    nivel = nivel.split('(')[1].split(')')[0];

    let zona: string = this.exchangeArticles.NOMBRE_ZONA;
    if (!zona.includes('(') || !zona.includes(')')) {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener el nombre de la zona.`);
      return true;
    }
    zona = zona.split('(')[1].split(')')[0];

    const almacenForm: string = this.formGroup.controls['ALMACEN'].value;
    const areaForm: string = this.formGroup.controls['AREA'].value;
    const nivelForm: string = this.formGroup.controls['NIVEL'].value;
    const zonaForm: string = this.formGroup.controls['ZONA'].value;


    return almacenForm === almacen && areaForm === area && nivelForm === nivel && zonaForm === zona;
  }

  public save() {
    this._dialog.open(AlertComponent, {
      disableClose: true,
      data: {
        icon: `warning`,
        title: `Confirmación`,
        description: `¿Está seguro de mover el artículo ${this.exchangeArticles.CODIGO} de dirección?`
      }
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.moveArticle();
      }
    });
  }

  private async moveArticle() {
    /* await lastValueFrom(this._exchangeArticlesService.moveArticleToWarehouse()).then(
      () => {

      }, () => this.resourcesService.checkErrors(httpErrorResponse)
    ); */
  }

}
