import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { ArtitleDetailsOrder, GetOrderData, ResponseDataArtitleByRequest, ResponseDataOrder } from 'src/app/interfaces/acquisition-management/order.interface';
import { lastValueFrom } from 'rxjs';
import { OrderService } from 'src/app/services/acquisition-management/order.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { HttpErrorResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { EncService } from 'src/app/services/enc/enc.service';
import { AddStateOrderComponent } from './add-state-order/add-state-order.component';
import { MatPaginator } from '@angular/material/paginator';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { ResponseData } from 'src/app/interfaces/response-data';
import { ReportProblemsOrdersComponent } from './report-problems-orders/report-problems-orders.component';
import { ContentArtitle, DataTableResponse } from 'src/app/interfaces/acquisition-management/artitle.interface';
import { SliderData } from 'src/app/interfaces/slider.interface';
import { PermissionsData } from '../../acquisition-management.component';
import { SocketService } from 'src/app/services/socket.service';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { UserConsultResponse } from 'src/app/interfaces/user.interface';
import { ProfileInterface } from 'src/app/interfaces/profile.interface';
import { GenerateSheetComponent } from '../../../resources/dialogs/generate-sheet/generate-sheet.component';

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

  public displayedColumns: string[] = ['ORCO_NUOR','LINE_IDLI','PROV_NOCO','DESP_NOMB','ORCO_FEMO','ORCO_ESTA','ACCIONES'];

  public isLoading: boolean = false;
  public isLoadingForm: boolean = false;
  
  public dataSource: MatTableDataSource<GetOrderData> ;
  public reorderEnabled: boolean;
  public getDocumentEnabled: boolean;
  public formDocumentEnabled: boolean;
  public getOrdersEnabled: boolean;
  public detailsOrdersEnabled: boolean;
  public configOrderEnabled: boolean;

  @ViewChild(MatPaginator) paginator!: MatPaginator;

  constructor(
    public dialog: MatDialog,
    public resourcesService: ResourcesService,
    private _orderService: OrderService,
    private _router: Router,
    private _encService: EncService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
  ) {
    this.dataSource = new MatTableDataSource<GetOrderData>();
    this.reorderEnabled = true;
    this.getDocumentEnabled = true;
    this.formDocumentEnabled = true;
    this.getOrdersEnabled = true;
    this.detailsOrdersEnabled = true;
    this.configOrderEnabled = true;
  }

  async ngOnInit() {
    await this.refreshPermissions();
    await this.setPermissions();
    await this.getOrders();
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }

  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 == "S002V01F04GEDO")[0];
              
              this.getDocumentEnabled = panPerm1.children.filter(item => item.id == 'S002V01P01CODO')[0].access > 0;
              this.formDocumentEnabled = panPerm1.children.filter(item => item.id == 'S002V01P02SUDO')[0].access > 0;
              
              let panPerm2 = funPerm.children.filter(item => item.id == "S002V01F02CGPE")[0];
              this.reorderEnabled = panPerm2.children.filter(item => item.id == 'S002V01P01AOCO')[0].access > 0;
              this.configOrderEnabled = panPerm2.children.filter(item => item.id == 'S002V01P02COCO')[0].access > 0;

              let panPerm3 = funPerm.children.filter(item => item.id == "S002V01F03SEPE")[0];
              this.getOrdersEnabled = panPerm3.children.filter(item => item.id == 'S002V01P01COPE')[0].access > 0;
              this.detailsOrdersEnabled = panPerm3.children.filter(item => item.id == 'S002V01P02DEPE')[0].access > 0;

              if (panPerm3.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 panPerm1 = funPerm.children.filter(item => item.id == "S002V01F04GEDO")[0];
    
    this.getDocumentEnabled = panPerm1.children.filter(item => item.id == 'S002V01P01CODO')[0].access > 0;
    this.formDocumentEnabled = panPerm1.children.filter(item => item.id == 'S002V01P02SUDO')[0].access > 0;
    
    let panPerm2 = funPerm.children.filter(item => item.id == "S002V01F02CGPE")[0];
    this.reorderEnabled = panPerm2.children.filter(item => item.id == 'S002V01P01AOCO')[0].access > 0;

    let panPerm3 = funPerm.children.filter(item => item.id == "S002V01F03SEPE")[0];
    this.getOrdersEnabled = panPerm3.children.filter(item => item.id == 'S002V01P01COPE')[0].access > 0;
    this.detailsOrdersEnabled = panPerm3.children.filter(item => item.id == 'S002V01P02DEPE')[0].access > 0;

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

  }

  public async getOrders() {
    this.isLoading = true;
    await lastValueFrom(this._orderService.getOrders()).then(
      (responseData: ResponseDataOrder) => {
        if ( !responseData.error ) {          
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

  public async checkPermission() {
    const encPermisos = localStorage.getItem('permisos');
    if (encPermisos === null || encPermisos === undefined || encPermisos === '') {
      this.resourcesService.openSnackBar(`No se pudo obtener los permisos del usuario.`);
      return;
    }

    const strPermission: string = await this._encService.decrypt(encPermisos); 
    const arrPermission: Array<PermissionsData> = JSON.parse(strPermission).permissions;

    arrPermission.map((permissionData: PermissionsData) => {
      if ( permissionData.id === "S002V01M05GEAD") {
        permissionData.children.map((permissionSubmodule:PermissionsData) => {
          
          if (permissionSubmodule.id === "S002V01S01ADQU") {
            permissionSubmodule.children.map((permissionFunction:PermissionsData) => {

              if (permissionFunction.id === "S002V01F02CGPE" && permissionFunction.access > 0) {
                this.reorderEnabled = true;
              }
            });
          }

        });
      }
    });
  }

  public async getInformationOrder( element: GetOrderData) {
    let encOrderNumber: string = await this._encService.encrypt( element.ORCO_NUOR );
    let encProviderNumber: string = await this._encService.encrypt( element.PROV_NUPR );
    this._router.navigate(['/sam/GEAD/ADQU/SEPE/details-order/' + encOrderNumber + '/' + encProviderNumber]);
  }

  public async getDocumentOrder( element: GetOrderData ) {    
    // let encOrderNumber: string = await this._encService.encrypt( element.ORCO_NUOR.toString() );
    let encLineNumber: string = await this._encService.encrypt( element.LINE_IDLI.toString() );
    this._router.navigate([`/sam/GEAD/ADQU/GEDO/${encLineNumber}`]);
  }

  public openDialog(typeDialog: string, dataElement: GetOrderData) {
    if (typeDialog === 'STATE') {
      this.dialog.open(AddStateOrderComponent, {
        width: '500px',
        disableClose: true,
        data: dataElement.ORCO_NUOR
      }).afterClosed().subscribe((result:any) => {
        if (result) {
          this.getOrders();
        }
      });
    }else if (typeDialog === 'WARNING') {
      this.dialog.open(ReportProblemsOrdersComponent, {
        width: '500px',
        disableClose: true,
        data: dataElement.ORCO_NUOR,
      }).afterClosed().subscribe((result:any) => {
        if (result) {
          this._router.navigate(['/sam/GEAD/DESP/SEPR']);
        }
      });
    }
  }

  private async _reOrder(dataElement: GetOrderData) {

    let encRequestLine: string = await this._encService.encrypt(dataElement.LINE_IDLI.toString());
    await lastValueFrom(this._orderService.getArtitlesByRequestLine(encRequestLine)).then(
      async (responseData:ResponseDataArtitleByRequest) => {
        if (!responseData.error) {
          const strShoppingCart: string = JSON.stringify(responseData.response);
          const encShoppingCart: string = await this._encService.encrypt(strShoppingCart);
          localStorage.setItem('shopping_cart', encShoppingCart);          

          const strPurchasePurpose: string = JSON.stringify({ PROPOSITO: 'NA' });
          const encPurchasePurpose: string = await this._encService.encrypt(strPurchasePurpose);
          this._router.navigate([`/sam/GEAD/ADQU/CGPE/shopping-cart/${encPurchasePurpose}`]);

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

  public alert(typeAlert: string, dataElement: GetOrderData) {
    if (typeAlert === 'REORDER') {
      this.dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          icon: 'warning',
          title: 'Reordenar Línea de Solicitud',
          description: '¿Está seguro de volver a pedir los artículos de la orden de compra?'
        }
      }).afterClosed().subscribe( (result:any) => {
        if (result) {
          let carShoppingArtitles = localStorage.getItem('shopping_cart');
          if (carShoppingArtitles !== null ) {
            this.alert('CONFIRM', dataElement);
          } else {
            this._reOrder(dataElement);
          }
        }
      });
    } else if ( typeAlert === 'CONFIRM' ) {
      this.dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          icon: 'warning',
          title: 'Confirmación',
          description: `Existen datos guardados en el carrito de compras, ¿Está seguro de eliminar el carrito y cargar los datos de la orden ${dataElement.ORCO_NUOR}?`
        }
      }).afterClosed().subscribe( (result:any) => {
        if (result) {
          this._reOrder(dataElement);
        }
      });
    } else if ( typeAlert === 'GENERATE_ACQUISITION' ) {
      this.dialog.open(GenerateSheetComponent, {
        disableClose: true,
        data: {
          title: 'Generar Ficha de Adquisición',
          description: 'Seleccione el tipo de formato de ficha',
        }
      }).afterClosed().subscribe((result) => {
        if (result === 'XLS') {
          this.generateSheetAcquisitionXLS(dataElement.ORCO_NUOR);
        } else if (result === 'PDF') {
          this.generateSheetAcquisitionPDF(dataElement.ORCO_NUOR);
        }

      })
    } else if ( typeAlert === 'GENERATE_DIVISA' ) {
      this.dialog.open(GenerateSheetComponent, {
        disableClose: true,
        data: {
          title: 'Generar Ficha de Divisa',
          description: 'Seleccione el tipo de formato de ficha',
        }
      }).afterClosed().subscribe((result) => {
        if (result === 'XLS') {
          this.generateSheetDivisaXLS(dataElement.ORCO_NUOR);
        } else if (result === 'PDF') {
          this.generateSheetDivisaPDF(dataElement.ORCO_NUOR);
        }
      });
    } else if ( typeAlert === 'GENERATE_INVOICE' ) {
      this.dialog.open(GenerateSheetComponent, {
        disableClose: true,
        data: {
          title: 'Generar Ficha de Factura',
          description: 'Seleccione el tipo de formato de ficha',
        }
      }).afterClosed().subscribe((result) => {
        if (result === 'XLS') {
          this.generateSheetInvoiceXLS(dataElement.ORCO_NUOR);
        } else if (result === 'PDF') {
          this.generateSheetInvoicePDF(dataElement.ORCO_NUOR);
        }
      });
    }
  }

  
  
  private async generateSheetAcquisitionXLS(orderNumber:string) {
    this.isLoadingForm = true;
    const encOrderNumber: string = await this._encService.encrypt(orderNumber);
    // const user: string = this.resourcesService.getUser();
    await lastValueFrom(this._orderService.generateSheetAcquisitionXLS(encOrderNumber)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, (httpErrorResponse:HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }

  private async generateSheetAcquisitionPDF(orderNumber:string) {
    this.isLoadingForm = true;
    const encOrderNumber: string = await this._encService.encrypt(orderNumber);
    // const user: string = this.resourcesService.getUser();
    await lastValueFrom(this._orderService.generateSheetAcquisitionPDF(encOrderNumber)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, (httpErrorResponse:HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }

  
  private async generateSheetDivisaXLS(orderNumber:string) {
    this.isLoadingForm = true;
    const encOrderNumber: string = await this._encService.encrypt(orderNumber);
    // const user: string = this.resourcesService.getUser();
    await lastValueFrom(this._orderService.generateSheetDivisaXLS(encOrderNumber)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, (httpErrorResponse:HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }
  
  private async generateSheetDivisaPDF(orderNumber:string) {
    this.isLoadingForm = true;
    const encOrderNumber: string = await this._encService.encrypt(orderNumber);
    // const user: string = this.resourcesService.getUser();
    await lastValueFrom(this._orderService.generateSheetDivisaPDF(encOrderNumber)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, (httpErrorResponse:HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }


  private async generateSheetInvoiceXLS(orderNumber:string) {
    this.isLoadingForm = true;
    const encOrderNumber: string = await this._encService.encrypt(orderNumber);
    // const user: string = this.resourcesService.getUser();
    await lastValueFrom(this._orderService.generateSheetInvoiceXLS(encOrderNumber)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, (httpErrorResponse:HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }
  
  private async generateSheetInvoicePDF(orderNumber:string) {
    this.isLoadingForm = true;
    const encOrderNumber: string = await this._encService.encrypt(orderNumber);
    // const user: string = this.resourcesService.getUser();
    await lastValueFrom(this._orderService.generateSheetInvoicePDF(encOrderNumber)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, (httpErrorResponse:HttpErrorResponse) => this.resourcesService.checkErrors(httpErrorResponse)
    );
    this.isLoadingForm = false;
  }
}
