import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface CartItem {
  id: number
  productId: number
  productName: string
  productImg: string
  spec: string
  price: number
  quantity: number
  checked: boolean
}

export const useCartStore = defineStore('cart', () => {
  const cartList = ref<CartItem[]>([])

  // 购物车数量
  const cartCount = computed(() => cartList.value.reduce((sum, item) => sum + item.quantity, 0))

  // 选中的商品
  const checkedItems = computed(() => cartList.value.filter(item => item.checked))

  // 选中商品总价
  const checkedTotal = computed(() => 
    checkedItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
  )

  // 添加到购物车
  const addToCart = (product: Omit<CartItem, 'id' | 'checked'>) => {
    const existItem = cartList.value.find(
      item => item.productId === product.productId && item.spec === product.spec
    )
    if (existItem) {
      existItem.quantity += product.quantity
    } else {
      cartList.value.push({
        ...product,
        id: Date.now(),
        checked: true
      })
    }
  }

  // 更新数量
  const updateQuantity = (id: number, quantity: number) => {
    const item = cartList.value.find(item => item.id === id)
    if (item) {
      item.quantity = Math.max(1, quantity)
    }
  }

  // 删除商品
  const removeFromCart = (id: number) => {
    const index = cartList.value.findIndex(item => item.id === id)
    if (index > -1) {
      cartList.value.splice(index, 1)
    }
  }

  // 切换选中状态
  const toggleChecked = (id: number) => {
    const item = cartList.value.find(item => item.id === id)
    if (item) {
      item.checked = !item.checked
    }
  }

  // 全选/取消全选
  const toggleAllChecked = (checked: boolean) => {
    cartList.value.forEach(item => {
      item.checked = checked
    })
  }

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

  return {
    cartList,
    cartCount,
    checkedItems,
    checkedTotal,
    addToCart,
    updateQuantity,
    removeFromCart,
    toggleChecked,
    toggleAllChecked,
    clearCart
  }
})
