import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import type { CartVO, CartItem } from '@/types'
import {
  getCartApi,
  addCartItemApi,
  updateCartQuantityApi,
  updateCartItemSelectedApi,
  updateCartAllSelectedApi,
  deleteCartItemApi,
  batchDeleteCartApi,
  clearCartApi
} from '@/api/cart'

/**
 * 购物车 Store
 *
 * 后端返回结构：CartVO { items, totalCount, selectedCount, totalAmount, selectedAmount, allSelected }
 * - 修改数量 / 选中 / 删除 / 清空均调用对应后端接口，再重新拉一次整体数据
 * - 这样后端统计字段(selectedAmount 等)始终与 items 一致
 */
export const useCartStore = defineStore('cart', () => {
  const items = ref<CartItem[]>([])
  const allSelected = ref(0)
  const loading = ref(false)

  const totalCount = computed(() => items.value.reduce((sum, it) => sum + it.quantity, 0))
  const selectedCount = computed(() =>
    items.value.filter(i => i.selected === 1).reduce((sum, it) => sum + it.quantity, 0)
  )
  const totalAmount = computed(() =>
    items.value.reduce((sum, it) => sum + (it.subtotal || 0), 0)
  )
  const selectedAmount = computed(() =>
    items.value
      .filter(i => i.selected === 1)
      .reduce((sum, it) => sum + (it.subtotal || 0), 0)
  )

  function applyCartVO(vo: CartVO) {
    items.value = vo.items || []
    allSelected.value = vo.allSelected ?? 0
  }

  async function fetchCart() {
    loading.value = true
    try {
      const vo = await getCartApi()
      applyCartVO(vo)
    } finally {
      loading.value = false
    }
  }

  async function addItem(productId: number, skuId: number, quantity: number) {
    await addCartItemApi({ productId, skuId, quantity })
    await fetchCart()
  }

  async function updateQuantity(skuId: number, quantity: number) {
    await updateCartQuantityApi({ skuId, quantity })
    await fetchCart()
  }

  async function toggleItemSelected(skuId: number, selected: 0 | 1) {
    await updateCartItemSelectedApi(skuId, selected)
    await fetchCart()
  }

  async function toggleAllSelected(selected: boolean) {
    await updateCartAllSelectedApi(selected ? 1 : 0)
    await fetchCart()
  }

  async function removeItem(skuId: number) {
    await deleteCartItemApi(skuId)
    await fetchCart()
  }

  async function batchRemove(skuIds: number[]) {
    await batchDeleteCartApi(skuIds)
    await fetchCart()
  }

  async function clear() {
    await clearCartApi()
    await fetchCart()
  }

  return {
    items,
    allSelected,
    loading,
    totalCount,
    selectedCount,
    totalAmount,
    selectedAmount,
    fetchCart,
    addItem,
    updateQuantity,
    toggleItemSelected,
    toggleAllSelected,
    removeItem,
    batchRemove,
    clear
  }
})
