import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MatAccordion } from '@angular/material/expansion';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable, lastValueFrom, map, startWith } from 'rxjs';
import { ArtitleResponse, ResponseDataArtitle, ContentArtitle, DataFamilies, ResponseDataFamilies, DataSubfamilies } from 'src/app/interfaces/acquisition-management/artitle.interface';
import { InformationsData, ResponseDataProvider } from 'src/app/interfaces/acquisition-management/provider.interface';
import { PurchasePurpose } from 'src/app/interfaces/acquisition-management/purchase-purpose.interface';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { ArtitleService } from 'src/app/services/acquisition-management/artitle.service';
import { ProviderService } from 'src/app/services/acquisition-management/provider.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { SocketService } from 'src/app/services/socket.service';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { PermissionsData } from '../../acquisition-management.component';

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

  public isLoading: boolean;
  public isLoadingForm: boolean;

  public selectedFamiliesEnabled: boolean;
  public cartShoppingEnabled: boolean;
  public selectedArtitlesEnabled: boolean;

  public quantityCarArtitle: number | null;

  public formGroup: FormGroup;
  
  public filteredOptionsFamily?: Observable<Array<string>>
  public filteredOptionsSubfamily?: Observable<Array<string>>
  public filteredOptionsProvider?: Observable<Array<string>>
  public filteredOptionsArtitle?: Observable<Array<string>>
  
  public arrArtitles: Array<ArtitleResponse>;
  public arrFamilies: Array<DataFamilies>;
  public arrSubfamilies: Array<DataSubfamilies>;
  public arrProvider: Array<InformationsData>;

  public artitlesStr: Array<string>;
  public familiesStr: Array<string>;
  public providerStr: Array<string>;
  public subfamiliesStr: Array<string>;

  private _purchasePurpose: PurchasePurpose;

  @ViewChild(MatAccordion) accordion?: MatAccordion;

  constructor(
    public resourcesService: ResourcesService,
    private _artitleServices: ArtitleService,
    private _router: Router,
    private _encService: EncService,
    private _providerService: ProviderService,
    private _activatedRoute: ActivatedRoute,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
  ) {
    this.isLoading = true;
    this.isLoadingForm = true;
    this.arrArtitles = [];
    this.arrFamilies = [];
    this.arrSubfamilies = [];
    this.arrProvider = [];

    this.artitlesStr = [];
    this.familiesStr = [];
    this.subfamiliesStr = [];
    this.providerStr = [];
    this._purchasePurpose = {} as PurchasePurpose;
    this.formGroup =this.createFormGroup();

    this.selectedFamiliesEnabled = true;
    this.cartShoppingEnabled = true;
    this.selectedArtitlesEnabled = true;

    this.quantityCarArtitle = null;

    this.formGroup.controls['FAMILY'].valueChanges.subscribe((family:string) => {    
      if (family.includes('(') && family.includes(')')) {
        const idFamily:string = family.split('(')[1].split(')')[0];
        this.arrFamilies.forEach((elementFamily: DataFamilies) => {
          if (elementFamily.ID_FAMILIA == idFamily) {            
            this.arrSubfamilies = elementFamily.SUBFAMILIAS;
            this.subfamiliesStr = [];
            this.arrSubfamilies.forEach((elementSubfamily: DataSubfamilies) => {
              this.subfamiliesStr.push(`(${elementSubfamily.ID_SUBFAMILIA}) ${elementSubfamily.SUBFAMILIA}`);
            });
            this.formGroup.controls['SUBFAMILY'].enable();
          }
        });
      } else {
        this.formGroup.controls['SUBFAMILY'].disable();
      }
      
    });

    this.filteredOptionsFamily = this.formGroup.controls['FAMILY'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.familiesStr.filter(item => item.toLowerCase().includes(filterValue));
      }),
    );
    this.filteredOptionsSubfamily = this.formGroup.controls['SUBFAMILY'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.subfamiliesStr.filter(item => item.toLowerCase().includes(filterValue));
      }),
    );
    this.filteredOptionsProvider = this.formGroup.controls['PROVIDER'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.providerStr.filter(item => item.toLowerCase().includes(filterValue));
      }),
    );
    this.filteredOptionsArtitle = this.formGroup.controls['ARTITLE'].valueChanges.pipe(
      startWith(''),
      map(value => {
        value = value === null || value === undefined ? '' : value;
        const filterValue = value.toLowerCase();
        return this.artitlesStr.filter(item => item.toLowerCase().includes(filterValue));
      }),
    );

  }

  async ngOnInit() {
    this.isLoading = true;
    this.isLoadingForm = true;
    await this.setPermissions();
    await this.refreshPermissions();
    await this.getInformationShopping();
    await this.getQuantityCarArtitle();
    await this.getFamilies();
    await this.getProvider();
    await this.getArtitle();
    this.isLoading = false;
    this.isLoadingForm = false;
  }

  private async refreshPermissions() {
    this._socketService.refreshPermissions().subscribe(async (profUpdEnc) => {
      let idUser = localStorage.getItem('idusuario')!;
      let usrInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesSevice.getUser(idUser, idUser, 1));
      let currentProfile = await this._encService.decrypt(localStorage.getItem('perfil')!);

      if(parseInt(currentProfile) != usrInfo.response.PERFIL){
        this._router.navigate(['/sam/home']);
      }

      let profileUpdated = await this._encService.decrypt(`${profUpdEnc}`);
      if(profileUpdated == currentProfile){
        let profile = localStorage.getItem('perfil')!;

        await lastValueFrom(this._usersProfilesSevice.getProfile( profile, idUser, 1 )).then(
          (responseData: ProfileInterface) => {
            if (!responseData.error) {
              let modPerm = responseData.response.PERMISOS.permissions.filter(item => item.id == 'S002V01M05GEAD')[0];
              let funPerm = modPerm.children.filter(item => item.id == 'S002V01S01ADQU')[0];
              let panPerm = funPerm.children.filter(item => item.id == "S002V01F01NSCO")[0];

              this.selectedFamiliesEnabled = panPerm.children.filter(item => item.id == 'S002V01P02SFSU')[0].access > 0;
              this.cartShoppingEnabled = panPerm.children.filter(item => item.id == 'S002V01P04BOLS')[0].access > 0;
              this.selectedArtitlesEnabled = panPerm.children.filter(item => item.id == 'S002V01P03SEAR')[0].access > 0;

              if (panPerm.access === 0) {
                this._router.navigate(['/sam/home']);
              }

            } else {
              this.resourcesService.openSnackBar(`${responseData.msg}`);
            }
          }, ( httpErrorResponse: HttpErrorResponse ) => this.resourcesService.checkErrors(httpErrorResponse)
        );
      }
    });
  }

  private async setPermissions() {
    const encPermissions = localStorage.getItem('permisos');
    if (encPermissions === null || encPermissions === undefined || encPermissions === '') {
      this.resourcesService.openSnackBar(`Ocurrió un error al obtener los permisos del usuario.`);
      this._router.navigate(['/sam/home']);
      return;
    }
    const strPermissions:string = await this._encService.decrypt(encPermissions);
    const arrPermissions:Array<PermissionsData> = JSON.parse(strPermissions).permissions;

    let modPerm = arrPermissions.filter(item => item.id == 'S002V01M05GEAD')[0];
    let funPerm = modPerm.children.filter(item => item.id == 'S002V01S01ADQU')[0];
    let panPerm = funPerm.children.filter(item => item.id == "S002V01F01NSCO")[0];

    this.selectedFamiliesEnabled = panPerm.children.filter(item => item.id == 'S002V01P02SFSU')[0].access > 0;
    this.cartShoppingEnabled = panPerm.children.filter(item => item.id == 'S002V01P04BOLS')[0].access > 0;
    this.selectedArtitlesEnabled = panPerm.children.filter(item => item.id == 'S002V01P03SEAR')[0].access > 0;

    if (panPerm.access === 0) {
      this._router.navigate(['/sam/home']);
    }
  }

  public async getInformationShopping() {
    let getInformation = this._activatedRoute.snapshot.paramMap.get('info');
    if (getInformation !== null ) {
      getInformation = await this._encService.decrypt(getInformation);
      const purchasePurpose = JSON.parse(getInformation);
      this._purchasePurpose = purchasePurpose;      
    }
  }

  private createFormGroup() {
    return new FormGroup({
      FAMILY: new FormControl(''),
      SUBFAMILY: new FormControl({value:'', disabled: true}),
      PROVIDER: new FormControl(''),
      ARTITLE: new FormControl(''),
    });
  }

  private async getArtitle(){
    await lastValueFrom(this._artitleServices.getArtitles()).then(
      (responseData: ResponseDataArtitle) => {
        if (!responseData.error) {
          this.arrArtitles = responseData.response;          
          this.artitlesStr = [];
          this.arrArtitles.forEach((artitles:ArtitleResponse) => {
            this.artitlesStr.push(`${artitles.MODELO}`);
          });
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );    
  }
  private async getFamilies(){
    await lastValueFrom(this._artitleServices.getFamiliesAndSubfamilies()).then(
      (responseData: ResponseDataFamilies) => {
        if (!responseData.error) {
          this.arrFamilies = responseData.response;
          this.familiesStr = [];
          this.arrFamilies.forEach((families:DataFamilies) => {
            this.familiesStr.push(`${families.FAMILIA} (${families.ID_FAMILIA})`);
          });
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }
  public getSubfamily() {
    const family:string = this.formGroup.controls['FAMILY'].value;
    if (family.includes('(') && family.includes(')')) {
      const idFamily:string = family.split('(')[1].split(')')[0];
      this.arrFamilies.forEach((elementFamily: DataFamilies) => {
        if (elementFamily.ID_FAMILIA === idFamily) {          
          this.arrSubfamilies = elementFamily.SUBFAMILIAS;
          this.subfamiliesStr = [];
          this.arrSubfamilies.forEach((elementSubfamily: DataSubfamilies) => {
            this.subfamiliesStr.push(`(${elementSubfamily.ID_SUBFAMILIA}) ${elementSubfamily.SUBFAMILIA}`);
          });
          this.formGroup.controls['SUBFAMILY'].enable();
        }
      });
    }
  }
  private async getProvider() {
    await lastValueFrom(this._providerService.getProviderActives()).then(
      (responseData: ResponseDataProvider) => {
        if (!responseData.error) {
          this.arrProvider = responseData.response;          
          this.providerStr = [];
          this.arrProvider.map((provider: InformationsData) => {
            this.providerStr.push(`(${provider.PROV_NUPR}) ${provider.PROV_NOCO}`);
          });
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
  }

  public async setFilter() {
    this.isLoadingForm = true;
    await this.getArtitle();
    let arrArtitleFilter: Array<ArtitleResponse> = [... this.arrArtitles];    

    let family:string = this.formGroup.controls['FAMILY'].value;
    let subfamily:string = this.formGroup.controls['SUBFAMILY'].value;
    let provider:string = this.formGroup.controls['PROVIDER'].value;
    let artitle:string = this.formGroup.controls['ARTITLE'].value;

    // Se filtran por las familias
    if (family !== '' && family !== null) {
      if ( family.includes('(') && family.includes(')') ) {
        const idFamily:string = family.split('(')[1].split(')')[0];
        arrArtitleFilter = arrArtitleFilter.filter((artitleFilter:ArtitleResponse) => artitleFilter.ID_FAMILIA == idFamily);
      } else {
        provider = provider.toString().trim().toLowerCase();
        arrArtitleFilter = arrArtitleFilter.filter((artitleFilter:ArtitleResponse) => artitleFilter.FAMILIA.toLowerCase().includes(provider));
      }
    }
    
    // Se filtran por las subfamilias
    if (subfamily !== '' && subfamily !== null) {
      if (subfamily.includes('(') && subfamily.includes(')')) {
        const idSubfamily:string = subfamily.split('(')[1].split(')')[0];
        arrArtitleFilter = arrArtitleFilter.filter((artitleFilter:ArtitleResponse) => artitleFilter.ID_SUBFAMILIA == idSubfamily);
      } else {
        subfamily = subfamily.toString().trim().toLowerCase();
        arrArtitleFilter = arrArtitleFilter.filter((artitleFilter:ArtitleResponse) => artitleFilter.SUBFAMILIA.toLowerCase().includes(subfamily));
      }
    }
    
    // Se filtran por los proveedores
    if (provider !== '' && provider !== null) {
      if ( provider.includes('(') && provider.includes(')') ) {
        const idProvider:string = provider.split('(')[1].split(')')[0];
        arrArtitleFilter = arrArtitleFilter.filter((artitleFilter:ArtitleResponse) => artitleFilter.ID_PROVEEDOR == idProvider);
      } else {
        provider = provider.toString().trim().toLowerCase();
        arrArtitleFilter = arrArtitleFilter.filter((artitleFilter:ArtitleResponse) => artitleFilter.PROVEEDOR.toLowerCase().includes(provider));
      }
    }

    // Se filtran por el módelo del artículo
    if (artitle !== '' && artitle !== null) {
      artitle = artitle.toString().trim().toLowerCase();
      arrArtitleFilter = arrArtitleFilter.filter((artitleFilter:ArtitleResponse) => artitleFilter.MODELO.toLowerCase().includes(artitle));
    }

    this.arrArtitles = arrArtitleFilter;
    this.accordion?.closeAll();
    this.isLoadingForm = false;
  }
  public async removeFilter() {
    this.isLoadingForm = true;
    await this.getArtitle();
    this.formGroup.reset();
    this.arrSubfamilies = [];
    this.subfamiliesStr = [];
    this.formGroup.controls['SUBFAMILY'].disable();
    this.accordion?.closeAll();
    this.isLoadingForm = false;
  }

  // Método para obtener la cantidad de productos en el carrito
  public async getQuantityCarArtitle() {
    // Se obtiene los datos del localstorage del carrito de compra
    let localStorageCar = localStorage.getItem('car_shopping_artitles');
    // Se valida que la variable se encuentre en el localstorage
    let strItemsCar:string = localStorageCar !== null && localStorageCar !== undefined ?  localStorageCar : '';
    // Se verifica si hay articulos en el localstorage
    if (strItemsCar?.length === 0) {
      // Se coloca la cantidad como null
      this.quantityCarArtitle = null!;
    }else{
      // Se desencripta la cadena obtenida por el localstorage
      let decArtitlesSelected: string = await this._encService.decrypt(strItemsCar);
      // Se transforma a un arreglo los datos guardados del localstorage
      let arrCarShopping: Array<ContentArtitle> = JSON.parse(decArtitlesSelected);

      console.log(arrCarShopping);
      
      let countArtitles: number = 0;
      // Se ingresa la cantidad a la variable global
      arrCarShopping.map( (element:ContentArtitle) => {
        countArtitles += element.content.length;
      });

      if (countArtitles > 0) {
        this.quantityCarArtitle = countArtitles;
      }
    }
  }
  // Abrir un Artículo
  public async openArtitle(artitle:ArtitleResponse){
    // Se transforma en string los datos del artículo
    const strIdArtitle:string = artitle.ID_DESC_ARTI;
    // Se encripta la información
    const encIdArtitle = await this._encService.encrypt(`${strIdArtitle}`);

    // Se transforma en string los datos del proveedor
    const strIdProvider:string = artitle.ID_PROVEEDOR;
    // Se encripta la información
    const encIdProveedor = await this._encService.encrypt(`${strIdProvider}`);


    const strPurchasePurpose:string = JSON.stringify(this._purchasePurpose);
    const encPurchasePurpose:string = await this._encService.encrypt(strPurchasePurpose);

    // Redirigir a la ruta con el ID Encriptado
    this._router.navigate([ `/sam/GEAD/ADQU/CGPE/information/${encIdArtitle}/${encIdProveedor}/${encPurchasePurpose}` ]);
  }
  public async openShoppingCart() {
    const strPurchasePurpose: string = JSON.stringify(this._purchasePurpose);
    const encPurchasePurpose: string = await this._encService.encrypt(strPurchasePurpose);
    this._router.navigate([`/sam/GEAD/ADQU/CGPE/shopping-cart/${encPurchasePurpose}`]);
  }

}
