import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { ArtitleDetailsOrder, HistoryOrder } from 'src/app/interfaces/acquisition-management/order.interface';
import { GetOrderDetails, ResponseDataOrderDetails } from 'src/app/interfaces/acquisition-management/order.interface';
import { OrderService } from 'src/app/services/acquisition-management/order.service';
import { EncService } from 'src/app/services/enc/enc.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { InformationProviderComponent } from '../../../provider/providers/information-provider/information-provider.component';
import { ViewDetailsLineComponent } from '../../purchase-line/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',
  styleUrls: ['./details-order.component.css']
})
export class DetailsOrderComponent implements OnInit {

  public displayedColumnsArtitle: string[] = ['IMAGEN','ARTI_NOMB','INAR_MODE','INAR_CODI','ARSE_PRTO','ARSE_CANT','INAR_MONE','ACCIONES'];
  public displayedColumnsState: string[] = ['HIOR_ESOR','HIOR_FERE','ACCIONES'];

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

  public orderDetails!: GetOrderDetails;

  public numberOrder: string;
  public numberProvider: string;

  public isLoading: boolean;
  public isScreenSmall: boolean;

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

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

    this.isLoading = false;
    this.isScreenSmall = false;

    this.orderDetails = {
      ORCO_NUOR: '',
      PROV_NUPR: '',
      PROV_NOCO: '',
      DESP_NUDE: '',
      DESP_NOMB: '',
      DESP_CALL: '',
      DESP_NUEX: '',
      DESP_NUIN: '',
      DESP_COPO: '',
      DESP_COLO: '',
      DESP_MUNI: '',
      DESP_ENTI: '',
      DESP_PAIS: '',
      LINE_IDLI: 0,
      LINE_DESC: '',
      LINE_IDME: '',
      MEPA_NOMB: '',
      ORCO_COST: 0,
      ORCO_MONE: '',
      ORCO_PROP: '',
      ORCO_ACTI: '',
      ORCO_PROY: '',
      ORCO_ESTA: '',
      ORCO_USRE: '',
      ORCO_FERE: '',
      ORCO_USMO: '',
      ORCO_FEMO: '',
      PRODUCTS: [],
      STATES: [],
    }
  }

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

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

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

    this.getDetailsOrder(encOrderNumber, encProviderNumber);
  }

  private async getDetailsOrder(encOrderNumber: string, encProviderNumber: string) {
    this.isLoading = true;
    await lastValueFrom(this._orderService.getOrderByNumber(encOrderNumber, encProviderNumber)).then(
      (responseData: ResponseDataOrderDetails) => {
        if ( !responseData.error ) {
          this.orderDetails = responseData.response;
          this.dataSourceArtitles.data = this.orderDetails.PRODUCTS;
          this.dataSourceState.data = this.orderDetails.STATES;
        } else {
          this.resourcesService.openSnackBar(responseData.msg);
        }
      }, (error: HttpErrorResponse) => this.resourcesService.checkErrors(error)
    );
    this.isLoading = false;
  }

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

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

    if ( this.orderDetails !== null ) {
      direction += this.orderDetails.DESP_CALL + ', ';
      direction += this.orderDetails.DESP_NUEX;
      direction += this.orderDetails.DESP_NUIN === null || this.orderDetails.DESP_NUIN === undefined ? ', ' : ' ';
      direction += this.orderDetails.DESP_NUIN === null || this.orderDetails.DESP_NUIN === undefined ? '' : this.orderDetails.DESP_NUIN + ', ';
      direction += this.orderDetails.DESP_COPO + ', ';
      direction += this.orderDetails.DESP_COLO + '. ';
      direction += this.orderDetails.DESP_MUNI + ', ';
      direction += this.orderDetails.DESP_ENTI + ', ';
      direction += this.orderDetails.DESP_PAIS + '.';

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

  public onResize():void {
    this.isScreenSmall = window.innerWidth <= 1022;
  }
}
