import { defineStore } from 'pinia'
import type { Product } from './product'

export const useCartStore = defineStore('cart', () => {
  // 购物车商品列表
  const cartItems = ref<Array<{ product: Product; quantity: number }>>([])

  // 添加商品到购物车
  const addToCart = (product: Product, quantity: number = 1): boolean => {
    if (quantity > product.stock && product.stock !== -1) {
      return false;
    }
    const existingItem = cartItems.value.find(item => item.product.cellId === product.cellId)
    if (existingItem) {
      if (existingItem.quantity + quantity > product.stock && product.stock !== -1) {
        return false;
      }
      existingItem.quantity += quantity
    } else {
      cartItems.value.push({ product, quantity })
    }
    return true;
  }

  // 移除商品
  const removeFromCart = (cellId: number, quantity: number = 1) => {
    const index = cartItems.value.findIndex(item => item.product.cellId === cellId)
    if (index !== -1) {
      if (cartItems.value[index].quantity <= quantity) {
        cartItems.value.splice(index, 1)
      } else {
        cartItems.value[index].quantity -= quantity
      }
    }
  }

  // 计算总价
  const totalPrice = computed(() => {
    return cartItems.value.reduce((sum, item) => {
      return sum + (item.product.price || 0) * item.quantity
    }, 0)
  })

  //计算总数
  const totalQuantity = computed(() => {
    return cartItems.value.reduce((sum, item) => {
      return sum + item.quantity
    }, 0)  
  })

  // 清空购物车
  const clearCart = () => {
    cartItems.value = []
  }

  return { 
    cartItems, 
    addToCart, 
    removeFromCart, 
    totalPrice, 
    totalQuantity,
    clearCart 
  }
})

// 支持在setup外使用
export function useCartStoreOutside() {
  return useCartStore()
}
