import { Component, OnInit, OnDestroy, ChangeDetectionStrategy, Input, ChangeDetectorRef } from '@angular/core';
import { Store } from '@ngxs/store';
import { Subject } from 'rxjs';
import { OrderItemDTO, EnvironmentChannel, LogisticianDTO, ReceiptListItemDTO } from '@swagger/oms';
import { orderChannelMapper, receiptType, OrderStatus } from 'apps/sales/src/app/core/mappings/shelf.mapping';
import { BranchSelectors } from 'apps/sales/src/app/core/store/selectors/branch.selector';
import { isNullOrUndefined } from 'util';
import { CollectingShelfService } from 'apps/sales/src/app/core/services/collecting-shelf.service';
import { DatePipe } from '@angular/common';
import { SupplierState } from 'apps/sales/src/app/core/store/state/supplier.state';
import { take, filter } from 'rxjs/operators';
import { objectNotNull } from 'apps/sales/src/app/core/utils/app.utils';

@Component({
  selector: 'app-shelf-article-details',
  templateUrl: './article-details.component.html',
  styleUrls: ['./article-details.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ShelfArticleDetailsComponent implements OnInit, OnDestroy {
  destroy$ = new Subject();
  features: { [key: string]: string };
  showPayment = false;
  isPayed = false;
  isPreorder = false;
  available = true;

  @Input() paymentType: string;
  @Input() paymentReferenceNumber: string;
  @Input() expand = false;
  @Input() set article(val: OrderItemDTO) {
    if (val) {
      this._article.orderId = val.order.id;
      if (val.product) {
        this._article.title = val.product.contributors ? val.product.contributors + ' - ' + val.product.name : val.product.name;
        this._article.coverUrl = val.product.ean;
        this._article.isbn = val.product.ean;
      }

      if (val.grossPrice && val.grossPrice.value) {
        this._article.price = val.grossPrice.value.value;
        this._article.currency = val.grossPrice.value.currency;
      }

      if (val.subsetItems && val.subsetItems.length > 0) {
        const quantity = val.subsetItems
          .filter((subItems) => subItems && subItems.data && subItems.data.quantity)
          .map((subItems) => subItems.data.quantity)
          .reduce((q1, q2) => q1 + q2);
        this._article.quantity = `${quantity ? quantity : 0}x`;
      }

      if (val.features && val.features['fsk']) {
        this._article.fsk = val.features['fsk'];
      }

      if (val.grossPrice && val.grossPrice.vat && val.grossPrice.vat.vatType) {
        this._article.mwst = val.grossPrice.vat.inPercent + '%';
      }

      if (
        val.subsetItems &&
        val.subsetItems[0] &&
        val.subsetItems[0].data &&
        val.subsetItems[0].data.ssc &&
        val.subsetItems[0].data.sscText
      ) {
        this._article.messageNumber = val.subsetItems[0].data.ssc + ' - ' + val.subsetItems[0].data.sscText;
      }

      if (
        val.subsetItems &&
        val.subsetItems[0] &&
        val.subsetItems[0].data &&
        val.subsetItems[0].data.supplier &&
        val.subsetItems[0].data.supplier.id
      ) {
        this.store
          .select(SupplierState.getSuppliers)
          .pipe(
            filter((data) => objectNotNull(data)),
            take(1)
          )
          .subscribe((suppliers) => {
            if (suppliers && suppliers[val.subsetItems[0].data.supplier.id]) {
              this._article.supplier = suppliers[val.subsetItems[0].data.supplier.id].name;
            }
          });
      }

      if (val.subsetItems && val.subsetItems[0] && val.subsetItems[0].data && val.subsetItems[0].data.features) {
        this.features = val.subsetItems[0].data.features;
      }

      if (val.subsetItems && val.subsetItems[0] && val.subsetItems[0].data && val.subsetItems[0].data.specialComment) {
        this._article.remark = val.subsetItems[0].data.specialComment;
      }

      if (val.subsetItems && val.subsetItems[0] && val.subsetItems[0].data && val.subsetItems[0].data.processingStatus) {
        const status = val.subsetItems[0].data.processingStatus;
        if (status === OrderStatus.NotAvailable) {
          this.available = false;
        }
        if (status === OrderStatus.Fetched) {
          this.showPayment = true;
          if (val.invoiceText) {
            this._article.invoiceText = val.invoiceText;
          }
          if (val.order.id) {
            this.getReceiptData(val.order.id);
          }
        } else {
          this.showPayment = false;
        }
      }

      if (val.subsetItems && val.subsetItems[0] && val.subsetItems[0].data && !isNullOrUndefined(val.subsetItems[0].data.isPrebooked)) {
        this.isPreorder = val.subsetItems[0].data.isPrebooked;
      }

      this.cdrf.detectChanges();
    }
  }
  @Input() set clientChannel(val: EnvironmentChannel) {
    if (val) {
      this._article.orderChanel = orderChannelMapper[val];
      this.cdrf.detectChanges();
    }
  }
  @Input() set targetBranch(val: number) {
    if (val) {
      const branches = this.store.selectSnapshot(BranchSelectors.getBranches);
      if (branches && branches[val]) {
        this._article.targetBranch = branches[val].name;
        this.cdrf.detectChanges();
      }
    }
  }
  @Input() set logistician(val: LogisticianDTO) {
    if (val) {
      // this._article.supplier = val.name;
      // this.cdrf.detectChanges();
    }
  }

  get isSubscription() {
    if (this.features) {
      return !isNullOrUndefined(this.features['subscription']);
    }
    return false;
  }

  get isGift() {
    if (this.features) {
      return !isNullOrUndefined(this.features['promotion']);
    }
    return false;
  }

  get isPayment() {
    return this.isPayed;
  }

  _article: {
    orderId?: number;
    title?: string;
    coverUrl?: string;
    price?: number;
    currency?: string;
    quantity?: string;
    isbn?: string;
    fsk?: string;
    supplier?: string;
    orderChanel?: string;
    targetBranch?: string;
    mwst?: string;
    messageNumber?: string;
    remark?: string;
    invoiceText?: string;
    receiptNumber?: string;
    receiptType?: string;
    printedDate?: string;
    placeOfPayment?: string;
  } = {
    title: '-',
    coverUrl: '-',
    currency: '-',
    quantity: '-',
    isbn: '-',
    fsk: '-',
    supplier: '-',
    orderChanel: '-',
    targetBranch: '-',
    mwst: '-',
    messageNumber: '-',
    remark: undefined,
    invoiceText: '-',
    receiptNumber: '-',
    receiptType: '-',
    printedDate: '-',
    placeOfPayment: '-',
  };

  constructor(
    private store: Store,
    private cdrf: ChangeDetectorRef,
    private shelfService: CollectingShelfService,
    private datePipe: DatePipe
  ) {}

  ngOnInit() {}

  ngOnDestroy() {
    this.destroy$.next();
  }

  getReceiptData(orderId: number) {
    this.shelfService
      .getReceipt(orderId)
      .toPromise()
      .then((receiptList: ReceiptListItemDTO[]) => {
        if (receiptList && receiptList.length > 0) {
          const receipt = receiptList[0];
          this._article.receiptNumber = receipt.receiptNumber;
          this._article.receiptType = receiptType[receipt.receiptType];
          if (receipt.printedDate) {
            this._article.printedDate = this.datePipe.transform(receipt.printedDate, 'dd.MM.yy | HH:mm') + ' Uhr';
          }
          this._article.placeOfPayment = receipt.placeOfPayment;
          if (receipt.paidAt && !isNullOrUndefined(receipt.paidAt)) {
            this.isPayed = true;
          } else {
            this.isPayed = false;
          }
          this.cdrf.detectChanges();
        }
      })
      .catch((error) => {
        console.error(error);
      });
  }
}
