import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { DetailsProduct, ObjectDeleteArtitleByRequestLine, ObjectGetRequest, RequestLines, ResponseRequestLines } from '../../../../interfaces/acquisition-management/order.interface';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { PreventiveWorkOrdersActive } from '../../../../interfaces/preventive-work-orders-active.interface';
import { DispatchData } from '../../../../interfaces/acquisition-management/dispatch.interface';
import { ResourcesService } from '../../../../services/resources.service';
import { EncService } from '../../../../services/enc.service';
import { Router } from '@angular/router';
import { AcquisitionService } from '../../../../services/acquisition-management/acquisition.service';
import { SocketService } from '../../../../services/socket.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { MatDialog } from '@angular/material/dialog';
import { PermissionsData } from '../../acquisition-management.component';
import { UserConsultResponse } from '../../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../interfaces/profile.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { AlertComponent } from '../../../resources/dialogs/alert/alert.component';
import { ResponseData } from '../../../../interfaces/response-data';
import { GetInvoiceControlComponent } from './get-invoice-control/get-invoice-control.component';
import { FormPurchaseLineComponent } from './form-purchase-line/form-purchase-line.component';
import { FunctionsService } from '../../../../services/functions.service';

const ID_MODULE = "S002V01M05GEAD";
@Component({
    selector: 'app-purchase-line',
    templateUrl: './purchase-line.component.html',
    styleUrl: './purchase-line.component.css',
    animations: [
        trigger('detailExpand', [
            state('collapsed', style({ height: '0px', minHeight: '0' })),
            state('expanded', style({ height: '*' })),
            transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')),
        ]),
    ],
    standalone: false
})
export class PurchaseLineComponent implements AfterViewInit, OnInit {
  public dataSource: MatTableDataSource<RequestLines>;
  public isLoading: boolean;
  public isLoadingForm: boolean;

  columnsToDisplay = [
    'ID_LINEA_SOLICITUD',
    'NOMBRE_COMERCIAL',
    'ORDEN_TRABAJO_PREVENTIVO',
    'USUARIO_MODIFICA',
    'FECHA_MODIFICA',
    'ESTADO',
    'ACCIONES'];
  columnsToDisplayWithExpand = [ ...this.columnsToDisplay, 'expand' ];
  expandedElement?: RequestLines
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  public arrProject: Array<any>;
  public arrPreventiveMaintenance: Array<PreventiveWorkOrdersActive>;
  public arrCorrectiveMaintenance: Array<any>;
  public arrDispatch: Array<DispatchData>;

