import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ContentArtitle, CreateRequestLineToShoppingCart, DataTableResponse, ResponseDataLine, ShoppingCart } from '../../../../../interfaces/acquisition-management/artitle.interface';
import { PreventiveWorkOrdersActive, PreventiveWorkOrdersActiveResponse } from '../../../../../interfaces/preventive-work-orders-active.interface';
import { PurchasePurpose } from '../../../../../interfaces/acquisition-management/purchase-purpose.interface';
import { ResourcesService } from '../../../../../services/resources.service';
import { ActivatedRoute, Router } from '@angular/router';
import { EncService } from '../../../../../services/enc.service';
import { AcquisitionService } from '../../../../../services/acquisition-management/acquisition.service';
import { MatDialog } from '@angular/material/dialog';
import { PreventiveMaintenanceService } from '../../../../../services/preventive-maintenance.service';
import { SocketService } from '../../../../../services/socket.service';
import { UsersProfilesService } from '../../../../../services/users-profiles.service';
import { UserConsultResponse } from '../../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../../interfaces/profile.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { PermissionsData } from '../../../acquisition-management.component';
import { AlertComponent } from '../../../../resources/dialogs/alert/alert.component';
import { ObjectRequestLine } from '../../../../../interfaces/acquisition-management/order.interface';
import { ViewDetailsLineComponent } from '../view-details-line/view-details-line.component';
import { FunctionsService } from '../../../../../services/functions.service';

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

  // Variables de la tabla
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public dataSource: MatTableDataSource<ShoppingCart>;
  
  public displayedColumns: Array<string>;
  public arrShoppingCart: Array<ContentArtitle>;
  public arrPreventiveMaintenance: Array<PreventiveWorkOrdersActive>;
  public arrCorrectiveMaintenance: Array<any>;

  public purchasePurpose: PurchasePurpose;

  public titleCard:string;
  public selectedProject: string;

  public cartShoppingEnabled: boolean;
  public createGroupEnable: boolean;
  public selectedArtitleEnable: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _router: Router,
    private _encService: EncService,
    private _orderServices: AcquisitionService,
    private _dialog: MatDialog,
    private _preventiveMaintenanceService: PreventiveMaintenanceService,
    private _activatedRoute: ActivatedRoute,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.isLoading = false;
    this.isLoadingForm = false;
    this.cartShoppingEnabled = true;
    this.createGroupEnable = true;
    this.selectedArtitleEnable = true;
    this.dataSource = new MatTableDataSource<ShoppingCart>();
    this.arrShoppingCart = [];
    this.arrPreventiveMaintenance = [];
    this.arrCorrectiveMaintenance = [];
    this.displayedColumns = [
      'IMAGENES',
      'PROVEEDOR',
      'ARTICULO',
      'MODELO',
      'CODIGO',
      'PRECIO',
      'CANTIDAD',
      'PRECIOTOTAL',
      'ACCIONES'
    ];
    this.purchasePurpose = {} as PurchasePurpose;
    this.selectedProject = '';
    this.titleCard = '';
  }

  async ngOnInit() {
    await this.refreshPermissions();
    await this.setPermissions();
    await this.getInformationShopping();
    await this.getShoppingCart();
    await this.getPreventiveMaintenance();
  }

  ngAfterViewInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  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 panPerm1 = funPerm.children.filter(item => item.id == "S002V01F01NSCO")[0];
              this.cartShoppingEnabled = panPerm1.children.filter(item => item.id == 'S002V01P04BOLS')[0].access > 0;
              this.selectedArtitleEnable = panPerm1.children.filter(item => item.id == 'S002V01P03SEAR')[0].access > 0;
              
              let panPerm2 = funPerm.children.filter(item => item.id == "S002V01F02CGPE")[0];
              this.createGroupEnable = panPerm2.children.filter(item => item.id == 'S002V01P01AOCO')[0].access > 0;

              if (panPerm2.access !== 2) {
                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));
  }

  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 panPerm1 = funPerm.children.filter(item => item.id == "S002V01F01NSCO")[0];
    this.cartShoppingEnabled = panPerm1.children.filter(item => item.id == 'S002V01P04BOLS')[0].access > 0;
    this.selectedArtitleEnable = panPerm1.children.filter(item => item.id == 'S002V01P03SEAR')[0].access > 0;
    
    let panPerm2 = funPerm.children.filter(item => item.id == "S002V01F02CGPE")[0];
    this.createGroupEnable = panPerm2.children.filter(item => item.id == 'S002V01P01AOCO')[0].access > 0;


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

  }

  public async getInformationShopping() {
    const encInformation:string = this._activatedRoute.snapshot.paramMap.get('info')!;
    const strInformation:string = await this._encService.decrypt(encInformation);
    this.purchasePurpose = JSON.parse(strInformation);  

    switch (this.purchasePurpose.PROPOSITO) {
      case 'MANT-CORR':
        this.titleCard = ` para Mantenimiento Correctivo #${this.purchasePurpose.ID}`;
      break;
      case 'MANT-PREV':
        this.titleCard = ` para Mantenimiento Preventivo #${this.purchasePurpose.ID}`;
      break;
      case 'NA':
        this.titleCard = ``;
      break;
    }
  }

  public async getShoppingCart() {
    const storeShoppingCart = localStorage.getItem('shopping_cart');
    if (storeShoppingCart === null) {
      this.dataSource.data = [];
      return;
    }
    const decShoppingCart: string = await this._encService.decrypt(storeShoppingCart);
    const arrShoppingCart:Array<ShoppingCart> = JSON.parse(decShoppingCart); 
    this.dataSource.data = arrShoppingCart;
  }

  private async getPreventiveMaintenance() {
    this.isLoading = true;
    const idUser:string = this.resourcesService.getUser();
    const line:number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._preventiveMaintenanceService.getActiveWorkOrders(idUser, line)).then(
      (responseData: PreventiveWorkOrdersActiveResponse) => {
        if ( !responseData.error ) {
          this.arrPreventiveMaintenance = responseData.response;
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getPreventiveMaintenance();
        }
      }
    );
    this.isLoading = false;
  }

  public async goShopping() {
    let strPurchasePurpose:string = JSON.stringify(this.purchasePurpose);
    let encPurchasePurpose:string = await this._encService.encrypt(strPurchasePurpose);
    this._router.navigate([`/sam/GEAD/PROV/SOPR/${ encPurchasePurpose }`]);
  }

  public async alert(type: string, shoppingCart?: ShoppingCart) {
    this.isLoadingForm = true;
    if (type === 'DELETE' && shoppingCart !== undefined) {
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          icon: "warning",
          title: "Eliminar artículo",
          description: "¿Está seguro de eliminar el artículo del carrito de compra?"
        },
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.deleteArtitle(shoppingCart);
        }
      });
    }else if(type === 'CREATE') {
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          icon: "warning",
          title: "Registro de línea de solicitud",
          description: "¿Está seguro de registrar los artículos a la línea de solicitud de compra?"
        },
      }).afterClosed().subscribe((result) => {
        if( result ){
          this.registerRequestLine();
        }
      });
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible.`);
    }
    this.isLoadingForm = false;
  }
  
  public async deleteArtitle(shoppingCart: ShoppingCart) {
    let arrShoppingCart: Array<ShoppingCart> = this.dataSource.data.filter((element: ShoppingCart) => 
      !(element.NUMERO_ARTICULO === shoppingCart.NUMERO_ARTICULO &&
      element.NUMERO_DESCRIPCION === shoppingCart.NUMERO_DESCRIPCION &&
      element.NUMERO_INFORMACION === shoppingCart.NUMERO_INFORMACION &&
      element.NUMERO_PROVEEDOR === shoppingCart.NUMERO_PROVEEDOR)
    );

    this.dataSource.data = arrShoppingCart;
    if (arrShoppingCart.length === 0) {
      localStorage.removeItem('shopping_cart');
    } else {
      const strShoppingCart:string = JSON.stringify(arrShoppingCart);
      const encShoppingCart:string = await this._encService.encrypt(strShoppingCart);
      localStorage.setItem('shopping_cart', encShoppingCart);
    }
    this.resourcesService.openSnackBar(`Artículo Eliminado`);

  }

  private async registerRequestLine() {
    this.isLoading = true;
    
    const arrRequestLine: Array<CreateRequestLineToShoppingCart> = this.createArrayShoppingCart();
    if(arrRequestLine.length <= 0){
      this.resourcesService.openSnackBar('Aún no se ha agregado ningún producto al carrito de artículos.');
    }else{
      const objRequestLine: ObjectRequestLine = {
        LINE: this.resourcesService.getLineNumber(),
        USER: this.resourcesService.getUser(),
        PRODUCTS: arrRequestLine,
        PURPOSE: this.purchasePurpose,
      };
      
      await lastValueFrom(this._orderServices.createRequestLine(objRequestLine)).then(
        (responseData: ResponseDataLine) => {
          if (!responseData.error) {
            this.resourcesService.openSnackBar('¡La línea de solicitud se registró correctamente!');
            localStorage.removeItem('shopping_cart');
            this._router.navigate(['/sam/GEAD/ADQU/NSCO']);
          } else {
            this.resourcesService.openSnackBar('Ocurrió un error inesperado: ' + responseData.msg);
          }
        }, async (httpErrorResponse: HttpErrorResponse) => {
          let response = this.resourcesService.checkErrors(httpErrorResponse)
          if (response !== null && response.reload) {
            await this.registerRequestLine();
          }
        }
      );
    }
    
    this.isLoading = false;
  }

  public createArrayShoppingCart(): Array<CreateRequestLineToShoppingCart> {
    let requestLineShopping: Array<CreateRequestLineToShoppingCart> = [];
    this.dataSource.data.map((shoppingCart: ShoppingCart) => {
      for (let index = 0; index < shoppingCart.CANTIDAD; index++) {
        requestLineShopping.push({
          NUMERO_ARTICULO: shoppingCart.NUMERO_ARTICULO,
          NUMERO_PROVEEDOR: shoppingCart.NUMERO_PROVEEDOR,
          NUMERO_INFORMACION: shoppingCart.NUMERO_INFORMACION,
        });
      }
    });
    return requestLineShopping;
  }

  public async quantityProducts(accion: 'suma' | 'resta', data: any) {
    this.dataSource.data.map( (element:ShoppingCart) => {
      if (element.NUMERO_INFORMACION === data.NUMERO_INFORMACION && accion == 'suma') {
        element.CANTIDAD ++;
      }else if (element.NUMERO_INFORMACION === data.NUMERO_INFORMACION && accion == 'resta') {
        element.CANTIDAD --;
      }
    });

    const strShoppingCart:string = JSON.stringify(this.dataSource.data);
    const encShoppingCart:string = await this._encService.encrypt(strShoppingCart);
    localStorage.setItem('shopping_cart', encShoppingCart);
  }

  public async setQuantity(cantidad: number, dataElemenet: ShoppingCart){    
    if (cantidad < 0 ) {
      this.dataSource.data.map((element:any) => {
        if (element.NUMERO_INFORMACION === dataElemenet.NUMERO_INFORMACION) {
          element.CANTIDAD = 0;
        }
      });
    } else if (cantidad > 9999 ) {
      this.dataSource.data.map((element:any) => {
        if (element.NUMERO_INFORMACION === dataElemenet.NUMERO_INFORMACION) {
          element.CANTIDAD = 9999;
        }
      });
    }
    const strShoppingCart:string = JSON.stringify(this.dataSource.data);
    const encShoppingCart:string = await this._encService.encrypt(strShoppingCart);
    localStorage.setItem('shopping_cart', encShoppingCart);
  }

  public async openDialog( typeDialog: string, dataElement: DataTableResponse ) {
    if (typeDialog === 'DETAILS') {
      this._dialog.open(ViewDetailsLineComponent, {
        data: dataElement.NUMERO_INFORMACION,
        disableClose: true,
        width: '1200px',
        maxWidth: '1200px',
      }).afterClosed().subscribe((description) => {
        if (description) {
          this.alert(typeDialog, description);
        }
      });
    }
  }
}
