import { defineStore } from 'pinia' import router from '@/router' interface cartState { cartList: Api.myShoppingCart[] } export const useXsbCartStore = defineStore('xsb-cart', { state: (): cartState => ({ cartList: [], }), getters: { /** * 计算星闪豹购物车商品总数量 * @returns 购物车商品总数量 */ getTotalNum(): number { return this.cartList.map(it => it.skuList.map(its => its.num)).reduce((a, b) => a.concat(b), []).reduce((a, b) => a + b, 0) }, }, actions: { /** * 星闪豹加入购物车逻辑 * @param skuId 商品skuId * @param num 商品数量 * @param shopId 门店id */ async addCart(skuId: number, num: number, shopId: number) { return new Promise((resolve, reject) => { if (!skuId) { useGlobalToast().show({ msg: '请选择商品规格' }) return reject(new Error('请选择商品规格')) } const { userInfo, token } = storeToRefs(useUserStore()) if (!token.value) { useGlobalToast().show({ msg: '请先登录' }) setTimeout(() => { router.replace({ name: 'smqjh-login' }) }, 2000) return reject(new Error('请先登录')) } Apis.common.addShoppingCart({ data: { businessType: 'XSB', skuId, num, shopId, channelId: userInfo.value.channelId, }, }).then((res) => { this.getCartList() resolve(res) }) }) }, /** * 星闪豹获取购物车列表 */ async getCartList() { const { userInfo, token } = storeToRefs(useUserStore()) if (!unref(token)) { return } const res = await Apis.common.myShoppingCart({ data: { channelId: unref(userInfo).channelId, businessType: 'XSB', }, }) this.cartList = res.data }, /** * * @param ids * @returns 计算选中商品总价 */ async getCartAddGoodsPrice(ids: string): Promise { return new Promise((resolve, reject) => { uni.showLoading({ mask: true }) Apis.common.shoppingCartOrderConfirm({ pathParams: { ids, }, }).then((res) => { resolve(res.data) }).catch(err => reject(err)).finally(() => uni.hideLoading()) }) }, }, })