import {
    removeProductFromCart,
    fetchCartProductCount,
    shoppingAddCart,
    updateProductCount
} from '@/services/api/cart.js'

const state = {
    kindCount: 0
}

const mutations = {
    SET_KIND_COUNT: (state, count) => {
        state.kindCount = count
    },
    // 设置购物车商品数量角标
    SET_TABBAR_BADGE: (state, num) => {
        console.log(num)
        if (num >= 100) {
            return uni.setTabBarBadge({ index: 2, text: '99+' })
        }
        if (num > 0) {
            return uni.setTabBarBadge({ index: 2, text: num.toString() })
        }
        uni.setTabBarBadge({ index: 2, text: undefined })
    },
}

const actions = {
    // 加入购物车
    async addToCart({ dispatch, rootGetters }, { productId, productCount = 1, heUserId = 0 }) {
        try {
            const res = await shoppingAddCart({ productId, userId: rootGetters.userId, productCount, heUserId })
            uni.showToast({ icon: 'success', title: '加入购物车成功' })
            dispatch('fetchCartKindCount')
            return res
        } catch (e) {
            console.log(e)
        }
    },
    // 获取购物车商品数量
    async fetchCartKindCount({ commit, rootGetters }) {
        try {
            const res = await fetchCartProductCount({ userId: rootGetters.userId })
            commit('SET_KIND_COUNT', res.data)
            commit('SET_TABBAR_BADGE', res.data)
            return res
        } catch (e) {
            console.log(e)
        }
    },
    // 从购物车移除
    async removeFromCart({ commit, dispatch }, cartIds = []) {
        try {
            const res = await removeProductFromCart({ cartIds: cartIds.join(',') })
            await dispatch('fetchCartKindCount')
            uni.showToast({ icon: 'success', title: '删除成功' })
            return res
        } catch (e) {
            console.log(e)
        }
    },
    // 加减购物车商品更新到后台
    async updateProductCount({ dispatch }, { cartId, productCount }) {
        try {
            return updateProductCount({ cartId, productCount })
        } catch (e) {
            console.log(e)
        }
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
