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 { GetOrderReception, ResponseDataGetOrderReception } from '../../../../interfaces/acquisition-management/order-reception.interface';
import { ResourcesService } from '../../../../services/resources.service';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { EncService } from '../../../../services/enc.service';
import { SocketService } from '../../../../services/socket.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { DispatchService } from '../../../../services/acquisition-management/dispatch.service';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { GetDataRegisterArtitle } from './move-stock/move-stock.component';
import { ReportProblemsOrdersComponent } from '../../acquisition/orders/report-problems-orders/report-problems-orders.component';
import { GenerateSheetComponent } from '../../../resources/dialogs/generate-sheet/generate-sheet.component';
import { ResponseData } from '../../../../interfaces/response-data';
import { DataOrder } from './artitle-list-reception/artitle-list-reception.component';
import { FunctionsService } from '../../../../services/functions.service';

const ID_MODULE = "S002V01M05GEAD";
@Component({
    selector: 'app-order-reception',
    templateUrl: './order-reception.component.html',
    styleUrl: './order-reception.component.css',
    standalone: false
})
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 _dispatchService: DispatchService,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.displayedColumns = [
      'NUMERO_ORDEN',
      'NUMERO_PROVEEDOR',
      'NOMBRE_DESPACHO',
      'USUARIO_MODIFICA',
      'FECHA_MODIFICA',
      'ESTADO',
      '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(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}`);
            }
          }, 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));
  }

  public async getOrderReception() {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._dispatchService.getOrderReception(user, line)).then(
      (responseData: ResponseDataGetOrderReception) => {
        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.getOrderReception();
        }
      }
    );
    this.isLoading = false;
  }

  public async registerArtitlesToEquipment() {
    const contentForm: GetDataRegisterArtitle = {
      action: 'new'
    }
    const strContentForm:string = JSON.stringify(contentForm);
    const encContentForm:string = await this._encService.encrypt(strContentForm);

    this._router.navigate([`/sam/GEAD/DESP/REPE/register/${encContentForm}`]);
  }

  public async getInformationOrder( element: GetOrderReception) {    
    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 async openDialog(typeDialog: string, dataElement: GetOrderReception) {
    if (typeDialog === 'WARNING') {
      this._dialog.open(ReportProblemsOrdersComponent, {
        width: '500px',
        maxWidth: '500px',
        disableClose: true,
        data: dataElement.NUMERO_ORDEN,
      }).afterClosed().subscribe((result:any) => {
        if (result) {
          this._router.navigate(['/sam/GEAD/DESP/SEPR']);
        }
      });
    } else if (typeDialog === 'GENERATE') {

      this._dialog.open(GenerateSheetComponent, {
        width: '400px',
        maxWidth: '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.NUMERO_ORDEN );
        } else if (result === 'PDF') {
          this.generateSheetDeliveryListPDF( dataElement.NUMERO_ORDEN );
        }
      });

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

      const orderReception: DataOrder = {
        ORDER: dataElement.NUMERO_ORDEN
      };
      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 user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    const encOrderNumber:string = await this._encService.encrypt(orderNumber);
    await lastValueFrom(this._dispatchService.generateSheetDeliveryListXLS(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.generateSheetDeliveryListXLS(orderNumber);
        }
      }
    );
    this.isLoadingForm = false;
  }
  
  private async generateSheetDeliveryListPDF(orderNumber: string) {
    this.isLoadingForm = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    const encOrderNumber:string = await this._encService.encrypt(orderNumber);
    await lastValueFrom(this._dispatchService.generateSheetDeliveryListPDF(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.generateSheetDeliveryListPDF(orderNumber);
        }
      }
    );
    this.isLoadingForm = false;
  }
}
