shopping-cart.js 7.4 KB
// pages/shopping-cart/shopping-cart.js
let method = require("../../utils/reuqest.js")
Page({
  data: {
    checkType: 1,
    userData: {},
    startTime: '', //日历选择获取当天日期
    date: '',
    cartList: [],
    buyData: {
      price: 100
    },
    checkNum: 0,
    stockNum: '',

    // 购物车
    carts: [], // 购物车列表
    pitchCart: [], //选中商品
    pitchList: [], //选中商品id
    hasList: false, // 列表是否有数据
    totalPrice: 0, // 总价,初始为0
    selectAllStatus: true, // 全选状态,默认全选
    obj: {
      name: "hello"
    }
  },

  //地址信息
  // getAddress() {
  //   method.getRequest("/address", data => {
  //     if (data.statusCode == 0) {
  //       data.data.forEach((item, index) => {
  //         if (item.delFlag == 1) {
  //           this.setData({
  //             userData: item,
  //           })
  //         }
  //       })
  //     }
  //   })
  // },
  getAddress() {
    let index = wx.getStorageSync('addIndex')
    method.getRequest("/address", data => {
      if (data.statusCode == 0) {
        this.setData({
          userData: data.data[index],
        })
      }
    })
  },
  goAddress() {
    wx.navigateTo({
      url: '/pages/select-address/select-address',
    })
  },
  //配送时间
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  //获取当天时间
  getDayTime() {
    var myDate = new Date();
    var year = myDate.getFullYear();
    var month = myDate.getMonth();
    var day = myDate.getDate();
    var dayNow = year + '-' + (month + 1) + "-" + day;
    console.log(dayNow, 'daynow')
    this.setData({
      startTime: dayNow
    })
  },
  //查看详情
  goDetail(e) {
    let id = e.currentTarget.dataset.goodsid;
    console.log(id, 'id')
    wx.navigateTo({
      url: '/pages/product-detail/product-detail?id=' + id,
    })
  },
  //购物车事件
  // 选中事件
  selectList(e) {
    let list = [];
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    const selected = carts[index].selected;
    carts[index].selected = !selected;
    list.push(selected)
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
    this.getTotalNum();
  },

  //  删除当前商品
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    const cartIds = e.currentTarget.dataset.cartid;
    let carts = this.data.carts;
    carts.splice(index, 1);
    this.setData({
      carts: carts
    });
    method.deleteRequest("/cart/" + cartIds, data => {
      if (data.statusCode == 0) {
        wx.showToast({
          title: '删除成功',
          icon: 'none'
        })
      }
    })
    if (!carts.length) {
      this.setData({
        hasList: false
      });
    } else {
      this.getTotalPrice();
    }
  },

  // 全选
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts
    });
    this.getTotalPrice();
  },

  // 数量增加
  addCount(e) {
    const idx = e.currentTarget.dataset.index;
    const goodSkuId = e.currentTarget.dataset.goodskuid;
    let carts = this.data.carts;
    let num = carts[idx].num;
    carts.forEach((item, index) => {
      if (idx == index) {
        if (carts[idx].num >= carts[idx].goodsStock) {
          wx.showToast({
            title: '达到最大库存',
          })
          return false;
        } else {
          num = num + 1;
          // console.log(num,'num')
          // console.log(carts[index],'index')
          carts[idx].num = num;
          this.setData({
            carts: carts
          });
          method.postRequest("/cart/" + goodSkuId, {}, data => {
            if (data.statusCode == 0) {

            }
          })
          this.getTotalPrice();
          this.getTotalNum();
        }
      }

    })
  },

  //数量减少
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    const obj = e.currentTarget.dataset.obj;
    const goodSkuId = e.currentTarget.dataset.goodskuid;
    let carts = this.data.carts;
    let num = carts[index].num;
    if (num <= 1) {
      wx.showToast({
        title: '已经是最少了',
      })
      return false;
    }
    num = num - 1;
    carts[index].num = num;
    this.setData({
      carts: carts
    });
    method.postRequest("/cart/less/" + goodSkuId, {}, data => {
      if (data.statusCode == 0) {

      }
    })
    this.getTotalPrice();
    this.getTotalNum();
  },

  //计算总价
  getTotalPrice() {
    let carts = this.data.carts;
    let total = 0;
    for (let i = 0; i < carts.length; i++) {
      if (carts[i].selected) {
        total += carts[i].num * carts[i].goodsPrice;
      }
    }
    this.setData({
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  },
  //已选数量
  getTotalNum() {
    let carts = this.data.carts;
    let totalNum = 0;
    for (let i = 0; i < carts.length; i++) {
      if (carts[i].selected) {
        totalNum += carts[i].num
      }
    }
    this.setData({
      carts: carts,
      checkNum: totalNum
    })
  },
  //立即购买
  immediatelyPay() {
    if (this.data.checkNum == 0) {
      wx.showToast({
        title: '未选择购买商品',
        icon: 'none'
      })
      return false
    } else {
     
      wx.navigateTo({
        url: '/pages/cart-affirm-order/cart-affirm-order',
      })
      let carts = this.data.carts;
      for (let i = 0; i < carts.length; i++) {
        if (carts[i].selected && this.data.pitchList.indexOf(carts[i].cartId) == -1) {
          this.data.pitchList.push(carts[i].cartId)
          this.data.pitchCart.push(carts[i])
        }
      }
      wx.setStorageSync('date', this.data.date)
      console.log(this.data.date, 'datess')
      wx.removeStorageSync('time')
      wx.setStorageSync('pitchList', this.data.pitchList)
      wx.setStorageSync('pitchCart', this.data.pitchCart)
    }
  },
  //购物车为空
  goHome() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  onLoad: function (options) {
    this.getAddress();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    method.getRequest('/cart', data => {
      if (data.statusCode == 0) {
        this.setData({
          carts: data.data,
        })
      }
    })
    this.setData({
      hasList: true,
      carts: [{
        id: 1,
        title: '新鲜芹菜 半斤',
        desc: '商品描述商品描述',
        image: '/images/demo/s5.png',
        num: 4,
        price: 0.01,
        selected: false
      }]
    });
    this.getTotalPrice();
    this.getAddress() //获取默认地址
    this.getDayTime() //获取当太日期
    this.setData({ //每次购物车下单重新选择商品
      pitchCart: [],
      pitchList: []
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})