const app = getApp(); const regeneratorRuntime = app.loadAsync() const { StorageSync } = require("./getSetting") const util = app.loadUtils("util") const { Msg } = require("../model/message") const msg = new Msg() export class ShopCart extends StorageSync { constructor() { super() } /** * 获取本地购物车缓存如果没有数据返回空数组 */ async getCart() { let that = this let shopCart = await that.getSetting("shopCart") if (typeof shopCart === 'undefined') { await this.setStorage("shopCart", []) return await [] } return await shopCart } /** * * @param { Object } data 放到购物中的数据 */ async setCart(data) { let getCart = await this.getCart() if (data.num <= 0) { data.num = ++data.num } if (getCart.length <= 0) { getCart.push(data) } else { for (let i = 0; i < getCart.length; i++) { if (util.Compare(getCart[i], data, "num")) { getCart[i].num += data.num break; } if (getCart.length - 1 == i) { getCart.push(data) break; } } } this.setStorage("shopCart", getCart) // 更新角标 app.globalData.cartNum = getCart.length wx.showToast({ title: '添加成功,在购物车等亲~', icon: 'none', duration: 800 }) } /** * * @param { Object } data 已经更新过的数据 */ async updateCart(data) { let that = this let getCart = await this.getCart() for (let i = 0; i < getCart.length; i++) { if (util.Compare(getCart[i], data, "num")) { if (data.num == 0) { getCart.splice(i, 1) break; } getCart[i].num = data.num break; } } return new Promise((resolve, reject) => { if (data.num == 0) { wx.showModal({ title: '删除该商品', content: '点击确定删除', confirmText: "确认", cancelText: "取消", async success(res) { if (res.confirm) { that.setStorage("shopCart", getCart) // 更新角标 app.globalData.cartNum = getCart.length resolve(getCart) } } }) } else { this.setStorage("shopCart", getCart) // 更新角标 app.globalData.cartNum = getCart.length resolve(getCart) } }) } /** * */ async getCartMon() { let cart = await this.getCart() let totalprice = 0 cart.map((v, i) => { totalprice += v.num * v.price }) return totalprice } /** * 购物车删除商品 * @param { Object } data 需要删除的商品id */ async deleteCart(data) { let getCart = await this.getCart() let newCart = [] let newData = data.allCart newData.map((v, i) => { if (typeof v.isShow == 'boolean') { delete newData[i].isShow } }) getCart.map((v, i) => { let n = newData.filter(n => { return util.Compare(v, n, "num") }) if (n.length <= 0) { newCart.push(v) } }) this.setStorage("shopCart", newCart) // 更新角标 app.globalData.cartNum = newCart.length } }