shopping-cart.js 8.4 KB
// pages/shopping-cart/shopping-cart.js
let method = require("../../utils/reuqest.js")
const util = require("../../utils/util.js")
Page({
  data: {
    checkType: 1,
    userData: {},
    addHint: false, //判断有没有地址
    startTime: '', //日历选择获取当天日期
    date: '',
    cartList: [],
    buyData: {
      price: 100
    },
    checkNum: 0,
    stockNum: '',

    // 购物车
    carts: [], // 购物车列表
    pitchCart: [], //选中商品
    pitchList: [], //选中商品id
    hasList: false, // 列表是否有数据
    cartnoData: false, //购物车是否为空
    totalPrice: 0, // 总价,初始为0
    selectAllStatus: true, // 全选状态,默认全选
    obj: {
      name: "hello"
    }
  },
  //地址信息
  getAddress() {
    // if (wx.getStorageSync('addIndex')) {
    //   wx.removeStorageSync('addIndex')
    // }
    let index = wx.getStorageSync('addIndex')
    method.getRequest("/address", data => {
      if (data.statusCode == 0) {
        let list = data.data.reverse();
        this.setData({
          userData: list[index],
          addHint: true
        })
      }
    })
  },
  goAddress() {
    wx.navigateTo({
      url: '/pages/select-address/select-address',
    })
    wx.setStorageSync("shopCartAdd", 'true')
  },
  //没有登录
  goAddress1() {
    if (wx.getStorageSync('Authorization')) {
      wx.navigateTo({
        url: '/pages/select-address/select-address',
      })
      wx.setStorageSync("shopCartAdd", 'true')
    } else {
      wx.showToast({
        title: '请先登录!',
        icon: 'none'
      })
      setTimeout(() => {
        util.getUser();
      }, 2000)

    }

  },
  //配送时间
  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;
    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();
  },

  //删除
  delGoods(e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除该商品吗',
      success(res) {
        if (res.confirm) {
          const index = e.currentTarget.dataset.index;
          const cartIds = e.currentTarget.dataset.cartid;
          let carts = that.data.carts;
          carts.splice(index, 1);
          that.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();
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 全选
  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])
        }
      }
      let list = this.data.carts;
      list.forEach((item, index) => {
        if (item.selected == true) {
          console.log(item, "item")
          list.splice(index, 1)
          console.log(list, 'list')
        }
        this.setData({
          carts: list
        })
      })
      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: [],
      checkNum: 0
    });
    this.getTotalPrice();
    this.getAddress() //获取默认地址
    this.getDayTime() //获取当太日期
    this.setData({ //每次购物车下单重新选择商品
      pitchCart: [],
      pitchList: []
    })

    setTimeout(() => {   //判断购物车是否有商品
      if (this.data.carts.length == 0) {
        this.setData({
          cartnoData: true
        })
      }
    }, 500)

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})