import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { DataDescriptionArticle, DataFamilies, DataInformationArticle, DataMoneda, DataSubfamilies, DialogInformationArtitle, FormRequestArticle, FormRequestInformation, GetArticleById, ResponseDataFamilies, ResponseDataGetArticleById, TypeFormArticle } from '../../../../../interfaces/acquisition-management/artitle.interface';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ResourcesService } from '../../../../../services/resources.service';
import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../../../services/enc.service';
import { GdelService } from '../../../../../services/gdel.service';
import { AcquisitionService } from '../../../../../services/acquisition-management/acquisition.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { ArtitleDescriptionFormComponent } from '../artitle-description-form/artitle-description-form.component';
import { ArtitleDetailsComponent } from '../artitle-details/artitle-details.component';
import { AlertComponent } from '../../../../resources/dialogs/alert/alert.component';
import { PriorityArticleComponent } from '../priority-article/priority-article.component';
import { ResponseData } from '../../../../../interfaces/response-data';
import { ResponseDataUploadTempFile } from '../../../../../interfaces/gdel.interface';

@Component({
    selector: 'app-artitle-form',
    templateUrl: './artitle-form.component.html',
    styleUrl: './artitle-form.component.css',
    standalone: false
})
export class ArtitleFormComponent implements OnInit {
  public isLoading:boolean;

  public dataSource: MatTableDataSource<DataDescriptionArticle>;
  public displayedColumnsInformation: Array<string>;
  public arrFamilies: Array<DataFamilies>;
  public arrSubfamilies: Array<DataSubfamilies>;
  public arrCatalogoMonedas: Array<DataMoneda>;
  public arrDeleteFiles: Array<string>;
  public arrArtitle: Array<any>;

  public formGroup: FormGroup;
  public typeForm: TypeFormArticle;
  public idArticle!: number;
  public title!: string;

  constructor(
    public resourcesService: ResourcesService,
    private _router: Router,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _gdelService: GdelService,
    private _activatedRouter: ActivatedRoute,
    private _acquisitionServices: AcquisitionService,
  ) {
    this.typeForm = {} as TypeFormArticle;
    this.displayedColumnsInformation = ['IMAGEN','PROVEEDOR','DESCRIPCION','CARACTERISTICAS','CANTIDAD_DETALLES','ESTADO','ACCIONES'];
    this.dataSource = new MatTableDataSource<DataDescriptionArticle>();
    this.formGroup = this.createFormGroup();
    this.isLoading = false;

    this.arrFamilies = [];
    this.arrSubfamilies = [];
    this.arrArtitle = [];
    this.arrCatalogoMonedas = [];
    this.arrDeleteFiles = [];

    this.formGroup.controls['FAMILIA'].valueChanges.subscribe((family) => {
      this.arrSubfamilies = family.SUBFAMILIAS;
      this.formGroup.controls['SUBFAMILIA'].enable();
    })
  }

  private createFormGroup() {
    return new FormGroup({
      'CODIGO': new FormControl('', Validators.required),
      'ARTICULO': new FormControl('', Validators.required),
      'FAMILIA': new FormControl('', Validators.required),
      'SUBFAMILIA': new FormControl({ value: '', disabled: true }, Validators.required),
    });
  }

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

