import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import {animate, state, style, transition, trigger} from '@angular/animations';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { Router } from '@angular/router';
import { SliderData } from 'src/app/interfaces/slider.interface';
import { lastValueFrom } from 'rxjs';
import { DetailsProduct, ObjectDeleteArtitleByRequestLine, ObjectGetRequest, RequestLines, ResponseRequestLines } from 'src/app/interfaces/acquisition-management/order.interface';
import { HttpErrorResponse } from '@angular/common/http';
import { OrderService } from 'src/app/services/acquisition-management/order.service';
import { MatDialog } from '@angular/material/dialog';
import { GetInvoiceControlComponent } from './get-invoice-control/get-invoice-control.component';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { PreventiveWorkOrdersActive, PreventiveWorkOrdersActiveResponse } from 'src/app/interfaces/preventive-work-orders-active.interface';
import { PreventiveMaintenanceService } from 'src/app/services/preventive-maintenance.service';
import { DispatchData } from 'src/app/interfaces/acquisition-management/dispatch.interface';
import { DispatchService } from 'src/app/services/acquisition-management/dispatch.service';
import { ResponseData } from 'src/app/interfaces/response-data';
import { GdelService } from 'src/app/services/document-management/gdel.service';
import { FormPurchaseLineComponent } from './form-purchase-line/form-purchase-line.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 { PermissionsData } from '../../acquisition-management.component';


@Component({
  selector: 'app-purchase-line',
  templateUrl: './purchase-line.component.html',
  styleUrls: ['./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)')),
    ]),
  ],
})
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 _orderService: OrderService,
    private _socketService: SocketService,
    private _usersProfilesSevice: UsersProfilesService,
    private _dialog: MatDialog,
  ) {
    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 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 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}`);
            }
          }, ( 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 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']);
    }

  }

  public async getAllRequestLines():Promise<void> {
    this.isLoading = true;
    await lastValueFrom(this._orderService.getAllRequestLines()).then(
      (responseData:ResponseRequestLines) => {
        if (!responseData.error) {
          responseData.response = responseData.response.map((requestLines:RequestLines) => {
            requestLines.SELECTED = requestLines.SELECTED.map((detailsProduct:DetailsProduct) => {
              let arrSliderData:Array<SliderData> = [];
              detailsProduct.IMAGENES.forEach(image => {
                arrSliderData.push({
                  image: image,
                  height: '130px'
                })
              });
              detailsProduct.CARR_IMAG = arrSliderData
              return detailsProduct;
            });
            return requestLines;
          });
          this.dataSource.data = responseData.response;
          this.isLoading = false;
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

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

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

  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._orderService.deleteArtitleByRequestLine(objectDeleteArtitle)).then(
      (responseData: ResponseData) => {
        if (!responseData.error) {
          this.resourcesService.openSnackBar('¡Eliminación Exitosa!');
          this.getAllRequestLines();
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  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._orderService.cancelRequestLine(objGetRequest)).then(
      (data:ResponseRequestLines) => {
        if(!data.error){
          this.resourcesService.openSnackBar('¡La solicitud fue cancelada correctamente!');
          this.getAllRequestLines();
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
  }

  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 ""
    }
  }

}
