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

@Component({
  selector: 'app-shopping-cart',
  templateUrl: './shopping-cart.component.html',
  styleUrls: ['./shopping-cart.component.css']
})
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: OrderService,
    private _dialog: MatDialog,
    private _preventiveMaintenanceService: PreventiveMaintenanceService,
    private _activatedRoute: ActivatedRoute,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
  ) {
    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(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 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}`);
            }
          }, ( 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 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;
  }

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

  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 Producto",
          description: "¿Está seguro de eliminar este produto 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 estos productos 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;
  }

  private async registerRequestLine() {
    this.isLoading = true;
    
    const arrRequestLine: Array<CreateRequestLineToShoppingCart> = this.createArrayShoppingCart();
    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);
        }
      }, (httpErrorResponse: HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    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,
        });
      }
    });
    console.log(requestLineShopping);
    return requestLineShopping;
  }
  
  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 getPreventiveMaintenance() {
    this.isLoading = true;
    const idUser:string = this.resourcesService.getUser();
    const line:number = parseInt(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);
        }
      },(error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

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



export interface GetRequestLine {
  PROVIDER: string;
  ARTITLES: Array<GetArtitleCar>
}

export interface RequestLine {
  ARTICULO: string;
  CANTIDAD: number;
  CARACTERISTICAS: string;
  CODIGO: string;
  IMAGEN: string;
  MODELO: string;
  MONEDA: string;
  NUMERO_ARTICULO: number;
  NUMERO_DESC_ARTICULO: number;
  NUMERO_INFORMACION: number;
  PRECIO: number;
  URL_IMAGEN: Array<SliderData>;
}

export interface GetArtitleCar {
  ARTICULO: string;
  CANTIDAD: number;
  CARACTERISTICAS: string;
  CODIGO: string;
  IMAGEN: string;
  MODELO: string;
  MONEDA: string;
  NUMERO_ARTICULO: number;
  NUMERO_DESC_ARTICULO: number;
  NUMERO_INFORMACION: number;
  NUMERO_PROVEEDOR: string;
  PRECIO: number;
  URL_IMAGEN: Array<string>;
}
