import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, of, Subject } from 'rxjs';
import { SharedSelectors } from '../../../../core/store/selectors/shared.selectors';
import { EditCustomerData } from '../../../../core/models/edit-customer.model';
import { Select, Store } from '@ngxs/store';
import { OrdersService } from '../../../../core/services/order.service';
import { switchMap, filter, takeUntil } from 'rxjs/operators';
import { OrderListItemDTO } from '@swagger/oms';
import { CustomerOrder, OrderType, OrderStatus } from '../../../../core/models/customer-order.model';
import { AddBreadcrumb } from '../../../../core/store/actions/breadcrumb.actions';
import { User } from '../../../../core/models/user.model';
import { Router } from '@angular/router';
import { ChangeCurrentRoute } from '../../../../core/store/actions/process.actions';
import { BranchSelectors } from '../../../../core/store/selectors/branch.selector';
import { isNullOrUndefined } from 'util';
import { BranchService } from 'apps/sales/src/app/core/services/branch.service';

@Component({
  selector: 'app-customer-orders-card',
  templateUrl: './customer-orders-card.component.html',
  styleUrls: ['./customer-orders-card.component.scss'],
})
export class CustomerOrdersCardComponent implements OnInit, OnDestroy {
  @Select(SharedSelectors.getCustomerEditData) customerEditData$: Observable<EditCustomerData>;
  orders: CustomerOrder[] = [];
  loading = true;
  customer: User;
  destroy$ = new Subject();
  customerId: number;

  constructor(private ordersService: OrdersService, private store: Store, private router: Router, private branchService: BranchService) {}

  ngOnInit() {
    this.customerEditData$
      .pipe(
        filter((data) => data && !isNullOrUndefined(data.customer) && this.customerId !== data.customer.id),
        switchMap((data: EditCustomerData) => {
          if (data.customer) {
            this.customer = data.customer;
            this.customerId = data.customer.id;
            return this.ordersService.getCustomerOrders(data.customer.customerId);
          } else {
            return of({});
          }
        }),
        takeUntil(this.destroy$)
      )
      .subscribe((orders: OrderListItemDTO[]) => {
        this.processOrders(orders);
      });
  }

  details(orderId: number) {
    const route = `/customer/${this.customer.id}/order/${orderId}`;
    this.store.dispatch(new ChangeCurrentRoute(route));
    this.store.dispatch(
      new AddBreadcrumb(
        {
          name: 'Bestelldetails',
          path: route,
        },
        'customer'
      )
    );
    this.router.navigate([route]);
  }

  private async processOrders(orders: OrderListItemDTO[]) {
    if (!Array.isArray(orders)) {
      return;
    }
    const customerOrders: CustomerOrder[] = [];
    const branches = await this.branchService.getOrderBranchList();
    if (branches && branches.length > 0) {
      orders.forEach((order: OrderListItemDTO) => {
        const branch = branches.find((t) => t && t.id === order.targetBranchId);
        customerOrders.push({
          id: order.orderId,
          date: order.orderDate,
          location: order.orderType === 2 ? '-' : branch ? branch.shortName : '-',
          price: order.orderValue,
          currency: order.currency,
          count: order.itemsCount,
          status: OrderStatus[order.processingStatus],
          type: OrderType[order.clientChannel],
        });
      });

      this.orders = customerOrders;
    }
    this.loading = false;
  }

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