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

export const useCartStore = defineStore(
  'cart',
  () => {
    const cartTotalNum = ref(0)

    // 设置购物车商品总数量
    const setCartTotalNum = (num: number) => {
      cartTotalNum.value = num
    }

    //设置购物车角标
    const setCartTabBadge = () => {
      const cartTabbarIndex = 2
      if (cartTotalNum.value > 0) {
        uni.setTabBarBadge({
          index: cartTabbarIndex,
          text: `${cartTotalNum.value}`,
        })
      } else {
        uni.removeTabBarBadge({
          index: cartTabbarIndex,
        })
      }
    }

    return {
      cartTotalNum,
      setCartTotalNum,
      setCartTabBadge,
    }
  },
  {
    persist: {
      storage: {
        setItem(key: string, value: any) {
          return uni.setStorageSync(key, value)
        },
        getItem(key: string) {
          return uni.getStorageSync(key)
        },
      },
    },
  },
)
