闫增涛
2024-12-20 55949f95a609733d1771d5b017d679cd7d1f005d
pages/cart/index.js
@@ -1,294 +1,355 @@
import Dialog from 'tdesign-miniprogram/dialog/index';
const app = getApp();
import {
  loginInfo
} from '../../assets/js/login';
import {
  getPublicImage
} from '../../assets/js/middleGround/tool';
import Toast from 'tdesign-miniprogram/toast/index';
import { fetchCartGroupData } from '../../services/cart/cart';
Page({
  data: {
    cartGroupData: null,
    price: '',
    loading: true,
    hidden: true,
    swipeOpened: false,
    onDisabled: false,
    imgUrl: [],
    shoppingCartData: [],
    checkAll: false,
    checkedList: [],
    selectedCount: 0,
    totalPrice: 0.00,
    type: '',
    start: 1,
    totalSize: '',
    isMore: null,
    bookId: '',
    bookName: ''
  },
  // 调用自定义tabbar的init函数,使页面与tabbar激活状态保持一致
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: '购物车'
    });
    this.shoppingCartGet();
    this.setData({
      swipeOpened: true
    })
  },
  onShow() {
    this.getTabBar().init();
    this.setData({
      swipeOpened: false
    })
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        active: 3
      })
    }
    this.shoppingCartGet();
    this.setData({
      totalPrice: 0.00,
      selectedCount: 0,
      checkAll: false,
    })
  },
  onLoad() {
    this.refreshData();
  },
  refreshData() {
    this.getCartGroupData().then((res) => {
      let isEmpty = true;
      const cartGroupData = res.data;
      // 一些组件中需要的字段可能接口并没有返回,或者返回的数据结构与预期不一致,需要在此先对数据做一些处理
      // 统计门店下加购的商品是否全选、是否存在缺货/无货
      for (const store of cartGroupData.storeGoods) {
        store.isSelected = true; // 该门店已加购商品是否全选
        store.storeStockShortage = false; // 该门店已加购商品是否存在库存不足
        if (!store.shortageGoodsList) {
          store.shortageGoodsList = []; // 该门店已加购商品如果库存为0需单独分组
        }
        for (const activity of store.promotionGoodsList) {
          activity.goodsPromotionList = activity.goodsPromotionList.filter((goods) => {
            goods.originPrice = undefined;
            // 统计是否有加购数大于库存数的商品
            if (goods.quantity > goods.stockQuantity) {
              store.storeStockShortage = true;
            }
            // 统计是否全选
            if (!goods.isSelected) {
              store.isSelected = false;
            }
            // 库存为0(无货)的商品单独分组
            if (goods.stockQuantity > 0) {
              return true;
            }
            store.shortageGoodsList.push(goods);
            return false;
          });
          if (activity.goodsPromotionList.length > 0) {
            isEmpty = false;
          }
        }
        if (store.shortageGoodsList.length > 0) {
          isEmpty = false;
        }
  // 金额显示.00格式
  numFormat(value) {
    if (!value) return "0.00";
    value = Number(value).toFixed(2);
    var intPart = Math.trunc(value); // 获取整数部分
    var intPartFormat = intPart
      .toString()
      .replace(/(\d)(?=(?:\d{3})+$)/g, "$1,"); // 将整数部分逢三一断
    var floatPart = ".00"; // 预定义小数部分
    var value2Array = value.split(".");
    // =2表示数据有小数位
    if (value2Array.length === 2) {
      floatPart = value2Array[1].toString(); // 拿到小数部分
      if (floatPart.length === 1) {
        return `${intPartFormat}.${floatPart}0`;
      }
      cartGroupData.invalidGoodItems = cartGroupData.invalidGoodItems.map((goods) => {
        goods.originPrice = undefined;
        return goods;
      return `${intPartFormat}.${floatPart}`;
    }
    return intPartFormat + floatPart;
  },
  onDelete(e) {
    const item = e.currentTarget.dataset.item;
    app.MG.store.delShoppingCart({
      ids: [item.id]
    }).then(res => {
      this.shoppingCartGet();
      wx.showToast({
        title: '删除图书成功',
        icon: 'none'
      });
      cartGroupData.isNotEmpty = !isEmpty;
      this.setData({ cartGroupData });
      this.setData({
        totalPrice: 0.00,
        selectedCount: 0,
        checkAll: false,
      })
    });
  },
  findGoods(spuId, skuId) {
    let currentStore;
    let currentActivity;
    let currentGoods;
    const { storeGoods } = this.data.cartGroupData;
    for (const store of storeGoods) {
      for (const activity of store.promotionGoodsList) {
        for (const goods of activity.goodsPromotionList) {
          if (goods.spuId === spuId && goods.skuId === skuId) {
            currentStore = store;
            currentActivity = currentActivity;
            currentGoods = goods;
            return {
              currentStore,
              currentActivity,
              currentGoods,
            };
          }
        }
      }
    }
    return {
      currentStore,
      currentActivity,
      currentGoods,
  shoppingCartGet() {
    let query = {
      start: 0,
      size: this.data.start * 4,
      filterList: [],
      searchList: []
    };
  },
    app.MG.store.getShoppingCartProductList(query).then(res => {
      console.log(res.datas);
      this.setData({
        totalSize: res.totalSize
      })
      res.datas.forEach(item => {
        this.setData({
          bookId: res.id,
          bookName: res.name,
          price: item.saleMethod.price.toFixed(2),
        })
        item.imgUrl = getPublicImage(item.productMonWithLinkDto.product.icon, '', '160');
        // this.setData({
        //   type: item.saleMethod.type == 'createProductItemSaleMethod' ? 'item' : 'product'
        // })
        const type = item.saleMethod.type == 'createProductItemSaleMethod' ? 'item' : 'product';
        item.type = type; // 将type设置为item对象的属性,而不是使用setData
        item.name = item.linkCmsItems[0].name ? item.productMonWithLinkDto.product.name + ':' + item.linkCmsItems[0].name : item.productMonWithLinkDto.product.name
        item.saleMethod.price = this.numFormat(item.saleMethod.price)
        if (item.productMonWithLinkDto.links[0].storeRefCode == 'jsek_digitalTextbooks') {
          item.typeTxt = '数字教材'
          item.productType = "数字教材"
        } else if (item.productMonWithLinkDto.links[0].storeRefCode == 'jsek_digitalCourses') {
          item.typeTxt = '数字课程'
          item.productType = "数字课程"
        } else {
          item.typeTxt = '电子书'
          item.productType = "图书服务-电子书"
  // 注:实际场景时应该调用接口获取购物车数据
  getCartGroupData() {
    const { cartGroupData } = this.data;
    if (!cartGroupData) {
      return fetchCartGroupData();
    }
    return Promise.resolve({ data: cartGroupData });
  },
  // 选择单个商品
  // 注:实际场景时应该调用接口更改选中状态
  selectGoodsService({ spuId, skuId, isSelected }) {
    this.findGoods(spuId, skuId).currentGoods.isSelected = isSelected;
    return Promise.resolve();
  },
  // 全选门店
  // 注:实际场景时应该调用接口更改选中状态
  selectStoreService({ storeId, isSelected }) {
    const currentStore = this.data.cartGroupData.storeGoods.find((s) => s.storeId === storeId);
    currentStore.isSelected = isSelected;
    currentStore.promotionGoodsList.forEach((activity) => {
      activity.goodsPromotionList.forEach((goods) => {
        goods.isSelected = isSelected;
          if (item.saleMethod.type == 'createProductItemSaleMethod' || item.saleMethod.type == 'createProductFolderSaleMethod') {
            if (item.linkCmsItems[0].refCode == 'questionBank') {
              item.type = '云测试'
              item.productType = '图书服务-云测试'
            } else {
              item.typeTxt = '云学习'
              item.productType = "图书服务-云学习"
            }
          }
        }
        //
      });
      this.setData({
        shoppingCartData: res.datas
      });
      if (this.data.shoppingCartData.length === 0) {
        this.setData({
          onDisabled: true
        })
      } else {
        this.setData({
          onDisabled: false
        })
      }
      setTimeout(() => {
        this.setData({
          loading: false,
          hidden: false,
        })
      }, 600)
    });
    return Promise.resolve();
    wx.stopPullDownRefresh()
  },
  // 加购数量变更
  // 注:实际场景时应该调用接口
  changeQuantityService({ spuId, skuId, quantity }) {
    this.findGoods(spuId, skuId).currentGoods.quantity = quantity;
    return Promise.resolve();
  },
  // 删除加购商品
  // 注:实际场景时应该调用接口
  deleteGoodsService({ spuId, skuId }) {
    function deleteGoods(group) {
      for (const gindex in group) {
        const goods = group[gindex];
        if (goods.spuId === spuId && goods.skuId === skuId) {
          group.splice(gindex, 1);
          return gindex;
        }
      }
      return -1;
    }
    const { storeGoods, invalidGoodItems } = this.data.cartGroupData;
    for (const store of storeGoods) {
      for (const activity of store.promotionGoodsList) {
        if (deleteGoods(activity.goodsPromotionList) > -1) {
          return Promise.resolve();
        }
      }
      if (deleteGoods(store.shortageGoodsList) > -1) {
        return Promise.resolve();
      }
    }
    if (deleteGoods(invalidGoodItems) > -1) {
      return Promise.resolve();
    }
    return Promise.reject();
  },
  // 清空失效商品
  // 注:实际场景时应该调用接口
  clearInvalidGoodsService() {
    this.data.cartGroupData.invalidGoodItems = [];
    return Promise.resolve();
  },
  onGoodsSelect(e) {
    const {
      goods: { spuId, skuId },
      isSelected,
    } = e.detail;
    const { currentGoods } = this.findGoods(spuId, skuId);
    Toast({
      context: this,
      selector: '#t-toast',
      message: `${isSelected ? '选择' : '取消'}"${
        currentGoods.title.length > 5 ? `${currentGoods.title.slice(0, 5)}...` : currentGoods.title
      }"`,
      icon: '',
  bottomChange(e) {
    const checked = e.detail.value.length > 0;
    const items = this.data.shoppingCartData.map(item => {
      item.checked = checked;
      return item;
    });
    this.selectGoodsService({ spuId, skuId, isSelected }).then(() => this.refreshData());
    this.setData({
      shoppingCartData: items,
      checkAll: checked
    });
    this.calculateSelectedCount();
    this.calculateTotalPrice();
  },
  onStoreSelect(e) {
  HandelItemChange(e) {
    const {
      store: { storeId },
      isSelected,
    } = e.detail;
    this.selectStoreService({ storeId, isSelected }).then(() => this.refreshData());
      item
    } = e.target.dataset;
    const items = this.data.shoppingCartData
    items.map(eitem => {
      if (eitem.id == item.id) {
        eitem.checked = e.detail.checked
      }
    })
    const data = items.filter(item => item.checked)
    const checkAll = data.length == this.data.shoppingCartData.length
    this.setData({
      shoppingCartData: items,
      checkAll
    });
    this.calculateSelectedCount();
    this.calculateTotalPrice();
  },
  onQuantityChange(e) {
    const {
      goods: { spuId, skuId },
      quantity,
    } = e.detail;
    const { currentGoods } = this.findGoods(spuId, skuId);
    const stockQuantity = currentGoods.stockQuantity > 0 ? currentGoods.stockQuantity : 0; // 避免后端返回的是-1
    // 加购数量超过库存数量
    if (quantity > stockQuantity) {
      // 加购数量等于库存数量的情况下继续加购
      if (currentGoods.quantity === stockQuantity && quantity - stockQuantity === 1) {
  calculateSelectedCount() {
    const selectedItems = this.data.shoppingCartData.filter(item => item.checked);
    const selectedCount = selectedItems.length;
    this.setData({
      selectedCount
    });
  },
  calculateTotalPrice() {
    const selectedItems = this.data.shoppingCartData.filter(item => item.checked);
    const totalPrice = selectedItems.reduce((total, item) => total + parseFloat(item.saleMethod.price), 0);
    this.setData({
      totalPrice: totalPrice.toFixed(2)
    });
  },
  goPaymentPage() {
    // 首页测试登录功能,后续注释
    // 检查登录状态
    const token = wx.getStorageSync(app.config.tokenKey)
    if (!token) {
      loginInfo(app, (data) => {
        // 如果不是第一次登录,会执行回调
        if (data) {
          const selectedItems = this.data.shoppingCartData.filter(item => item.checked);
          // console.log(selectedItems, 789);
          const selectedIds = selectedItems.map(item => item.id);
          console.log('选中的商品 id:', selectedIds);
          if (selectedIds.length) {
            let data = {
              linkIds: selectedIds
            }
            // '&onNorderSaleMethod=' +
            app.MG.store.shoppingCartCreateOrder(data).then(res => {
              const url = '/pages/cart/paymentPage/index?orderNumber=' + res.orderNumber
              wx.navigateTo({
                url
              });
            })
          } else {
            Toast({
              context: this,
              selector: '#t-toast',
              message: '请选择商品',
              theme: 'warning',
              direction: 'column',
            });
          }
        } else {
          // 出现错误,返回false
        }
      })
    } else {
      const selectedItems = this.data.shoppingCartData.filter(item => item.checked);
      // console.log(selectedItems, 789);
      const selectedIds = selectedItems.map(item => item.id);
      console.log('选中的商品 id:', selectedIds);
      if (selectedIds.length) {
        let data = {
          linkIds: selectedIds
        }
        app.MG.store.shoppingCartCreateOrder(data).then(res => {
          console.log(res.saleMethodLinks[0].orderSaleMethod.id, 'ressss798');
          const url = '/pages/cart/paymentPage/index?orderNumber=' + res.orderNumber + '&onNorderSaleMethod=' + res.saleMethodLinks[0].orderSaleMethod.id
          wx.navigateTo({
            url
          });
        })
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '当前商品库存不足',
          message: '请选择商品',
          theme: 'warning',
          direction: 'column',
        });
        return;
      }
      Dialog.confirm({
        title: '商品库存不足',
        content: `当前商品库存不足,最大可购买数量为${stockQuantity}件`,
        confirmBtn: '修改为最大可购买数量',
        cancelBtn: '取消',
      })
        .then(() => {
          this.changeQuantityService({
            spuId,
            skuId,
            quantity: stockQuantity,
          }).then(() => this.refreshData());
        })
        .catch(() => {});
      return;
    }
    this.changeQuantityService({ spuId, skuId, quantity }).then(() => this.refreshData());
  },
  goCollect() {
    /** 活动肯定有一个活动ID,用来获取活动banner,活动商品列表等 */
    const promotionID = '123';
  },
  onLogin() {
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
      url: '/pages/testLogin/index'
    });
  },
  goGoodsDetail(e) {
    const { spuId, storeId } = e.detail.goods;
  onScrollToLower() {
    if (this.data.shoppingCartData.length < this.data.totalSize) {
      this.setData({
        isMore: true,
        start: this.data.start + 1
      })
      this.shoppingCartGet()
    } else {
      this.setData({
        isMore: true,
      })
      setTimeout(() => {
        this.setData({
          isMore: false
        })
        console.log('300');
      }, 300)
    }
  },
  // 下拉函数
  onPullDownRefresh() {
    this.setData({
      start: 1,
      checkAll: false,
      selectedCount: 0,
      totalPrice: 0.00,
    })
    console.log(978);
    this.shoppingCartGet()
  },
  async onBook(e) {
    const item = e.currentTarget.dataset.item
    console.log(item);
    const type = item.productMonWithLinkDto.links[0].storeRefCode
    let url = ''
    if (type == 'jsek_digitalCourses') {
      // 课程
      url = '/pages/digitalCourses/digitalCoursesDetails/index?id=' + item.productMonWithLinkDto.product.id + '&path=' + ''
    } else if (type == 'jsek_digitalTextbooks') {
      // 数字教材
      url = '/pages/digitalTextbooks/digitalTextbooksDetails/index?id=' + item.productMonWithLinkDto.product.id
    } else {
      let parentData = null;
      parentData = await app.MG.store.getProductBySaleMethod({
        'saleMethodId': item.saleMethod.id
      })
      console.log(parentData)
      let bookId = item.productMonWithLinkDto.product.id;
      if (parentData.parentProduct.length > 0) {
        bookId = parentData.parentProduct[parentData.parentProduct.length - 1].id;
      }
      url = '/packageBookService/pages/bookServices/detail/index?id=' + bookId + '&name=' + item.productMonWithLinkDto.product.name
    }
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${spuId}&storeId=${storeId}`,
    });
  },
  clearInvalidGoods() {
    // 实际场景时应该调用接口清空失效商品
    this.clearInvalidGoodsService().then(() => this.refreshData());
  },
  onGoodsDelete(e) {
    const {
      goods: { spuId, skuId },
    } = e.detail;
    Dialog.confirm({
      content: '确认删除该商品吗?',
      confirmBtn: '确定',
      cancelBtn: '取消',
    }).then(() => {
      this.deleteGoodsService({ spuId, skuId }).then(() => {
        Toast({ context: this, selector: '#t-toast', message: '商品删除成功' });
        this.refreshData();
      });
    });
  },
  onSelectAll(event) {
    const { isAllSelected } = event?.detail ?? {};
    Toast({
      context: this,
      selector: '#t-toast',
      message: `${isAllSelected ? '取消' : '点击'}了全选按钮`,
    });
    // 调用接口改变全选
  },
  onToSettle() {
    const goodsRequestList = [];
    this.data.cartGroupData.storeGoods.forEach((store) => {
      store.promotionGoodsList.forEach((promotion) => {
        promotion.goodsPromotionList.forEach((m) => {
          if (m.isSelected == 1) {
            goodsRequestList.push(m);
          }
        });
      });
    });
    wx.setStorageSync('order.goodsRequestList', JSON.stringify(goodsRequestList));
    wx.navigateTo({ url: '/pages/order/order-confirm/index?type=cart' });
  },
  onGotoHome() {
    wx.switchTab({ url: '/pages/home/home' });
  },
});
      url
    })
  }
});