cartStore.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. class CartStore {
  2. constructor() {
  3. this.storageKey = 'shopping_cart';
  4. this.currentShopId = ''; // 当前店铺ID
  5. }
  6. // 设置当前店铺ID
  7. setShopId() {
  8. this.currentShopId = uni.getStorageSync('shop_id');
  9. }
  10. // 获取购物车数据
  11. getCart() {
  12. try {
  13. const cartStr = uni.getStorageSync(this.storageKey);
  14. if (!cartStr) {
  15. return {};
  16. }
  17. return JSON.parse(cartStr);
  18. } catch (e) {
  19. console.error('获取购物车失败:', e);
  20. return {};
  21. }
  22. }
  23. // 保存购物车数据
  24. saveCart(cartData) {
  25. try {
  26. uni.setStorageSync(this.storageKey, JSON.stringify(cartData));
  27. } catch (e) {
  28. console.error('保存购物车失败:', e);
  29. }
  30. }
  31. // 获取指定店铺的购物车
  32. getShopCart(shopId = null) {
  33. const cart = this.getCart();
  34. const targetShopId = shopId || this.currentShopId;
  35. if (!targetShopId) return null;
  36. if (!cart[targetShopId]) {
  37. cart[targetShopId] = {
  38. total_price: 0,
  39. total_num: 0,
  40. goods_list: [],
  41. shop_info: null
  42. };
  43. this.saveCart(cart);
  44. }
  45. return cart[targetShopId];
  46. }
  47. // 添加商品到购物车
  48. addToCart(goods, goodsSpec = [], quantity = 1) {
  49. if (!this.currentShopId) {
  50. console.error('未设置店铺ID');
  51. return false;
  52. }
  53. const cart = this.getCart();
  54. if (!cart[this.currentShopId]) {
  55. cart[this.currentShopId] = {
  56. total_price: 0,
  57. total_num: 0,
  58. goods_list: [],
  59. shop_info: null
  60. };
  61. }
  62. const shopCart = cart[this.currentShopId];
  63. // 生成商品唯一标识(结合商品ID和规格ID)
  64. const specIdStr = goodsSpec.length > 0
  65. ? goodsSpec.map(spec => `${spec.id}_${spec.number}`).sort().join('_')
  66. : 'no_spec';
  67. const goodsKey = `${goods.goods_id}_${specIdStr}`;
  68. // 查找是否已存在相同商品
  69. const existingIndex = shopCart.goods_list.findIndex(
  70. item => this.getGoodsKey(item) === goodsKey
  71. );
  72. if (existingIndex > -1) {
  73. // 已存在,更新数量
  74. shopCart.goods_list[existingIndex].goods_number += quantity;
  75. } else {
  76. // 新商品,添加到列表
  77. shopCart.goods_list.push({
  78. goods_id: goods.goods_id,
  79. goods_name: goods.goods_name || '',
  80. goods_image: goods.goods_image || '',
  81. price: this.calculatePrice(goods, goodsSpec),
  82. goods_number: quantity,
  83. goods_attr: this.getSpecAttr(goodsSpec),
  84. goods_spec: goodsSpec,
  85. category_id: goods.category_id,
  86. goods_desc: goods.goods_desc || '',
  87. spec_type: goods.spec_type || 1
  88. });
  89. }
  90. // 重新计算总计
  91. this.calculateTotals(shopCart);
  92. // 保存到本地存储
  93. this.saveCart(cart);
  94. return true;
  95. }
  96. // 更新商品数量
  97. updateQuantity(goodsId, goodsSpec = [], quantity) {
  98. if (!this.currentShopId) return false;
  99. const cart = this.getCart();
  100. const shopCart = cart[this.currentShopId];
  101. if (!shopCart) return false;
  102. const specIdStr = goodsSpec.length > 0
  103. ? goodsSpec.map(spec => `${spec.id}_${spec.number}`).sort().join('_')
  104. : 'no_spec';
  105. const goodsKey = `${goodsId}_${specIdStr}`;
  106. const goodsIndex = shopCart.goods_list.findIndex(
  107. item => this.getGoodsKey(item) === goodsKey
  108. );
  109. if (goodsIndex > -1) {
  110. if (quantity <= 0) {
  111. // 数量为0,移除商品
  112. shopCart.goods_list.splice(goodsIndex, 1);
  113. } else {
  114. // 更新数量
  115. shopCart.goods_list[goodsIndex].goods_number = quantity;
  116. }
  117. // 重新计算总计
  118. this.calculateTotals(shopCart);
  119. this.saveCart(cart);
  120. return true;
  121. }
  122. return false;
  123. }
  124. // 从购物车移除商品
  125. removeFromCart(goodsId, goodsSpec = []) {
  126. return this.updateQuantity(goodsId, goodsSpec, 0);
  127. }
  128. // 清空当前店铺购物车
  129. clearCurrentShopCart() {
  130. if (!this.currentShopId) return false;
  131. const cart = this.getCart();
  132. cart[this.currentShopId] = {
  133. total_price: 0,
  134. total_num: 0,
  135. goods_list: []
  136. };
  137. this.saveCart(cart);
  138. return true;
  139. }
  140. // 计算商品价格
  141. calculatePrice(goods, goodsSpec = []) {
  142. let price = goods.seckill_money > 0 ? Number(goods.seckill_money) : Number(goods.price);
  143. // 如果有规格,累加规格价格
  144. if (goodsSpec.length > 0) {
  145. goodsSpec.forEach(spec => {
  146. // 这里需要根据实际情况获取规格价格
  147. // 假设规格信息中包含价格
  148. if (spec.price) {
  149. price += Number(spec.price) * (spec.number || 1);
  150. }
  151. });
  152. }
  153. return Number(price).toFixed(2);
  154. }
  155. // 获取规格描述
  156. getSpecAttr(goodsSpec = []) {
  157. if (goodsSpec.length === 0) return '';
  158. return goodsSpec.map(spec => spec.name || '').join('、');
  159. }
  160. // 生成商品唯一键
  161. getGoodsKey(goodsItem) {
  162. const specIdStr = goodsItem.goods_spec && goodsItem.goods_spec.length > 0
  163. ? goodsItem.goods_spec.map(spec => `${spec.id}_${spec.number}`).sort().join('_')
  164. : 'no_spec';
  165. return `${goodsItem.goods_id}_${specIdStr}`;
  166. }
  167. // 计算购物车总计
  168. calculateTotals(shopCart) {
  169. let total_price = 0;
  170. let total_num = 0;
  171. shopCart.goods_list.forEach(item => {
  172. total_price += item.price * item.goods_number;
  173. total_num += item.goods_number;
  174. });
  175. shopCart.total_price = parseFloat(total_price.toFixed(2));
  176. shopCart.total_num = total_num;
  177. }
  178. // 获取商品在购物车中的数量
  179. getGoodsQuantity(goodsId, goodsSpec = []) {
  180. if (!this.currentShopId) return 0;
  181. const cart = this.getCart();
  182. const shopCart = cart[this.currentShopId];
  183. if (!shopCart) return 0;
  184. const specIdStr = goodsSpec.length > 0
  185. ? goodsSpec.map(spec => `${spec.id}_${spec.number}`).sort().join('_')
  186. : 'no_spec';
  187. const goodsKey = `${goodsId}_${specIdStr}`;
  188. const goodsItem = shopCart.goods_list.find(
  189. item => this.getGoodsKey(item) === goodsKey
  190. );
  191. return goodsItem ? goodsItem.goods_number : 0;
  192. }
  193. // 获取指定店铺购物车中某商品的总数量(所有规格合并)
  194. getGoodsTotalQuantity(goodsId) {
  195. if (!this.currentShopId) return 0;
  196. const cart = this.getCart();
  197. const shopCart = cart[this.currentShopId];
  198. if (!shopCart) return 0;
  199. let total = 0;
  200. shopCart.goods_list.forEach(item => {
  201. if (item.goods_id === goodsId) {
  202. total += item.goods_number;
  203. }
  204. });
  205. return total;
  206. }
  207. }
  208. // 创建单例
  209. const cartStore = new CartStore();
  210. export default cartStore;