import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { lastValueFrom } from 'rxjs';
import { DataFamilies, DataSubfamilies, ResponseDataFamilies } from 'src/app/interfaces/acquisition-management/artitle.interface';
import { ArtitleService } from 'src/app/services/acquisition-management/artitle.service';
import { UnitService } from 'src/app/services/acquisition-management/unit.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { ResponseDataUnit, UnitData } from '../../../provider/artitle/artitle-description-form/artitle-description-form.component';
import { ProviderService } from 'src/app/services/acquisition-management/provider.service';
import { InformationsData, ResponseDataProvider } from 'src/app/interfaces/acquisition-management/provider.interface';
import { MatDialog } from '@angular/material/dialog';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { WarehouseService } from 'src/app/services/inventory-management/warehouse.service';
import { ResponseData } from 'src/app/interfaces/response-data';
import { Router } from '@angular/router';
import { FileSelected } from 'src/app/interfaces/upload-files.interface';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { ResponseDataUploadTempFile } from 'src/app/interfaces/gdel.interface';

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

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

  public arrFamilies: Array<DataFamilies>;
  public arrSubfamilies: Array<DataSubfamilies>;
  public arrUnits: Array<UnitData>;
  public arrProvider: Array<InformationsData>;
  public arrFileSelected: Array<FileSelected>;

  constructor(
    public resourcesService: ResourcesService,
    private _artitleServices: ArtitleService,
    private _unitService: UnitService,
    private _providerService: ProviderService,
    private _dialog: MatDialog,
    private _warehouseService: WarehouseService,
    private _gdelService: GdelService,
    private _router: Router,
  ) {
    this.isLoading = false;
    this.isLoadingForm = false;

    this.arrFamilies = [];
    this.arrSubfamilies = [];
    this.arrUnits = [];
    this.arrProvider = [];
    this.arrFileSelected = [];

    this.formGroup = this.createFormGroup();
  }

  ngOnInit(): void {
    this.getFamiliesAndSubfamilies();
    this.getUnits();
    this.getProvider();
  }

  private createFormGroup() {
    return new FormGroup({
      'CODIGO_STOCK': new FormControl(''),
      'ARTICULO': new FormControl('', Validators.required),
      'MODELO': new FormControl('', Validators.required),
      'CODIGO_MODELO': new FormControl('', Validators.required),
      'FAMILIA': new FormControl('', Validators.required),
      'SUBFAMILIA': new FormControl('', Validators.required),
      'UNIDAD': new FormControl('', Validators.required),
      'CODIGO_BARRAS': new FormControl('', Validators.required),
      'CANTIDAD': new FormControl('', Validators.required),
      'STOCK_MINIMO': new FormControl('', Validators.required),
      'STOCK_MAXIMO': new FormControl('', Validators.required),
      'REPARACION': new FormControl(false),
      'CONSUMIBLE': new FormControl(false),
      'PELIGROSO': new FormControl(false),
      'FECHA_VENCIMIENTO': new FormControl(''),
      'PROVEEDOR': new FormControl(''),
      'IMAGEN': new FormControl('', Validators.required),
    });
  }

  public alert(typeAlert: string, fileSelected?: FileSelected) {

    if ( typeAlert === 'SAVE' ) {
      this._dialog.open(AlertComponent, {
        data: {
          icon: 'warning',
          title: 'Registro de Artículo',
          description: '¿Esta seguro de registrar el artículo sin pedido?'
        }
      }).afterClosed().subscribe((responseDialog: boolean) => {
        if (responseDialog) {
          this.registerArtitle();
        }
      });
    } else if (typeAlert === 'DELETE_TEMP') {
      this._dialog.open(AlertComponent, {
        data: {
          icon: "warning",
          title: "Eliminar Archivo",
          description: "¿Está seguro de eliminar el archivo seleccionado?"
        },
        disableClose: true,
      }).afterClosed().subscribe(async (result) => {
        if (result) {
          await this.deleteTempFile(fileSelected!.id);
        } 
      });
    }
  }

  public async uploadTempFile(event: any) {
    this.isLoadingForm = true;

    let arrFiles: Array<File> = Array.from(event.target.files);
    if (arrFiles.length > 1) {
      this.resourcesService.openSnackBar(`Analizando los ${arrFiles.length} archivos seleccionados.`)
    } else {
      this.resourcesService.openSnackBar(`Analizando el archivo seleccionado`);
    }

    let arrIdFile: Array<string> = [];

    await Promise.all(
      arrFiles.map(async (file:File) => {
        var myFormData = new FormData();
        myFormData.append('file', file);
        myFormData.append('id_user', this.resourcesService.getUser());
        myFormData.append('linea', this.resourcesService.getLineNumber());

        await lastValueFrom(this._gdelService.uploadTempFile(myFormData )).then(
          async (responseData: ResponseDataUploadTempFile) => {
            if (!responseData.error) {            
              this.arrFileSelected.push({
                id: responseData.response.idArchivo, 
                file: file,
                view: URL.createObjectURL(file),
                state: 'TEMPORAL',
              });
              arrIdFile.push(responseData.response.idArchivo);
            } else {
              this.resourcesService.openSnackBar(`${responseData.msg}`);
            }
          }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
        );
      })
    );

    if (arrIdFile.length != arrFiles.length) {
      this.resourcesService.openSnackBar(`Ocurrió un error con algún archivo, eliminando los archivos.`);
      await Promise.all(
        arrIdFile.map(async (idFile:string) => {
          await this.deleteTempFile(idFile);
        })
      );
      this.arrFileSelected = this.arrFileSelected.filter((selected:FileSelected) => !arrIdFile.includes(selected.id));

    } else {
      this.resourcesService.openSnackBar(`¡Archivos Analizados Exitosamente!`);
      const arrId:Array<string> = this.arrFileSelected.map(( fileSelected:FileSelected) => fileSelected.id);
      this.formGroup.controls['IMAGEN'].setValue(arrId);

    }
    this.isLoadingForm = false;    
  }

  private async deleteTempFile(idArchivo:string) {
    this.isLoadingForm = true;
    this.resourcesService.openSnackBar(`Eliminando archivo, espere un momento`);
    var myFormData = new FormData();
    myFormData.append('id_file', idArchivo);
    myFormData.append('id_user', this.resourcesService.getUser());
    myFormData.append('linea', this.resourcesService.getLineNumber());

    await lastValueFrom(this._gdelService.deleteTempFile(myFormData)).then(
      async (responseData: ResponseDataUploadTempFile) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar(`¡Eliminación del archivo temporal exitosa!`);
          this.arrFileSelected = await Promise.all(
            this.arrFileSelected.filter((selected:FileSelected) => selected.id !== idArchivo && selected.state === 'TEMPORAL')
          );
          const arrId:Array<string> = await Promise.all(
            this.arrFileSelected.map(( fileSelected:FileSelected) => fileSelected.id)
          );
          this.formGroup.controls['IMAGEN'].setValue(arrId);
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  private async registerArtitle() {
    this.isLoadingForm = true;
    let objectRequest = this.createObjectRequest();    
    await lastValueFrom(this._warehouseService.registerArtitleWithoutOrder(objectRequest)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar('¡Registro Exitoso!');
          this._router.navigate(['/sam/GEAD/DESP/REPE']);
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  private createObjectRequest() {
    let dateFormat = null;
    if (this.formGroup.controls['FECHA_VENCIMIENTO'].value !== '' && this.formGroup.controls['FECHA_VENCIMIENTO'].value !== null && this.formGroup.controls['FECHA_VENCIMIENTO'].value !== undefined) {
      let date:Date = new Date(this.formGroup.controls['FECHA_VENCIMIENTO'].value);
      dateFormat = this.resourcesService.getDateFormatCalendar(date);  
    }

    return {
      CODIGO_STOCK: this.formGroup.controls['CODIGO_STOCK'].value,
      ARTICULO: this.formGroup.controls['ARTICULO'].value.trim(),
      MODELO: this.formGroup.controls['MODELO'].value.trim(),
      CODIGO_MODELO: this.formGroup.controls['CODIGO_MODELO'].value.trim(),
      FAMILIA: this.formGroup.controls['FAMILIA'].value,
      SUBFAMILIA: this.formGroup.controls['SUBFAMILIA'].value,
      UNIDAD: this.formGroup.controls['UNIDAD'].value,
      CODIGO_BARRAS: this.formGroup.controls['CODIGO_BARRAS'].value.trim(),
      CANTIDAD: this.formGroup.controls['CANTIDAD'].value.toString().trim(),
      STOCK_MINIMO: this.formGroup.controls['STOCK_MINIMO'].value.toString().trim(),
      STOCK_MAXIMO: this.formGroup.controls['STOCK_MAXIMO'].value.toString().trim(),
      REPARACION: this.formGroup.controls['REPARACION'].value,
      CONSUMIBLE: this.formGroup.controls['CONSUMIBLE'].value,
      PELIGROSO: this.formGroup.controls['PELIGROSO'].value,
      FECHA_VENCIMIENTO: dateFormat,
      PROVEEDOR: this.formGroup.controls['PROVEEDOR'].value,
      IMAGEN: this.formGroup.controls['IMAGEN'].value,
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
      USUARIO: this.resourcesService.getUser(),
    }

  }

  

  private async getFamiliesAndSubfamilies() {
    await lastValueFrom(this._artitleServices.getFamiliesAndSubfamilies()).then(
      (responseData: ResponseDataFamilies) => {
        if (!responseData.error) {
          this.arrFamilies = responseData.response;
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  private async getUnits() {
    await lastValueFrom(this._unitService.getUnitsActives()).then(
      (responseData: ResponseDataUnit) => {
        if (!responseData.error) {
          this.arrUnits = responseData.response;
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  private async getProvider() {
    let idUser = localStorage.getItem('idusuario')!;
    await lastValueFrom(this._providerService.getProviderActives()).then(
      (responseData: ResponseDataProvider) => {
        if (!responseData.error) {
          this.arrProvider = responseData.response;
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }



}
