import { Component, OnInit, Input } from '@angular/core';
import { OrderItemListItemDTO } from '@swagger/oms';
import { orderStatusMapper } from 'apps/sales/src/app/core/mappings/shelf.mapping';
import { isNullOrUndefined } from 'util';
import { Store } from '@ngxs/store';
import { Router } from '@angular/router';
import { AddBreadcrumb } from 'apps/sales/src/app/core/store/actions/breadcrumb.actions';
import { SetBranchProcessCurrentPath } from 'apps/sales/src/app/core/store/actions/branch-process.actions';
import { GOODS_IN_SCROLL_INDEX } from 'apps/sales/src/app/core/utils/app.constants';
import { AppState } from 'apps/sales/src/app/core/store/state/app.state';

@Component({
  selector: 'app-goods-in-order-card',
  templateUrl: './goods-in-order-card.component.html',
  styleUrls: ['./goods-in-order-card.component.scss'],
})
export class GoodsInOrderCardComponent implements OnInit {
  @Input() set orderItem(val: OrderItemListItemDTO) {
    if (val) {
      this.processingStatus = orderStatusMapper[val.processingStatus];
      this.showStatusCheckMark = this.positiveStatuses[val.processingStatus] ? true : false;
      this.showStatusXMark = this.negativeStatuses[val.processingStatus] ? true : false;
      this.features = val.features;
      this.isPreorder = val.isPrebooked;
    }
    this.item = val;
  }
  @Input() isChildItem: boolean;
  @Input() first: boolean;
  @Input() last: boolean;
  @Input() hasTrailingItem: boolean;
  @Input() index: number;
  processingStatus: string;
  item: OrderItemListItemDTO;
  features: { [key: string]: string };
  isPreorder = false;
  positiveStatuses = {
    16: true,
    128: true,
    8192: true,
  };
  negativeStatuses = {
    512: true,
    1024: true,
    2048: true,
    4096: true,
    16777216: true,
  };
  showStatusXMark: boolean;
  showStatusCheckMark: boolean;

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

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

  constructor(private store: Store, private router: Router) {}

  ngOnInit() {}

  details() {
    const processId = this.store.selectSnapshot(AppState.getCurrentProcessId);
    sessionStorage.setItem(GOODS_IN_SCROLL_INDEX, this.index + ':' + processId);
    this.navigate(
      `/goodsin/details/${this.item.orderId}/${this.item.orderItemId}/${this.item.processingStatus}`,
      `${this.item.firstName} ${this.item.lastName}`
    );
  }

  navigate(path: string, name: string) {
    this.store.dispatch(
      new AddBreadcrumb(
        {
          name,
          path,
        },
        'goodsin'
      )
    );
    this.store.dispatch(new SetBranchProcessCurrentPath(path));
    this.router.navigate([path]);
  }
}
