import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

export interface CartItem {
  id: number;
  name: string;
  price: number;
  quantity: number;
  imageUrl?: string; // 可选属性
}

@Injectable({
  providedIn: 'root'
})
export class CartService {
  private cartItemsSubject = new BehaviorSubject<CartItem[]>([]);
  public cartItems$ = this.cartItemsSubject.asObservable();

  constructor() {}

  addToCart(item: CartItem) {
    let updatedCart = [...this.cartItemsSubject.value];
    const existingItemIndex = updatedCart.findIndex(i => i.id === item.id);

    if (existingItemIndex >= 0) {
      // 如果药品已经在购物车中，则增加数量
      updatedCart[existingItemIndex].quantity += item.quantity;
    } else {
      // 否则，添加新的药品到购物车
      updatedCart.push(item);
    }

    this.cartItemsSubject.next(updatedCart);
  }

  removeFromCart(itemId: number) {
    const updatedCart = this.cartItemsSubject.value.filter(item => item.id !== itemId);
    this.cartItemsSubject.next(updatedCart);
  }

  updateCartItem(itemId: number, newQuantity: number) {
    const updatedCart = this.cartItemsSubject.value.map(item =>
      item.id === itemId ? { ...item, quantity: newQuantity } : item
    );

    this.cartItemsSubject.next(updatedCart);
  }

  clearCart() {
    this.cartItemsSubject.next([]);
  }

  getCartTotal(): number {
    return this.cartItemsSubject.value.reduce((total, item) => total + item.price * item.quantity, 0);
  }
}