// pages/cart/cart.js
const wxService = require('../../utils/wxService')

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    product: {
      quantity: 1
    },
    isAllSelect: false,
    currentHeight: 52,
    startX: '',
    delBtnWidth: 66,//删除按钮宽度单位（rpx）
    cartList: [],
    outGoods: [],
    checkAll: false,
    checkedColor: 'rgb(203, 60, 60)'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wxService.getSystemInfo().then(res => {
      const { statusBarHeight } = res
      const { currentHeight, currentMarginTop, currentPaddingTop } = this.data
      this.setData({
        currentHeight: currentHeight + statusBarHeight,
      })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    this.init()
  },
  init() {
    wx.showLoading({
      title: '加载中'
    })
    // 1556108807316001
    // 1556108807316000
    const trolleySku = {
      count: 1,
      skuId: '1556108807316001'
    }
    // 加入购物车
    wxService.post('/sale/trolley/put', trolleySku).then(res => {
      if (res) {
        const { result } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.getCartList()
        }
      }
    })
  },
  // 查询  /trolley/query
  getCartList() {
    wx.showLoading({
      title: '加载中'
    })
    wxService.get('/sale/trolley/query').then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          // item.checked
          data.skuVOList.forEach(item=>{
            item.checked = false
          })
          this.setData({
            cartList: data.skuVOList
          })
        }
      }
    })
  },
  minusNum: function (e) { // 减少数量
    let cartList = this.data.cartList
    // let proNum = cartList[e.currentTarget.dataset.index].quantity
    console.log('sssse', e.currentTarget.dataset)
    // if (proNum > 1) {
    //   proNum--
    // } else {
    //   wx.showToast({
    //     title: '数量不能为0',
    //     icon: 'none'
    //   })
    //   return false
    // }
    // cartList[e.currentTarget.dataset.index].quantity = proNum
    // this.setData({
    //   cartList: cartList
    // }, function () {
    //   this.setTotalFee()
    //   this.editOk(cartList[e.currentTarget.dataset.index]) //调用完成
    // })

  },
  addNum: function (e) { // 增加数量
    var cartList = this.data.cartList
    console.log('add', e.currentTarget.dataset)
    var choosePro = cartList[e.currentTarget.dataset.index]
    console.log(choosePro)
    var proNum = choosePro.quantity
    if (choosePro.quantityAverage == '0') {
      if (proNum < choosePro.selectSku.inventory_num) {
        proNum++
      } else {
        wx.showToast({
          title: '不能超过库存',
          icon: 'none'
        })
      }
    } else {
      if (proNum < choosePro.quantityAverage) {
        proNum++
      } else {
        wx.showToast({
          title: '每人限购' + choosePro.quantityAverage + '件',
          icon: 'none'
        })
      }
    }
    cartList[e.currentTarget.dataset.index].quantity = proNum
    this.setData({
      cartList: cartList
    }, function () {
      this.setTotalFee()
      this.editOk(cartList[e.currentTarget.dataset.index]) //调用完成
    })

  },
  blurNum: function (e) {
    var newNum = e.detail.value
    console.log('blurNum', newNum)
    var cartList = this.data.cartList
    if (newNum === '') {
      newNum = 1
    }
    // cartList[e.currentTarget.dataset.index].quantity = newNum
    // this.setData({
    //   cartList: cartList
    // }, function () {
    //   this.setTotalFee()
    //   this.editOk(cartList[e.currentTarget.dataset.index]) //调用完成
    // })

  },
  inputNum: function (e) { // 输入数量
    var newNum = e.detail.value
    console.log('newNum', newNum)
    if (newNum) {
      const { cartList } = this.data
      if (newNum === '0') {
        newNum = 1
      } else {
        newNum = parseInt(newNum)
      }
    }
    // if(newNum) {
    //   var cartList = this.data.cartList

    //   var choosePro = cartList[e.currentTarget.dataset.index]
    //   if (newNum === '0') {
    //     newNum = 1
    //   } else {
    //     newNum = parseInt(newNum)
    //     if (choosePro.quantityAverage == '0') {
    //       if (newNum > choosePro.selectSku.inventory_num) {
    //         newNum = choosePro.selectSku.inventory_num
    //         wx.showToast({
    //           title: '不能超过库存',
    //           icon: 'none'
    //         })
    //       }
    //     } else {
    //       if (newNum > choosePro.quantityAverage) {
    //         newNum = choosePro.quantityAverage
    //         wx.showToast({
    //           title: '每人限购' + choosePro.quantityAverage + '件',
    //           icon: 'none'
    //         })
    //       }
    //     }
    //   }
    //   cartList[e.currentTarget.dataset.index].quantity = newNum
    //   this.setData({
    //     cartList: cartList
    //   }, function () {
    //     this.setTotalFee()
    //     this.editOk(cartList[e.currentTarget.dataset.index]) //调用完成
    //   })
    // }

  },
  goBuy() {
    let goodsIds = []
    let specIds = []
    let quantitys = []
    let redemptionSpecIds = []
    let cartListData = this.data.cartList || []

    if (!cartListData) return false
    cartListData.filter(item => { // 选中的商品信息
      return item.checked
    }).map(function (item) {
      goodsIds.push(item.skuId)
      quantitys.push(item.count)
    })
    if (goodsIds.length == 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      })
      return false
    }
    // 去下单页
    this.handleGoBuy()
  },
  handleGoBuy() {
    // 下单
    wx.showLoading({
      title: '加载中'
    })
    // wxService.post(`/sale/trade/buyer/create`).then(res => {
    //   if (!res) return false;
    //   const { result, data } = res && res.data || res && res.result
    //   if (result == 0) {
    //     delete data.appId
    //     wx.requestPayment(Object.assign({
    //       success(res) {
    //         wx.hideLoading()
    //         wx.showToast({
    //           title: '支付成功',
    //           icon: 'none',
    //           mask: true
    //         })
    //       },
    //       fail(res) {
    //         wx.hideLoading()
    //         wx.showToast({
    //           title: '支付失败',
    //           icon: 'none',
    //           mask: true
    //         })
    //       }
    //     }, data))
    //   }
    // })
  },
  // 调整商品 /trolley/add
  editOk() {
    wx.showLoading({
      title: '加载中'
    })
    wxService.post('/sale/trolley/add').then(res => {
      console.log('query', res)
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.setData({
            // cartList
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      }
    })
  },
  checkPro: function (e) { // 选中商品
    var cartList = this.data.cartList
    var index = e.currentTarget.dataset.index
    var checkAll = false

      if (cartList[index].checked) {
        cartList[index].checked = false
      } else {
        cartList[index].checked = true
      }
     
      if (cartList.length === cartList.filter(function (item) {
        return item.checked
      }).length ) {
        checkAll = true
      }else {
        checkAll = false
      }

      this.setData({
        cartList: cartList,
        checkAll: checkAll
      }, function () {
        // this.setTotalFee()
      })
  
  },
  checkAll: function () { // 全选
    var cartList = this.data.cartList || []
    if(!cartList.length) return false

    if (this.data.checkAll) {
      this.setData({
        cartList: cartList.map(function (item) {
          item.checked = false
          return item
        }),
        checkAll: false
      }, function () {
        // this.setTotalFee()
      })
    } else {
      this.setData({
        cartList: cartList.map(function (item) {
          // 区分失效商品
            item.checked = true
            return item
        }),
        checkAll: true
      }, function () {
        // this.setTotalFee()
      })
    }
  },

  //删除商品
  deletePro(e) {
    const {index, skuid} = e.currentTarget.dataset
    var self = this
    wx.showModal({
      title: '提示',
      content: '确认删除该商品',
      success(res) {
        if (res.confirm) {
          var cartList = self.data.cartList
          cartList = cartList.filter((item, i) => {
            return i !== index
          })
          self.setData({
            cartList: cartList
          })
         self.editDelOk(skuid) //调用完成 
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  editDelOk(skuId) {
    wx.showLoading({
      title: '加载中'
    })
    wxService.post(`/sale/trolley/remove?skuId=${skuId}`).then(res => {
      if (res) {
        const { result } = res.data
        if (result == 0) {
          wx.hideLoading()
          setTimeout(() => {
            wx.showToast({
              title: '删除成功'
            })
            setTimeout(() => {
              wx.hideToast();
            }, 2000)
          }, 100);
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      }
    })
  },
  // 开始滑动事件
  touchS: function (e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置 
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function (e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置 
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值 
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) { //如果移动距离小于等于0，文本层位置不变 
        txtStyle = "margin-left:0px";
      } else if (disX > 0) { //移动距离大于0，文本层left值等于手指移动距离 
        txtStyle = "margin-left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度 
          txtStyle = "margin-left:-" + delBtnWidth + "px";
        }
      }
      var index = e.currentTarget.dataset.index;
      var cartList = this.data.cartList;
      cartList[index].shows = txtStyle;
      //更新列表的状态 
      this.setData({
        cartList: cartList
      });

    }
  },
  // 滑动中事件
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置 
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离 
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮 
      var txtStyle = "";
      txtStyle = disX > delBtnWidth / 2 ? "margin-left:-" + delBtnWidth + "px" : "margin-left:0px";
      //获取手指触摸的是哪一项 
      var index = e.currentTarget.dataset.index;
      var cartList = this.data.cartList;
      cartList[index].shows = txtStyle;
      //更新列表的状态 
      this.setData({
        cartList: cartList
      });
    } else {
    }
  },
})