index.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import Dialog from 'tdesign-miniprogram/dialog/index';
  2. import { fetchCartGroupData, fetchCartItems, deleteCartItem, updateCartItemCount,getSwipe } from '../../services/cart/cart';
  3. import { getSkuDetail } from '../../services/sku/sku';
  4. import { objectToParamString } from '../../utils/util';
  5. import { getSingleCloudImageTempUrl, getCloudImageTempUrl } from '../../utils/cloudImageHandler';
  6. let updateCartItemCountTimeout = null;
  7. Component({
  8. data: {
  9. cartGroupData: null,
  10. cartItems: [],
  11. selectedCartItemNum: 0,
  12. allSelected: false,
  13. totalAmount: 0,
  14. loading: false,
  15. inited: false,
  16. imgSrcs: [], // 广告图数据
  17. },
  18. observers: {
  19. cartItems: function (cartItems) {
  20. const selectedCartItems = cartItems.filter((x) => x.selected === true);
  21. const selectedCartItemNum = selectedCartItems.length;
  22. const totalAmount = selectedCartItems.reduce((acc, cur) => acc + cur.count * cur.sku.price, 0);
  23. const allSelected = selectedCartItemNum === cartItems.length;
  24. this.setData({
  25. selectedCartItemNum,
  26. allSelected,
  27. totalAmount,
  28. });
  29. },
  30. },
  31. lifetimes: {
  32. attached: async function () {
  33. // console.log('called attached');
  34. // // 调用自定义tabbar的init函数,使页面与tabbar激活状态保持一致
  35. // this.getTabBar().init();
  36. // await this.setLoading();
  37. // await this.setDataPromise({ inited: true });
  38. // try {
  39. // await this.init();
  40. // } finally {
  41. // await this.unsetLoading();
  42. // }
  43. },
  44. },
  45. pageLifetimes: {
  46. show: async function () {
  47. // 调用自定义tabbar的init函数,使页面与tabbar激活状态保持一致
  48. this.getTabBar().init();
  49. await this.setLoading();
  50. try {
  51. await this.init();
  52. } finally {
  53. await this.unsetLoading();
  54. }
  55. },
  56. },
  57. methods: {
  58. async init() {
  59. const cartItems = (await fetchCartItems()).map((x) =>
  60. Object.assign(x, {
  61. selected: false,
  62. }),
  63. );
  64. await Promise.all(
  65. cartItems.map(async (cartItem) => {
  66. const skuId = cartItem.sku._id;
  67. const sku = await getSkuDetail(skuId);
  68. if (sku.image) {
  69. sku.image = await getSingleCloudImageTempUrl(sku.image);
  70. }
  71. cartItem.sku = sku;
  72. }),
  73. );
  74. await this.setDataPromise({
  75. cartItems,
  76. });
  77. // 加载广告图数据
  78. this.loadAdvertisementImages();
  79. },
  80. findGoods(spuId, skuId) {
  81. let currentStore;
  82. let currentActivity;
  83. let currentGoods;
  84. const { storeGoods } = this.data.cartGroupData;
  85. for (const store of storeGoods) {
  86. for (const activity of store.promotionGoodsList) {
  87. for (const goods of activity.goodsPromotionList) {
  88. if (goods.spuId === spuId && goods.skuId === skuId) {
  89. currentStore = store;
  90. currentActivity = currentActivity;
  91. currentGoods = goods;
  92. return {
  93. currentStore,
  94. currentActivity,
  95. currentGoods,
  96. };
  97. }
  98. }
  99. }
  100. }
  101. return {
  102. currentStore,
  103. currentActivity,
  104. currentGoods,
  105. };
  106. },
  107. // 注:实际场景时应该调用接口获取购物车数据
  108. getCartGroupData() {
  109. const { cartGroupData } = this.data;
  110. if (!cartGroupData) {
  111. return fetchCartGroupData();
  112. }
  113. return Promise.resolve({ data: cartGroupData });
  114. },
  115. // 选择单个商品
  116. // 注:实际场景时应该调用接口更改选中状态
  117. selectGoodsService({ spuId, skuId, isSelected }) {
  118. this.findGoods(spuId, skuId).currentGoods.isSelected = isSelected;
  119. return Promise.resolve();
  120. },
  121. // 全选门店
  122. // 注:实际场景时应该调用接口更改选中状态
  123. selectStoreService({ storeId, isSelected }) {
  124. const currentStore = this.data.cartGroupData.storeGoods.find((s) => s.storeId === storeId);
  125. currentStore.isSelected = isSelected;
  126. currentStore.promotionGoodsList.forEach((activity) => {
  127. activity.goodsPromotionList.forEach((goods) => {
  128. goods.isSelected = isSelected;
  129. });
  130. });
  131. return Promise.resolve();
  132. },
  133. // 加购数量变更
  134. // 注:实际场景时应该调用接口
  135. changeQuantityService({ spuId, skuId, quantity }) {
  136. this.findGoods(spuId, skuId).currentGoods.quantity = quantity;
  137. return Promise.resolve();
  138. },
  139. // 删除加购商品
  140. // 注:实际场景时应该调用接口
  141. deleteGoodsService({ spuId, skuId }) {
  142. function deleteGoods(group) {
  143. for (const gindex in group) {
  144. const goods = group[gindex];
  145. if (goods.spuId === spuId && goods.skuId === skuId) {
  146. group.splice(gindex, 1);
  147. return gindex;
  148. }
  149. }
  150. return -1;
  151. }
  152. const { storeGoods, invalidGoodItems } = this.data.cartGroupData;
  153. for (const store of storeGoods) {
  154. for (const activity of store.promotionGoodsList) {
  155. if (deleteGoods(activity.goodsPromotionList) > -1) {
  156. return Promise.resolve();
  157. }
  158. }
  159. if (deleteGoods(store.shortageGoodsList) > -1) {
  160. return Promise.resolve();
  161. }
  162. }
  163. if (deleteGoods(invalidGoodItems) > -1) {
  164. return Promise.resolve();
  165. }
  166. return Promise.reject();
  167. },
  168. onGoodsSelect({ detail: { goods } }) {
  169. const { cartItems } = this.data;
  170. const item = cartItems.find((x) => x._id === goods._id);
  171. if (item == null) {
  172. console.warn('Cart item not found!');
  173. return;
  174. }
  175. item.selected = !item.selected;
  176. this.setData({ cartItems });
  177. },
  178. // 加载广告图数据
  179. async loadAdvertisementImages() {
  180. try {
  181. const { images } = await getSwipe();
  182. console.log("获取到的广告图数据:", images);
  183. // 确保images是数组格式
  184. let handledImages = [];
  185. if (Array.isArray(images)) {
  186. handledImages = await getCloudImageTempUrl(images);
  187. }
  188. console.log("handledImages",handledImages[0]);
  189. this.setData({ imgSrcs: handledImages });
  190. } catch (error) {
  191. console.error("加载广告图失败:", error);
  192. }
  193. },
  194. onQuantityChange({ detail: { cartItemId, count } }) {
  195. const { cartItems } = this.data;
  196. const item = cartItems.find((x) => x._id === cartItemId);
  197. if (item == null) {
  198. console.warn('Cart item not found');
  199. return;
  200. }
  201. item.count = count;
  202. this.setData({ cartItems });
  203. this.debouncedUpdateCartItemCount({ cartItemId, count });
  204. },
  205. debouncedUpdateCartItemCount({ cartItemId, count }) {
  206. clearTimeout(updateCartItemCountTimeout);
  207. updateCartItemCountTimeout = setTimeout(async () => {
  208. this.setLoading();
  209. try {
  210. await updateCartItemCount({ cartItemId, count });
  211. } finally {
  212. this.unsetLoading();
  213. }
  214. }, 500);
  215. },
  216. goCollect() {
  217. /** 活动肯定有一个活动ID,用来获取活动banner,活动商品列表等 */
  218. const promotionID = '123';
  219. wx.navigateTo({
  220. url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
  221. });
  222. },
  223. goGoodsDetail({
  224. detail: {
  225. goods: {
  226. sku: {
  227. spu: { _id },
  228. },
  229. },
  230. },
  231. }) {
  232. wx.navigateTo({
  233. url: `/pages/goods/details/index?spuId=${_id}`,
  234. });
  235. },
  236. async onGoodsDelete({
  237. detail: {
  238. goods: { _id },
  239. },
  240. }) {
  241. try {
  242. await Dialog.confirm({
  243. context: this,
  244. closeOnOverlayClick: true,
  245. title: '确认删除该商品吗?',
  246. confirmBtn: '确定',
  247. cancelBtn: '取消',
  248. });
  249. this.setLoading();
  250. try {
  251. await deleteCartItem({ cartItemId: _id });
  252. const { cartItems } = this.data;
  253. this.setData({
  254. cartItems: cartItems.filter((x) => x._id !== _id),
  255. });
  256. } finally {
  257. this.unsetLoading();
  258. }
  259. } catch {
  260. console.warn('deletion is cancelled');
  261. }
  262. },
  263. onSelectAll() {
  264. const { cartItems, allSelected } = this.data;
  265. cartItems.forEach((x) => (x.selected = !allSelected));
  266. this.setData({ cartItems });
  267. },
  268. onToSettle() {
  269. wx.navigateTo({
  270. url: `/pages/order/order-confirm/index?${objectToParamString({
  271. type: 'cart',
  272. cartIds: this.data.cartItems
  273. .filter((x) => x.selected === true)
  274. .map((x) => x._id)
  275. .join(','),
  276. })}`,
  277. });
  278. },
  279. onGotoHome() {
  280. wx.switchTab({ url: '/pages/home/home' });
  281. },
  282. setLoading() {
  283. return this.setDataPromise({
  284. loading: true,
  285. });
  286. },
  287. unsetLoading() {
  288. return this.setDataPromise({
  289. loading: false,
  290. });
  291. },
  292. toggleLoading() {
  293. this.setData({
  294. loading: !this.data.loading,
  295. });
  296. },
  297. setDataPromise(data) {
  298. return new Promise((res) => {
  299. this.setData(data, () => res());
  300. });
  301. },
  302. },
  303. });