import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { GetOrderData, ResponseDataArtitleByRequest, ResponseDataOrder } from '../../../../interfaces/acquisition-management/order.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatDialog } from '@angular/material/dialog';
import { ResourcesService } from '../../../../services/resources.service';
import { AcquisitionService } from '../../../../services/acquisition-management/acquisition.service';
import { Router } from '@angular/router';
import { EncService } from '../../../../services/enc.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 { AddStateOrderComponent } from './add-state-order/add-state-order.component';
import { ReportProblemsOrdersComponent } from './report-problems-orders/report-problems-orders.component';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { GenerateSheetComponent } from '../../../resources/dialogs/generate-sheet/generate-sheet.component';
import { ResponseData } from '../../../../interfaces/response-data';
import { FunctionsService } from '../../../../services/functions.service';

const ID_MODULE = "S002V01M05GEAD";
@Component({
    selector: 'app-orders',
    templateUrl: './orders.component.html',
    styleUrl: './orders.component.css',
    standalone: false
})
export class OrdersComponent implements OnInit, AfterViewInit {
  public displayedColumns: string[] = [
    'NUMERO_ORDEN',
    'NUMERO_SOLICITUD_COMPRA',
    'NOMBRE_COMERCIAL',
    'NOMBRE_DESPACHO',
    'USUARIO_MODIFICA',
    'FECHA_MODIFICA',
    'ESTADO',
    '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 _acquisitionService: AcquisitionService,
    private _router: Router,
    private _encService: EncService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    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(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}`);
            }
          }, 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 == "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;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionService.getOrders(user, line)).then(
      (responseData: ResponseDataOrder) => {
        if ( !responseData.error ) {          
          this.dataSource.data = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${responseData.msg}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getOrders();
        }
      }
    );
    this.isLoading = false;
  }

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

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

  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.NUMERO_ORDEN}?`
        }
      }).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.NUMERO_ORDEN);
        } else if (result === 'PDF') {
          this.generateSheetAcquisitionPDF(dataElement.NUMERO_ORDEN);
        }

      })
    } 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.NUMERO_ORDEN);
        } else if (result === 'PDF') {
          this.generateSheetDivisaPDF(dataElement.NUMERO_ORDEN);
        }
      });
    } 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.NUMERO_ORDEN);
        } else if (result === 'PDF') {
          this.generateSheetInvoicePDF(dataElement.NUMERO_ORDEN);
        }
      });
    }
  }

  private async _reOrder(dataElement: GetOrderData) {
    let encRequestLine: string = await this._encService.encrypt(dataElement.NUMERO_SOLICITUD_COMPRA.toString());
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionService.getArtitlesByRequestLine(encRequestLine, user, line)).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}`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._reOrder(dataElement);
        }
      }
    );  
  }
  
  private async generateSheetAcquisitionXLS(orderNumber:string) {
    this.isLoadingForm = true;
    const encOrderNumber: string = await this._encService.encrypt(orderNumber);
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionService.generateSheetAcquisitionXLS(encOrderNumber, user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetAcquisitionXLS(orderNumber);
        }
      }
    );
    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();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionService.generateSheetAcquisitionPDF(encOrderNumber, user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetAcquisitionPDF(orderNumber);
        }
      }
    );
    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();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionService.generateSheetDivisaXLS(encOrderNumber, user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetDivisaXLS(orderNumber);
        }
      }
    );
    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();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionService.generateSheetDivisaPDF(encOrderNumber, user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetDivisaPDF(orderNumber);
        }
      }
    );
    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();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionService.generateSheetInvoiceXLS(encOrderNumber, user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetInvoiceXLS(orderNumber);
        }
      }
    );
    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();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionService.generateSheetInvoicePDF(encOrderNumber, user, line)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          window.open( `${responseData.response.url}`, '_blank');
        } else {
          this.resourcesService.openSnackBar(responseData.msg)
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.generateSheetInvoicePDF(orderNumber);
        }
      }
    );
    this.isLoadingForm = false;
  }

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