import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { DataFamilies, DataFormDetails, DataMoneda, DataSubfamilies, DetailsArtitle, InformationArtitle, ResponseArtitle, ResponseDataFamilies, ResponseDataGetArtitleById, ResponseDetails, ResponseFormDetails, ResponseInformation, TypeForm } from 'src/app/interfaces/acquisition-management/artitle.interface';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { ArtitleService } from 'src/app/services/acquisition-management/artitle.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { ArtitleDetailsFormComponent } from '../artitle-details-form/artitle-details-form.component';
import { ArtitleDescriptionFormComponent } from '../artitle-description-form/artitle-description-form.component';
import { ArtitleDetailsComponent } from '../artitle-details/artitle-details.component';
import { ActivatedRoute, Router } from '@angular/router';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResponseData } from 'src/app/interfaces/response-data';
import { UploadFilesService } from 'src/app/services/upload-files.service';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { ResponseDataUploadTempFile } from 'src/app/interfaces/gdel.interface';

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

  public isLoading:boolean;
  public isLoadingForm:boolean;

  public dataSourceInformation: MatTableDataSource<InformationArtitle>;
  public displayedColumnsInformation: Array<string>;
  public arrFamilies: Array<DataFamilies>;
  public arrSubfamilies: Array<DataSubfamilies>;
  public arrProvider: Array<ResponseArtitle>;
  public arrCatalogoMonedas: Array<DataMoneda>;
  public arrDeleteFiles: Array<string>;
  public arrArtitle: Array<any>;

  public formGroup: FormGroup;
  public typeForm:TypeForm;

  constructor(
    public resourcesService: ResourcesService,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _resourcesService: ResourcesService,
    private _artitleServices: ArtitleService,
    private _activatedRouter: ActivatedRoute,
    private _router: Router,
    private _uploadFilesService: UploadFilesService,
    private _gdelService: GdelService,
  ) {
    this.typeForm = {} as TypeForm;
    this.displayedColumnsInformation = ['IMAGEN','PROVEEDOR','DESCRIPCION','CARACTERISTICAS','CANTIDAD_DETALLES','ESTADO','ACCIONES'];
    this.dataSourceInformation = new MatTableDataSource<InformationArtitle>();
    this.formGroup = this.createFormGroup();

    this.isLoading = false;
    this.isLoadingForm = true;

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

  }

  async ngOnInit() {
    await this.getFamiliesAndSubfamilies();
    await this.getDataForm();
  }

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

  private async getDataForm() {
    this.isLoading = true;
    this.isLoadingForm = true;
    let encForm:string = this._activatedRouter.snapshot.paramMap.get('form')!;
    let strForm:string = await this._encService.decrypt(encForm);
    this.typeForm = JSON.parse(strForm);

    if (this.typeForm.type === 'EDIT') {
      this.getArtitleById(this.typeForm.element!.ID_ARTICULO);
    }else{
      this.isLoading = false;
      this.isLoadingForm = false;
    }
  }

  private async setFormData(artitle:ResponseArtitle) {
    this.isLoading = true;
    this.isLoadingForm = true;

    this.formGroup.controls['NO'].setValue(artitle.NUMERO_ARTICULO);
    this.formGroup.controls['CODIGO'].setValue(artitle.CODIGO);
    this.formGroup.controls['CODIGO'].setValue(artitle.CODIGO);
    this.formGroup.controls['ARTICULO'].setValue(artitle.ARTICULO);
    let family = this.arrFamilies.find((family: DataFamilies) => family.ID_FAMILIA === artitle.ID_FAMILIA );
    this.formGroup.controls['FAMILIA'].setValue(family);
    let subfamily = family?.SUBFAMILIAS.find((subfamilia: DataSubfamilies) => subfamilia.ID_SUBFAMILIA === artitle.ID_SUBFAMILIA );
    this.formGroup.controls['SUBFAMILIA'].setValue(subfamily);
    
    artitle.INFORMACION.map((information: ResponseInformation) => {      
      
      let arrDetailsInformation: Array<DetailsArtitle> = [];
      information.DETALLES.map((details:ResponseDetails) => {
        arrDetailsInformation.push({
          NO: details.NUMERO_DETALLE,
          CODIGO: details.CODIGO,
          MODELO: details.MODELO,
          MONEDA: details.MONEDA,
          PRECIO: details.PRECIO,
          MONTO_MINIMO: details.MONTO_MINIMO,
          ESTADO: details.ESTADO,
          CARACTERISTICAS: details.CARACTERISTICAS
        });
      });
      
      let strCaracteristicas:string = ''
      if (information.CARACTERISTICAS !== null) {
        strCaracteristicas = information.CARACTERISTICAS
      } 
      this.dataSourceInformation.data.push({
        NO: information.ID_DESCRIPCION,
        IMAGEN: information.IMAGEN,
        DATA_IMAGEN: [],
        DELETE_FILE: [],
        DESCRIPCION: information.DESCRIPCION,
        CARACTERISTICAS: strCaracteristicas,
        TIPO_UNIDAD: information.TIPO_UNIDAD,
        PROVEEDOR: information.PROVEEDOR,
        COMPRA_WEB: information.COMPRA_WEB,
        ESTADO: information.ESTADO,
        DETAILS: arrDetailsInformation
      })
    });

    this.dataSourceInformation.data = this.dataSourceInformation.data;

    this.isLoading = false;
    this.isLoadingForm = false;
  }


  public getSubfamily(){
    let family:DataFamilies = this.formGroup.controls['FAMILIA'].value;
    this.arrSubfamilies = family.SUBFAMILIAS;
    this.formGroup.controls['SUBFAMILIA'].enable();
  }

  public openDialog(type:string, elementData?:any) {
    // Abrir el formulario de información
    if (type === 'FORM_INFO') {
      this._dialog.open(ArtitleDescriptionFormComponent, {
        disableClose: true,
        width: '450px',
        data: {
          dataSource: this.dataSourceInformation.data,
          elementData: elementData,
        },
      }).afterClosed().subscribe((result:InformationArtitle) => {
        this._uploadFilesService.arr$.next([]);

        // Se registra nuevo dato
        if (result && elementData === undefined ) {
          
          let dataSource:Array<InformationArtitle> = this.dataSourceInformation.data;
          result.NO = (this.dataSourceInformation.data.length + 1).toString();
          dataSource.push(result);
          this.dataSourceInformation.data = dataSource;
          
        // Se modifica un registro
        } else if (result && elementData !== undefined) {
          
          this.dataSourceInformation.data = this.dataSourceInformation.data.map((elementInformation: InformationArtitle) => {
            if (elementInformation.NO === elementData.NO) {
              elementInformation = result;
            }
            return elementInformation;
          });

          if (result.DELETE_FILE!.length > 0) {
            result.DELETE_FILE.forEach((element:string) => {
              this.arrDeleteFiles.push(element);
            });            
          } 
        }
      });
    // Abrir la alerta de la eliminación de información
    } else if (type === 'ELIM_INFO') {
      let objElement: AlertData = { title: 'Eliminar Información', description: '¿Está seguro de eliminar esta información?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data:objElement
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.dataSourceInformation.data = this.dataSourceInformation.data.map(
            (element:InformationArtitle) => {
              if (element.NO === elementData.NO) {
                element.ESTADO = 'Eliminado';
              }
              return element;
            }
          );
        }
      });
    } else if (type === 'REST_INFO') {
      let objElement: AlertData = { title: 'Restaurar Información', description: '¿Está seguro de restaurar esta información?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data:objElement
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.dataSourceInformation.data = this.dataSourceInformation.data.map(
            (element:InformationArtitle) => {
              if (element.NO === elementData.NO) {
                element.ESTADO = 'Activo';
              }
              return element;
            }
          );
        }
      });
    // Abre el formulario de detalles
    } else if (type === 'FORM_DETAILS') {
      let objElement: DataFormDetails = { element: elementData.element, itemElement: elementData.itemElement }
      this._dialog.open(ArtitleDetailsFormComponent, {
        disableClose: true,
        width: '450px',
        data: objElement,
      }).afterClosed().subscribe((result) => {
        this.openDialog('DETAILS', result);
      });
    // Abrir la alerta de la eliminación de detalle
    } else if (type === 'ELIM_DETAILS') {
      let objElement: AlertData = { title: 'Eliminar Detalle', description: '¿Está seguro de eliminar el detalle?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data:objElement
      }).afterClosed().subscribe((result) => {
        let tableInformation:InformationArtitle = elementData.element;
        if (result) {
          let arrTableInformation: Array<DetailsArtitle> = tableInformation.DETAILS.map(
            (element:DetailsArtitle) => {
              if (element.NO === elementData.itemElement.NO) {
                element.ESTADO = 'Eliminado';
              }
              return element;
            }
          );
          tableInformation.DETAILS = arrTableInformation;
        }
        this.openDialog('DETAILS', tableInformation);
      });
    } else if (type === 'REST_DETAILS') {
      let objElement: AlertData = { title: 'Restaurar Detalle', description: '¿Está seguro de restaurar el detalle?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data:objElement
      }).afterClosed().subscribe((result) => {
        let tableInformation:InformationArtitle = elementData.element;
        if (result) {
          let arrTableInformation: Array<DetailsArtitle> = tableInformation.DETAILS.map(
            (element:DetailsArtitle) => {
              if (element.NO === elementData.itemElement.NO) {
                element.ESTADO = 'Activo';
              }
              return element;
            }
          );
          tableInformation.DETAILS = arrTableInformation;
        }
        this.openDialog('DETAILS', tableInformation);
      });
    // Abrir el dialogo de consulta de detalles
    } else if (type === 'DETAILS') {
      this._dialog.open(ArtitleDetailsComponent, {
        disableClose: true,
        width: '800px',
        data: elementData,
      }).afterClosed().subscribe((result:ResponseFormDetails) => {
        if (result.typeForm === 'FORM_DETAILS') {
          let objElement = { element: result.element, itemElement: result.itemElement }
          this.openDialog(result.typeForm, objElement);
        } else if (result.typeForm === 'CLOSE') {
          let elementDataResult: InformationArtitle = result.element;
          this.dataSourceInformation.data = this.dataSourceInformation.data.map((element:InformationArtitle) => {
            if (element.NO === elementDataResult.NO){
              element = elementDataResult;
            }
            return element;
          });
        } else if (result.typeForm === 'ELIM_DETAILS') {
          let objElement = {
            element: result.element,
            itemElement: result.itemElement
          }
          this.openDialog(result.typeForm, objElement);
        } else if (result.typeForm === 'REST_DETAILS') {
          let objElement = {
            element: result.element,
            itemElement: result.itemElement
          }
          this.openDialog(result.typeForm, objElement);
        }
      });
    } else if (type === 'REGI') {
      let objElement: AlertData = { title: 'Registro de artículo', description: '¿Está seguro de registrar el artículo?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: objElement
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.register();
        }
      });
    } else if (type === 'EDIT') {
      let objElement: AlertData = { title: 'Modificación de artículo', description: '¿Está seguro de modificar el artículo?', icon: 'warning' };
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: objElement
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.update();
        }
      });
    }
  }

  public countDetails(arrDetails:Array<DetailsArtitle>){
    let count:number = 0;
    arrDetails.map((element:DetailsArtitle) => {
      if (element.ESTADO !== 'Eliminado') {
        count++;
      }
    });
    let response: string = '';
    if (count === 0) {
      response = 'Sin detalles';
    } else if (count === 1) {
      response = '1 Detalle';
    } else {
      response = count + ' Detalles';
    }
    return response;
  }

  public checkValidation(): boolean {
    if (this.formGroup.valid) {
      if (this.dataSourceInformation.data.length > 0) {
        return !this.dataSourceInformation.data.every((element:InformationArtitle) => element.DETAILS.length > 0);
      } else {
        return true;
      }
    }else{
      return true;
    }
  }

  public setImage (element:InformationArtitle) {
    
    let imageSelected: string = 'assets/img/empty_data.svg';

    if (element.DATA_IMAGEN.length > 0) {
      imageSelected = element.DATA_IMAGEN[0].view;      
    } else {
      imageSelected = element.IMAGEN[0];      

    }
    return imageSelected;
  }

  public setAlt (element:InformationArtitle) {
    let altSelected: string = '';
    if (element.DATA_IMAGEN.length > 0) {
      altSelected = element.DATA_IMAGEN[0].view;      
    } else {
      altSelected = element.IMAGEN[0];      

    }

    return altSelected;
  }

  private async getArtitleById(idArtitle:string) {
    this.isLoading = true;
    this.isLoadingForm = true;

    const encIdArtitle: string = await this._encService.encrypt(idArtitle.toString());
    await lastValueFrom(this._artitleServices.getArtitleById(encIdArtitle)).then(
      async (responseData:ResponseDataGetArtitleById) => {
        if (!responseData.error) {
          await this.setFormData(responseData.response);
        } else { 
          this.resourcesService.openSnackBar(responseData.msg);
        }
      },
      (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  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 register() {
    const objectRegister = await this.createObjectResponse();
    await lastValueFrom(this._artitleServices.registerArtitle(objectRegister)).then(
      (responseData: ResponseData) => {
        if ( !responseData.error ) {
          this.resourcesService.openSnackBar('¡Registro Exitoso!');
          this._router.navigate(['/sam/GEAD/PROV/GVPA']);
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  private async update() {    
    const objectUpdate = await this.createObjectResponse();
    await lastValueFrom(this._artitleServices.updateArtitle(objectUpdate)).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);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );

    if (this.arrDeleteFiles.length > 0) {
      this.arrDeleteFiles.forEach(element => {
        this.deleteFile(element);
      });
    }
  }

  private async deleteFile(encCode:string) {
    this.isLoadingForm  = true;

    var myFormData = new FormData();
    myFormData.append('id_file', encCode);
    myFormData.append('id_user', this.resourcesService.getUser());
    myFormData.append('linea', this.resourcesService.getLineNumber());

    await lastValueFrom(this._gdelService.deleteFile(myFormData)).then(
      (responseData: ResponseDataUploadTempFile) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar('¡Archivo Eliminado Exitosamente!');
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoadingForm  = false;
  }

  public async createObjectResponse () {
    let arrObjInformation: Array<any> = [];
    for (let key = 0; key < this.dataSourceInformation.data.length; key ++) {
      let elementInformation:InformationArtitle = this.dataSourceInformation.data[key];

      let arrObjDetails: Array<any> = [];
      elementInformation.DETAILS.map((elementDetails:DetailsArtitle) => {
        // Se obtiene el código de la moneda seleccionada
        let coin: string = elementDetails.MONEDA.substring(1, 4);
    
        arrObjDetails.push({
          NO: (elementDetails.NO).toString().trim(),
          CODIGO: (elementDetails.CODIGO).toString().trim(),
          MODELO: (elementDetails.MODELO).toString().trim(),
          MONEDA: coin,
          PRECIO: (elementDetails.PRECIO).toString().trim(),
          MONTO_MINIMO: (elementDetails.MONTO_MINIMO).toString().trim(),
          ESTADO: (elementDetails.ESTADO).toString().trim(),
          CARACTERISTICAS: (elementDetails.CARACTERISTICAS).toString().trim(),
        });
      });
      
      arrObjInformation.push({
        NO: elementInformation.NO,
        IMAGEN: elementInformation.IMAGEN,
        DESCRIPCION: (elementInformation.DESCRIPCION).toString().trim(),
        CARACTERISTICAS: elementInformation.CARACTERISTICAS === '' ? null : (elementInformation.CARACTERISTICAS!).toString().trim(),
        TIPO_UNIDAD: elementInformation.TIPO_UNIDAD,
        PROVEEDOR: elementInformation.PROVEEDOR.PROV_NUPR,
        COMPRA_WEB: elementInformation.COMPRA_WEB,
        ESTADO: elementInformation.ESTADO,
        DETAILS: arrObjDetails,
      });
    }

    let objectResponse = {
      ARTICULO: (this.formGroup.controls['ARTICULO'].value).toString().trim(),
      CODIGO: (this.formGroup.controls['CODIGO'].value).toString().trim(),
      INFORMATION: arrObjInformation,
      NO: (this.formGroup.controls['NO'].value).toString().trim(),
      FAMILIA: this.formGroup.controls['FAMILIA'].value.ID_FAMILIA,
      SUBFAMILIA: this.formGroup.controls['SUBFAMILIA'].value.ID_SUBFAMILIA,
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: '1',
    }
    
    return objectResponse;
  }

  

}

