import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { GetOrderReception, ResponseDataGetOrderReception } from 'src/app/interfaces/acquisition-management/order-reception.interface';
import { lastValueFrom } from 'rxjs';
import { OrderReceptionService } from 'src/app/services/acquisition-management/order-reception.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { HttpErrorResponse } from '@angular/common/http';
import { ReportProblemsOrdersComponent } from '../../acquisition/orders/report-problems-orders/report-problems-orders.component';
import { Router } from '@angular/router';
import { EncService } from 'src/app/services/enc/enc.service';
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 { ResponseData } from 'src/app/interfaces/response-data';
import { GenerateSheetComponent } from 'src/app/components/resources/dialogs/generate-sheet/generate-sheet.component';
import { DataOrder } from './artitle-list-reception/artitle-list-reception.component';


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

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  public displayedColumns: string[];
  public dataSource: MatTableDataSource<GetOrderReception>;
  public txtBuscador:string;

  public isLoading: boolean;
  public isLoadingForm: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _router: Router,
    private _dialog: MatDialog,
    private _encService: EncService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _orderReceptionService: OrderReceptionService,
  ) {
    this.displayedColumns = [
      'ORCO_NUOR', 
      'LINE_NUPR', 
      'DESP_IDDE', 
      'DESP_NODE', 
      'ORCO_USMO', 
      'ORCO_FEMO', 
      'ORCO_ESTA', 
      'ACCIONES', 
    ];
    this.dataSource = new MatTableDataSource();
    this.txtBuscador = '';
    this.isLoading = false;
    this.isLoadingForm = false;
  }

  async ngOnInit() {
    await this.refreshPermissions();
    await this.getOrderReception();
  }

  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 == 'S002V03S03DESP')[0];
              let panPerm = funPerm.children.filter(item => item.id == "S002V01F01REPE")[0];

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

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

  public async getOrderReception() {
    this.isLoading = true;
    await lastValueFrom(this._orderReceptionService.getOrderReception()).then(
      (responseData: ResponseDataGetOrderReception) => {
        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 getInformationOrder( element: GetOrderReception) {    
    let encOrderNumber: string = await this._encService.encrypt( element.ORCO_NUOR );
    let encProviderNumber: string = await this._encService.encrypt( element.LINE_NUPR );
    this._router.navigate(['/sam/GEAD/ADQU/SEPE/details-order/' + encOrderNumber + '/' + encProviderNumber]);
  }

  public async openDialog(typeDialog: string, dataElement: GetOrderReception) {
    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']);
        }
      });
    } else if (typeDialog === 'GENERATE') {

      this._dialog.open(GenerateSheetComponent, {
        width: '400px',
        disableClose: true,
        data: {
          title: 'Generar Lista de Entrega',
          description: 'Seleccione el tipo de formato de la lista de entrega',
        }
      }).afterClosed().subscribe((result:any) => {
        if (result === 'XLS') {
          this.generateSheetDeliveryListXLS( dataElement.ORCO_NUOR );
        } else if (result === 'PDF') {
          this.generateSheetDeliveryListPDF( dataElement.ORCO_NUOR );
        }
      });

    } else if (typeDialog === 'STOCK') {

      const orderReception: DataOrder = {
        ORDER: dataElement.ORCO_NUOR
      };
      const strOrderReception: string = JSON.stringify(orderReception);
      const encOrderReception: string = await this._encService.encrypt(strOrderReception);
      this._router.navigate([`/sam/GEAD/DESP/REPE/list-artitle-reception/${encOrderReception}`]);
    }
  }

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

