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

const state = {
    kindCount: 0
}

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

const actions = {
    // 加入购物车
    async addToCart({ dispatch, rootGetters }, { skuId, productCount = 1, heUserId = 0 }) {

        if (!rootGetters.userId) {
            const pages = getCurrentPages()
            const page = pages[pages.length - 1]
            uni.setStorageSync('LOGIN_REDIRECT_URL', page.$page.fullPath)
            uni.redirectTo({ url: '/pages/authorize/login-custom' })
            return Promise.reject('用户未登录')
        }

        try {
            const res = await shoppingAddCart({ skuId, userId: rootGetters.userId, productCount, heUserId })
            dispatch('fetchCartKindCount')
            setTimeout(() => {
                uni.showToast({
                    icon: 'success',
                    title: '加入购物车成功',
                    mask: true
                })
            }, 200)

            return res
        } catch (e) {
            return Promise.reject(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) {
            return Promise.reject(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) {
            return Promise.reject(e)
        }
    },
    // 加减购物车商品更新到后台
    async updateProductCount({ dispatch }, { cartId, productCount }) {
        try {
            return updateProductCount({ cartId, productCount })
        } catch (e) {
            return Promise.reject(e)
        }
    },

    // 购物车商品规格更新
    async updateProductUnit({ dispatch }, { cartId, newSkuId, productCount }) {
        try {
            return updateProductUnit({ newSkuId, cartId, count: productCount })
        } catch (e) {
            return Promise.reject(e)
        }
    }
}

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