  public getRequestLineEnabled: boolean;
  public configOrderEnabled: boolean;
  public sendDocumentEnabled: boolean;
  public infoSelectedEnabled: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _encService: EncService,
    private _router: Router,
    private _acquisitionService: AcquisitionService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _dialog: MatDialog,
    private _functionsService: FunctionsService,
  ) {
    this._functionsService.consultModuleStatus(ID_MODULE);
    this.dataSource = new MatTableDataSource<RequestLines>();
    this.isLoading = false;
    this.isLoadingForm = false;
    
    this.getRequestLineEnabled = true;
    this.configOrderEnabled = true;
    this.sendDocumentEnabled = true;
    this.infoSelectedEnabled = true;

    this.arrProject = [];
    this.arrDispatch = [];
    this.arrPreventiveMaintenance = [];
    this.arrCorrectiveMaintenance = [];

  }
  
  async ngOnInit() {
    this.isLoading = true;
    await this.setPermissions();
    await this.refreshPermissions();
    await this.getAllRequestLines();
    this.isLoading = false;
  }

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

  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 funPerm1 = modPerm.children.filter(item => item.id == 'S002V01S01ADQU')[0];
    let panPerm1 = funPerm1.children.filter(item => item.id == "S002V01F01NSCO")[0];
    this.getRequestLineEnabled = panPerm1.children.filter(item => item.id == 'S002V01P01CLSO')[0].access > 0;
    
    let panPerm2 = funPerm1.children.filter(item => item.id == "S002V01F02CGPE")[0];
    this.configOrderEnabled = panPerm2.children.filter(item => item.id == 'S002V01P02COCO')[0].access > 0;
    
    let panPerm3 = funPerm1.children.filter(item => item.id == "S002V01F04GEDO")[0];
    this.sendDocumentEnabled = panPerm3.children.filter(item => item.id == 'S002V01P02SUDO')[0].access > 0;

    let funPerm2 = modPerm.children.filter(item => item.id == 'S002V02S02PROV')[0];
    let panPerm4 = funPerm2.children.filter(item => item.id == "S002V01F01SOPR")[0];

    this.infoSelectedEnabled = panPerm4.children.filter(item => item.id == 'S002V01P03INSE')[0].access > 0;

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

  }

  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 funPerm1 = modPerm.children.filter(item => item.id == 'S002V01S01ADQU')[0];
              let panPerm1 = funPerm1.children.filter(item => item.id == "S002V01F01NSCO")[0];
              this.getRequestLineEnabled = panPerm1.children.filter(item => item.id == 'S002V01P01CLSO')[0].access > 0;
              
              let panPerm2 = funPerm1.children.filter(item => item.id == "S002V01F02CGPE")[0];
              this.configOrderEnabled = panPerm2.children.filter(item => item.id == 'S002V01P02COCO')[0].access > 0;
              
              let panPerm3 = funPerm1.children.filter(item => item.id == "S002V01F04GEDO")[0];
              this.sendDocumentEnabled = panPerm3.children.filter(item => item.id == 'S002V01P02SUDO')[0].access > 0;

              let funPerm2 = modPerm.children.filter(item => item.id == 'S002V02S02PROV')[0];
              let panPerm4 = funPerm2.children.filter(item => item.id == "S002V01F01SOPR")[0];

              this.infoSelectedEnabled = panPerm4.children.filter(item => item.id == 'S002V01P03INSE')[0].access > 0;

              if (panPerm1.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 getAllRequestLines():Promise<void> {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionService.getAllRequestLines(user, line)).then(
      (responseData:ResponseRequestLines) => {
        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.getAllRequestLines();
        }
      }
    );
    this.isLoading = false;
  }

  public getProposite(LINE_OTPR: number,LINE_OTCO: number): string {
    if (LINE_OTPR === null && LINE_OTCO === null) {
      return "Sin Proposito";

    } else if (LINE_OTPR !== null) {
      return `MTPR-#${LINE_OTPR}`;

    } else if (LINE_OTCO !== null) {
      return `MTCO-#${LINE_OTCO}`;

    } else {
      return ""
    }
  }

  public async alert(typeAlert: string, dataElement: any = null, dataElement2: any = null):Promise<void> {
     if (typeAlert === 'DELETE') {
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          icon: "warning",
          title: "Eliminar Artículo",
          description: "¿Está seguro de eliminar el artículo de la línea de solicitud de compra?"
        },
      }).afterClosed().subscribe((result) => {
        if (result ) {
          this.deleteArtitleByRequestLine(dataElement, dataElement2);
        }
      });
    } else if (typeAlert === 'CANCEL') {
      this._dialog.open(AlertComponent, {
        disableClose: true,
        data: {
          icon: "warning",
          title: "Cancelar Solicitud",
          description: "¿Está seguro de cancelar la línea de solicitud de compra?"
        },
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.cancelRequestLine(dataElement);
        }
      });
    }
  }

  private async deleteArtitleByRequestLine(details: DetailsProduct, requestLine: RequestLines) {
    let objectDeleteArtitle: ObjectDeleteArtitleByRequestLine = {
      USUARIO: this.resourcesService.getUser(),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
      NUMERO_INFORMACION: await this._encService.encrypt(details.NUMERO_INFORMACION.toString()),
      NUMERO_PROVEEDOR: await this._encService.encrypt(details.NUMERO_PROVEEDOR.toString()),
      NUMERO_ARTICULO: await this._encService.encrypt(details.NUMERO_ARTICULO.toString()),
      ID_LINEA_SOLICITUD: await this._encService.encrypt(requestLine.ID_LINEA_SOLICITUD.toString()),
    }
    await lastValueFrom(this._acquisitionService.deleteArtitleByRequestLine(objectDeleteArtitle)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
          this.getAllRequestLines();
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.deleteArtitleByRequestLine(details, requestLine);
        }
      }
    );
  }

  public async cancelRequestLine(requestLine: RequestLines):Promise<void>{
    let objGetRequest: ObjectGetRequest = {
      ID_LINEA_SOLICITUD: await this._encService.encrypt(requestLine.ID_LINEA_SOLICITUD.toString()),
      NUMERO_PROVEEDOR: await this._encService.encrypt(requestLine.NUMERO_PROVEEDOR.toString()),
      NUMERO_LINEA: this.resourcesService.getLineNumber(),
      USUARIO: this.resourcesService.getUser(),
    }
    await lastValueFrom(this._acquisitionService.cancelRequestLine(objGetRequest)).then(
      (data:ResponseRequestLines) => {
        if(!data.error){
          this.resourcesService.openSnackBar('¡La solicitud fue cancelada correctamente!');
          this.getAllRequestLines();
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.cancelRequestLine(requestLine);
        }
      }
    );
  }

  public async openDialogInvoice(dataElement:RequestLines):Promise<void> {
    this._dialog.open(GetInvoiceControlComponent, {
      disableClose: true,
      width: '500px',
      maxWidth: '500px',
      data: dataElement,
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.getAllRequestLines();
      }
    });
  }

  public async openDialogRegisterOrder(dataElement:RequestLines) {
    this._dialog.open(FormPurchaseLineComponent, {
      data: dataElement,
      width: '500px',
      maxWidth: '500px',
    }).afterClosed().subscribe((result) => {
      if (result) {
        this._router.navigate(['/sam/GEAD/ADQU/SEPE']);
      }
    });
  }
}