  private async _getFamiliesAndSubfamilies() {
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionServices.getFamiliesAndSubfamilies(USER, LINE)).then(
      (responseData:ResponseDataFamilies) => {
        if ( !responseData.error ) {
          this.arrFamilies = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._getFamiliesAndSubfamilies();
        }
        this.resourcesService.goBack();
      }
    );
  }

  private async getDataForm() {    
    
    const ENC_FORM: string | null = this._activatedRouter.snapshot.paramMap.get('form');
    if (ENC_FORM !== null) {
      const STR_FORM: string = await this._encService.decrypt(ENC_FORM);
      this.typeForm = JSON.parse(STR_FORM);
      
      if (this.typeForm.type === 'R') {
        this.title = `Registro de artículos`;
      } else if (this.typeForm.type === 'M' && this.typeForm.idArticle !== undefined) {
        this.title = `Modificación de artículos`;
        this.idArticle = this.typeForm.idArticle;
        await this._getArtitleById();

      } else {
        this.resourcesService.openSnackBar(`Opción del formulario no disponible`);
        this.resourcesService.goBack();
      }
      
    } else {
      this.resourcesService.openSnackBar(`No se pudo recuperar los datos del formulario.`);
      this.resourcesService.goBack();
    }
  }

  private async _getArtitleById() {
    const ENC_ARTICLE: string = await this._encService.encrypt(this.idArticle.toString());
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionServices.getArtitleById(ENC_ARTICLE, USER, LINE)).then(
      async (responseData: ResponseDataGetArticleById) => {
        if (!responseData.error) {
          const ARTICLE: GetArticleById = responseData.response;

          this.formGroup.controls['CODIGO'].setValue(ARTICLE.CODIGO);
          this.formGroup.controls['ARTICULO'].setValue(ARTICLE.ARTICULO);
          
          const FAMILY: DataFamilies | undefined = this.arrFamilies.find((family: DataFamilies) => family.ID_FAMILIA === ARTICLE.FAMILIA);
          if (FAMILY !== undefined) {
            this.formGroup.controls['FAMILIA'].setValue(FAMILY);
          } else {
            this.resourcesService.openSnackBar(`No se encontró la familia para seleccionarla.`);
            return;
          }

          const SUBFAMILY: DataSubfamilies | undefined = FAMILY.SUBFAMILIAS.find((subfamily: DataSubfamilies) => subfamily.ID_SUBFAMILIA === ARTICLE.SUBFAMILIA);
          if (FAMILY !== undefined) {
            this.formGroup.controls['SUBFAMILIA'].setValue(SUBFAMILY);
          } else {
            this.resourcesService.openSnackBar(`No se encontró la subfamilia para seleccionarla.`);
            return;
          }

          this.dataSource.data = ARTICLE.DESCRIPCION_ARTICULO;

        } else { 
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._getArtitleById();
        }
        this.resourcesService.goBack();
      }
    );
  }

  public openDialogDescriptionArticle(type: 'R' | 'M', index?: number) {

    let arrProvidersSelected: string[] = [];
    for (const element of this.dataSource.data) {
      arrProvidersSelected.push(element.NUMERO_PROVEEDOR);
    }
    let dialogInformation: DialogInformationArtitle = { } as DialogInformationArtitle;
    dialogInformation.type = type;
    dialogInformation.providersSelected = arrProvidersSelected;
    if (type === 'M' && index !== undefined) {
      dialogInformation.elementData = this.dataSource.data[index];
    }

    this._dialog.open(ArtitleDescriptionFormComponent, {
      disableClose: true,
      width: '600px',
      data: dialogInformation,
    }).afterClosed().subscribe((response: false | FormRequestInformation) => {
      if ( response && type === 'R') {
        this._registerDescriptionArticle(response)
      } else if ( response && type === 'M' && index !== undefined) {
        this._updateDescriptionArticle(response, index)
      } 
    });
  }
  
  private _registerDescriptionArticle(requestForm: FormRequestInformation) {
    let datasource = this.dataSource.data;
    const DATA_INFO: DataDescriptionArticle = {
      ID_DESCRIPCION: 0,
      NUMERO_PROVEEDOR: requestForm.NUMERO_PROVEEDOR,
      PROVEEDOR: requestForm.PROVEEDOR,
      ID_UNIDAD: requestForm.ID_UNIDAD,
      UNIDAD: requestForm.UNIDAD,
      CANTIDAD_UNIDAD: requestForm.CANTIDAD_UNIDAD,
      DESCRIPCION: requestForm.DESCRIPCION,
      CARACTERISTICAS: requestForm.CARACTERISTICAS,
      ESTADO: 'Activo',
      DETALLES: [],
      ARCHIVOS: requestForm.ARCHIVOS,
    }
    
    datasource.push(DATA_INFO);
    this.dataSource.data = datasource;    
  }
  
  private _updateDescriptionArticle (requestForm: FormRequestInformation, index: number) {

    let datasource = this.dataSource.data

    datasource[index].NUMERO_PROVEEDOR = requestForm.NUMERO_PROVEEDOR;
    datasource[index].PROVEEDOR = requestForm.PROVEEDOR;
    datasource[index].ID_UNIDAD = requestForm.ID_UNIDAD;
    datasource[index].UNIDAD = requestForm.UNIDAD;
    datasource[index].CANTIDAD_UNIDAD = requestForm.CANTIDAD_UNIDAD;
    datasource[index].DESCRIPCION = requestForm.DESCRIPCION;
    datasource[index].CARACTERISTICAS = requestForm.CARACTERISTICAS;
    datasource[index].ARCHIVOS = requestForm.ARCHIVOS,

    this.dataSource.data = datasource;

  }

  public setImage (dataDescription: DataDescriptionArticle) {
    if (dataDescription.ARCHIVOS.length === 0) {
      return 'assets/img/empty_img_2.svg';
    } else {
      let imagen = 'assets/img/empty_img_2.svg';
      for (const element of dataDescription.ARCHIVOS) {
        if (element.TYPE !== 'OD') {
          imagen = element.SHOW;
        }
      }
      return imagen;
    }
  }

  public setAlt (dataDescription: DataDescriptionArticle) {
    if (dataDescription.ARCHIVOS.length === 0) {
      return 'no_data';
    } else {
      return dataDescription.ARCHIVOS[0].NAME;
    }
  }

  public countDetails(arrDetails: DataInformationArticle[]){
    let items: number = 0;
    for (const details of arrDetails) {
      if (details.ESTADO !== 'Eliminado') {
        items += 1;
      }
    }

    if (items === 0) {
      return `No se ha registrado información`;
    } else {
      return items;
    }
  }

  public openDialogDetails (dataDescription: DataDescriptionArticle, index: number) {
    this._dialog.open(ArtitleDetailsComponent, {
      data: dataDescription.DETALLES,
      disableClose: true,
      width: '1000px',
    }).afterClosed().subscribe(
      (response: false | DataInformationArticle[]) => {
        if (response) {
          let datasource = this.dataSource.data;
          datasource[index].DETALLES = response;
          this.dataSource.data = datasource;
        }
      }
    );
  }

  public alertUpdateStatus (type: 'E' | 'A', index: number) {
    if (type === 'E') {
      this._dialog.open(AlertComponent, {
        data: {
          title: `Confirmación`,
          description: `¿Está seguro de eliminar la descripción del artículo?`,
          icon: `warning`,
        },
        disableClose: true,
      }).afterClosed().subscribe(
        (response) => {
          if (response) {
            let datasource = this.dataSource.data;
            datasource[index].ESTADO = 'Eliminado';
            this.dataSource.data = datasource;
          }
        }
      );
      
    } else if (type === 'A') {
      this._dialog.open(AlertComponent, {
        data: {
          title: `Confirmación`,
          description: `¿Está seguro de activar la descripción del artículo?`,
          icon: `warning`,
        },
        disableClose: true,
      }).afterClosed().subscribe(
        (response) => {
          if (response) {
            let datasource = this.dataSource.data;
            datasource[index].ESTADO = 'Activo';
            this.dataSource.data = datasource;
          }
        }
      );
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible`);
    }
  }

  public isValidData () {
    let isFormValid: boolean = this.formGroup.valid;
    let isDataValid: boolean = this.dataSource.data.length > 0;

    for (const element of this.dataSource.data) {
      if (element.ESTADO === 'Activo') {
        let countDetails: number = 0;

        for (const details of element.DETALLES) {
          if (details.ESTADO === 'Activo') {
            countDetails++;
          }
        }

        if (countDetails === 0) {
          isDataValid = false;
        }
      }
    }
    return isFormValid && isDataValid;
  }

  public async save () {
    if (this.dataSource.data.length > 1) {
      this._dialog.open(PriorityArticleComponent, {
        data: this.dataSource.data,
        width: '800px'
      }).afterClosed().subscribe(async (response) => {
        if (response) {
          this.dataSource.data = response
          await this._confirmateSave();
        }
      });
    } else {
      await this._confirmateSave();
    }
  }

  private async _confirmateSave() {
    this._dialog.open(AlertComponent, {
      data: {
        title: `Confirmación`,
        description: `¿Está seguro se guardar la información del artículo?`,
        icon: `warning`,
      }
    }).afterClosed().subscribe(
      async (response) => {
        if (response && this.typeForm.type === 'R') {
          await this._registerArticle();
        } else if (response && this.typeForm.type === 'M') {
          await this._updateArticle();
        }
      }
    );
  }

  private async _registerArticle() {
    const FORM_REQUEST: FormRequestArticle = this.createObjectResponse();
    await lastValueFrom(this._acquisitionServices.registerArticle(FORM_REQUEST)).then(
      async (responseData: ResponseData) => {
        if ( !responseData.error ) {
          await this._deleteTempFileDelete();
          this.resourcesService.openSnackBar('¡Registro exitoso!');
          this._router.navigate(['/sam/GEAD/PROV/GVPA']);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._registerArticle();
        }
      }
    );
  }
  
  private async _updateArticle () {
    const FORM_REQUEST: FormRequestArticle = this.createObjectResponse();
    const ENC_ARTICLE: string = await this._encService.encrypt(this.idArticle.toString())
    await lastValueFrom(this._acquisitionServices.updateArticle(ENC_ARTICLE, FORM_REQUEST)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar('¡Modificación exitosa!');
          this._router.navigate(['/sam/GEAD/PROV/GVPA']);
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._updateArticle();
        }
      }
    );
  }
  
  public createObjectResponse () : FormRequestArticle {
    
    let CODIGO = this.formGroup.controls['CODIGO'].value;
    CODIGO = CODIGO.toString().trim();

    let ARTICULO = this.formGroup.controls['ARTICULO'].value;
    ARTICULO = ARTICULO.toString().trim();

    let FAMILIA = this.formGroup.controls['FAMILIA'].value;
    FAMILIA = FAMILIA.ID_FAMILIA;
    
    let SUBFAMILIA = this.formGroup.controls['SUBFAMILIA'].value;
    SUBFAMILIA = SUBFAMILIA.ID_SUBFAMILIA;

    let DESCRIPCION_ARTICULO: DataDescriptionArticle[] = this.dataSource.data;
    console.log(DESCRIPCION_ARTICULO);
    
    const REQUEST_FORM: FormRequestArticle = {
      CODIGO: CODIGO,
      ARTICULO: ARTICULO,
      FAMILIA: FAMILIA,
      SUBFAMILIA: SUBFAMILIA,
      DESCRIPCION_ARTICULO: DESCRIPCION_ARTICULO,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
    }
    
    return REQUEST_FORM;
  }

  private async _deleteTempFileDelete () {
    this.resourcesService.openSnackBar(`Eliminando archivos temporales eliminados...`);
    for (const element of this.dataSource.data) {
      if (element.ESTADO === 'Eliminado') {
        for (const elementFiles of element.ARCHIVOS) {
          await this._deleteTempFile(elementFiles.ID);
        }
      }
    }
  }

  private async _deleteTempFile(idArchivo: string) {
    this.isLoading = true;
    
    var myFormData = new FormData();
    myFormData.append('id_file', idArchivo);
    myFormData.append('id_user', this.resourcesService.getUser());
    myFormData.append('linea', this.resourcesService.getLineNumber().toString());

    await lastValueFrom(this._gdelService.deleteTempFile(myFormData)).then(
      async (responseData: ResponseDataUploadTempFile) => {
        if (!responseData.error) {
          /* this.resourcesService.openSnackBar(`¡Eliminación del archivo temporal exitosa!`);
          this.dataSource.data = this.dataSource.data.filter((tempFile: TempFiles) => tempFile.ID !== idArchivo); */
        } else{
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._deleteTempFile(idArchivo);
        }
      }
    );
    this.isLoading = false;
  }
}
