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

const ID_MODULE = "S002V01M05GEAD";
@Component({
    selector: 'app-shopping',
    templateUrl: './shopping.component.html',
    styleUrl: './shopping.component.css',
    standalone: false
})
export class ShoppingComponent implements OnInit {
  public isLoading: boolean;
  public isLoadingForm: boolean;

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

  public quantityShoppingCart: 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<GetProvidersActives>;

  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 _acquisitionServices: AcquisitionService,
    private _router: Router,
    private _encService: EncService,
    private _providerService: ProviderService,
    private _activatedRoute: ActivatedRoute,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    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.quantityShoppingCart = 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));
      }),
    );
  }

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

  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 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']);
    }
  }

  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(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}`);
            }
          }, async (httpErrorResponse: HttpErrorResponse) => {
            let response = this.resourcesService.checkErrors(httpErrorResponse)
            if (response !== null && response.reload) {
              await this.refreshPermissions();
            }
          }
        );
      }
    });

    this._socketService.refreshModules().subscribe(async () => this._functionsService.consultModuleStatus(ID_MODULE));
  }

  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;      
    }
  }

  // Método para obtener la cantidad de productos en el carrito
  public async getQuantityCarArtitle() {
    let storeShoppingCart = localStorage.getItem('shopping_cart');
    if (storeShoppingCart !== null) {
      const decShoppingCart: string = await this._encService.decrypt(storeShoppingCart);
      const arrShoppingCart: Array<DataTableResponse> = JSON.parse(decShoppingCart);
      let quantity = 0;
      arrShoppingCart.map((dataTableResponse: DataTableResponse) => {
        quantity += dataTableResponse.CANTIDAD;
      });
      this.quantityShoppingCart = quantity;
    }
  }
  
  private async getFamilies(){
    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;
          this.familiesStr = [];
          this.arrFamilies.forEach((families:DataFamilies) => {
            this.familiesStr.push(`${families.FAMILIA} (${families.ID_FAMILIA})`);
          });
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getFamilies();
        }
      }
    );
  }
  
  private async getProvider() {
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._providerService.getProviderActives(user, line)).then(
      (responseData: ResponseDataGetProvidersActives) => {
        if (!responseData.error) {
          this.arrProvider = responseData.response;          
          this.providerStr = [];
          this.arrProvider.map((provider: GetProvidersActives) => {
            this.providerStr.push(`(${provider.NUMERO_PROVEEDOR}) ${provider.RAZON_SOCIAL}`);
          });
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getProvider();
        }
      }
    );
  }

  private async getArtitle(){
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionServices.getArtitles(user, line)).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)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getArtitle();
        }
      }
    );    
  }

  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;
  }
  // 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}`]);
  }
}
