import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { ArtitleDetailsOrder, GetOrderDetails, HistoryOrder, ResponseDataOrderDetails } from '../../../../../interfaces/acquisition-management/order.interface';
import { ResourcesService } from '../../../../../services/resources.service';
import { ActivatedRoute } from '@angular/router';
import { EncService } from '../../../../../services/enc.service';
import { AcquisitionService } from '../../../../../services/acquisition-management/acquisition.service';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { InformationProviderComponent } from '../../../provider/providers/information-provider/information-provider.component';
import { ViewDetailsLineComponent } from '../../shopping/view-details-line/view-details-line.component';
import { DetailsStateOrderComponent } from '../details-state-order/details-state-order.component';

@Component({
    selector: 'app-details-order',
    templateUrl: './details-order.component.html',
    styleUrl: './details-order.component.css',
    standalone: false
})
export class DetailsOrderComponent implements OnInit {
  public displayedColumnsArtitle: string[] = [
    'IMAGEN',
    'NOMBRE_FAMILIA',
    'MODELO_ARTICULO',
    'CODIGO_ARTICULO',
    'PRECIO',
    'CANTIDAD',
    'PRECIO_TOTAL',
    'ACCIONES',
  ];
  
  public displayedColumnsState: string[] = [
    'ESTADO_ORDEN',
    'FECHA_MODIFICA',
    'PORCENTAJE_ENTREGA',
    'ACCIONES',
  ];

  public dataSourceArtitles: MatTableDataSource<ArtitleDetailsOrder>;
  public dataSourceState: MatTableDataSource<HistoryOrder>;

  public orderDetails: GetOrderDetails;

  public numberOrder: string;
  public numberProvider: string;

  public isLoading: boolean;

  constructor(
    public resourcesService: ResourcesService,
    private _activatedRouter: ActivatedRoute,
    private _encService: EncService,
    private _acquisitionService: AcquisitionService,
    private _dialog: MatDialog,
  ) {
    this.numberOrder = '';
    this.numberProvider = '';

    this.dataSourceArtitles = new MatTableDataSource<ArtitleDetailsOrder>();
    this.dataSourceState = new MatTableDataSource<HistoryOrder>();

    this.isLoading = false;

    this.orderDetails = {} as GetOrderDetails;
  }

  ngOnInit(): void {
    this.getDataURL();
  }

  private async getDataURL() {
    let encOrderNumber = this._activatedRouter.snapshot.paramMap.get('numberOrder')!;
    this.numberOrder = await this._encService.decrypt(encOrderNumber)!;

    let encProviderNumber = this._activatedRouter.snapshot.paramMap.get('numberProvider')!;
    this.numberProvider = await this._encService.decrypt(encProviderNumber)!;

    this.getDetailsOrder(encOrderNumber, encProviderNumber);
  }

  private async getDetailsOrder(encOrderNumber: string, encProviderNumber: string) {
    this.isLoading = true;
    const user: string = this.resourcesService.getUser();
    const line: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._acquisitionService.getOrderByNumber(encOrderNumber, encProviderNumber, user, line)).then(
      (responseData: ResponseDataOrderDetails) => {
        if ( !responseData.error ) {
          
          this.orderDetails = responseData.response;
          this.dataSourceArtitles.data = this.orderDetails.ARTI;
          this.dataSourceState.data = this.orderDetails.HIST;
          
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this.getDetailsOrder(encOrderNumber, encProviderNumber);
        }
      }
    );
    this.isLoading = false;
  }

  public openDialog( typeDialog: string, dataElement: any = null ) {
    if ( typeDialog === 'VIEW_PROVIDER' ) {
      console.log(this.orderDetails.NUMERO_PROVEEDOR);
      this._dialog.open(InformationProviderComponent, {
        width: '1200px',
        maxWidth: '1200px',
        disableClose: true,
        data: this.orderDetails.NUMERO_PROVEEDOR,
      });
    } else if ( typeDialog === 'VIEW_ARTITLE' ) {
      let dataArtitle: ArtitleDetailsOrder = dataElement;
      this._dialog.open(ViewDetailsLineComponent, {
        width: '1200px',
        maxWidth: '1200px',
        disableClose: true,
        data: dataArtitle!.ID_INFORMACION,
      });
    } else if ( typeDialog === 'VIEW_STATE' ) {
      let dataState: HistoryOrder = dataElement;
      this._dialog.open(DetailsStateOrderComponent, {
        width: dataState.EVIDENCIA === null ? '500px' : '900px',
        maxWidth: dataState.EVIDENCIA === null ? '500px' : '900px',
        disableClose: true,
        data: dataState,
      });
    }
  }

  public setDirection() :string {
    let direction: string = '';

    if ( this.orderDetails !== null ) {
      direction += this.orderDetails.CALLE + ', ';
      direction += this.orderDetails.NUMERO_EXTERIOR;
      direction += this.orderDetails.NUMERO_INTERIOR === null || this.orderDetails.NUMERO_INTERIOR === undefined ? ', ' : ' ';
      direction += this.orderDetails.NUMERO_INTERIOR === null || this.orderDetails.NUMERO_INTERIOR === undefined ? '' : this.orderDetails.NUMERO_INTERIOR + ', ';
      direction += this.orderDetails.CODIGO_POSTAL + ', ';
      direction += this.orderDetails.COLONIA + '. ';
      direction += this.orderDetails.MUNICIPIO + ', ';
      direction += this.orderDetails.ENTIDAD_FEDERATIVA + ', ';
      direction += this.orderDetails.PAIS + '.';

      return direction;
    } else {
      return '';
    }
  }

  public setLabelOrder(): string {
    let label: string = '';

    if ( this.orderDetails.ORDEN_TRABAJO_CORRECTIVO === null && this.orderDetails.ORDEN_TRABAJO_PREVENTIVO === null )  {
      label = `Orden de Mantenimiento`;

    } else if (this.orderDetails.ORDEN_TRABAJO_CORRECTIVO !== null && this.orderDetails.ORDEN_TRABAJO_PREVENTIVO === null) {
      label = `Orden de Mantenimiento Correctivo`;

    } else if (this.orderDetails.ORDEN_TRABAJO_PREVENTIVO !== null && this.orderDetails.ORDEN_TRABAJO_CORRECTIVO === null) {
      label = `Orden de Mantenimiento Preventivo`;

    } else {
      label = 'ERR';

    }

    return label;
  }

  public setOrderValue(): string {
    let value: string = '';        

    if ( this.orderDetails.ORDEN_TRABAJO_CORRECTIVO === null && this.orderDetails.ORDEN_TRABAJO_PREVENTIVO === null )  {
      value = `No aplica`;

    } else if (this.orderDetails.ORDEN_TRABAJO_CORRECTIVO !== null && this.orderDetails.ORDEN_TRABAJO_PREVENTIVO === null) {
      value = `#${this.orderDetails.ORDEN_TRABAJO_CORRECTIVO}`;

    } else if (this.orderDetails.ORDEN_TRABAJO_PREVENTIVO !== null && this.orderDetails.ORDEN_TRABAJO_CORRECTIVO === null) {
      value = `#${this.orderDetails.ORDEN_TRABAJO_PREVENTIVO}`;

    } else {
      value = 'ERR';

    }


    return value;
  }
}