// 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)',
    shopCartTotalFee: 0, // 商品总价
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('cart', this.data.currentHasUserInfo)
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    this.init()
  },

  init() {
    wx.showLoading({
      title: '加载中'
    })
    // 1556108807316001
    // 1556108807316000
    this.getCartList()

    // const trolleySku = {
    //   count: 1,
    //   skuId: '1556108807316000'
    // }
    // // 加入购物车
    // 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
          })
        }
      }
    })
  },
  minusNumChange(e) {
    this.minusNum(e.detail)
  },
  minusNum: function (e) { // 减少数量
    let cartList = this.data.cartList
    // let proNum = cartList[e.currentTarget.dataset.index].count
    let proNum = cartList[e].count
    console.log('减少数量', proNum)
    if (proNum > 1) {
      proNum--
    } else {
      wx.showToast({
        title: '数量不能为0',
        icon: 'none'
      })
      return false
    }
    // cartList[e.currentTarget.dataset.index].count = proNum
    cartList[e].count = proNum
    this.setData({
      cartList: cartList
    }, function () {
      this.setTotalFee()
      this.editOk(cartList[e]) //调用完成
    })
  },
  addNumChange(e) {
    this.addNum(e.detail)
  },
  addNum (e) { // 增加数量
    var cartList = this.data.cartList
    // var proNum = cartList[e.currentTarget.dataset.index].count
    var proNum = cartList[e].count
    console.log('增加数量',proNum)
    // 判断库存
    if (proNum < 100) {
      proNum++
    } else {
      wx.showToast({
        title: '不能超过库存',
        icon: 'none'
      })
      return false
    }

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

    this.setData({
      cartList: cartList
    }, function () {
      this.setTotalFee()
      this.inputProNumber(cartList[e.index]) //调用完成
    })

  },
  inputNumChange(e) {
    this.inputNum(e.detail)
  },
  inputNum: function (e) { // 输入数量
    // var newNum = e.detail.value
    var newNum = e.value
    if (newNum) {
      const { cartList } = this.data
      if (newNum === '0') {
        newNum = 1
      } else {
        newNum = parseInt(newNum)
      }
      cartList[e.index].count = newNum
      this.setData({
        cartList: cartList
      }, function () {
        this.setTotalFee()
        this.inputProNumber(cartList[e.index]) //调用完成
      })
    }
  },
  setTotalFee(skipRedemption) {
    var cartList = this.data.cartList
    var checkProsId = [] // 选中的商品id
    console.log(cartList)
    
    var totalFee = 0
    // 购物车总金额
    for (let i = 0; i < cartList.length; i++) {
      if (cartList[i].checked) {
        totalFee += cartList[i].price * (cartList[i].count ? cartList[i].count : 1)
        checkProsId.push(cartList[i].skuId)
      }
    }

    this.setData({
      shopCartTotalFee: totalFee.toFixed(2)
    })

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

    if (!cartListData) return false
    cartListData.filter(item => { // 选中的商品信息
      return item.checked
    }).map(item => {
      if(!item.skuId) return false
      let trolleySku2BuyObj  = {
        count: 0,
        skuId: 0
      }
      trolleySku2BuyObj.count = item.count - 0
      trolleySku2BuyObj.skuId = item.skuId - 0
      // skuIds.push(item.skuId)
      trolleySku2Buy.push(trolleySku2BuyObj)
    })

    if (trolleySku2Buy.length == 0) {
      wx.showToast({
        title: '请选择商品',
        icon: 'none'
      })
      return false
    }
    
    // 去下单页 && 参数
    // let parmas = {
    //   trolleySku2Buy: JSON.stringify(trolleySku2Buy)
    // }

    let tradeDto = {
      trolleySku2Buy:JSON.stringify(trolleySku2Buy)
    }
    const parmas = tradeDto
 
    wxService
      .router('/pages/confirmOrder/confirmOrder')
      .search(parmas)



    // let tradeDto = {
    //   couponId: '',
    //   trolleySku2Buy:JSON.stringify(trolleySku2Buy)
    // }
    // const parmas = tradeDto
 
    // wxService
    //   .router('/pages/confirmOrder/confirmOrder')
    //   .search(parmas)
    // 直接调支付
    // this.handleGoBuy(skuIds)
  },
  handleGoBuy(parmas) {
    // 下单
    wx.showLoading({
      title: '加载中'
    })
    // 获取支付参数
    wxService.post(`/sale/trade/buyer/create`,parmas).then(res => {
      if (!res) return false;
      const { result, data } = res && res.data || res && res.result
      if (result == 0) {
        delete data.appId
        console.log('data', data)
        wx.requestPayment(Object.assign({
          success(res) {
            wx.hideLoading()
            // wx.showToast({
            //   title: '支付成功',
            //   icon: 'none',
            //   mask: true
            // })
            // 支付成功页面
            wxService.router('/subPackage/page/pages/paymentStatus/paymentStatus')
          },
          fail(res) {
            wx.hideLoading()
            wx.showToast({
              title: '支付失败',
              icon: 'none',
              mask: true
            })
          }
        }, data))
      }
    })
  },
  // 调整商品 /trolley/add
  editOk(cartPro) {
    console.log('cartPro', cartPro)
    // count skuId
    wx.showLoading({
      title: '加载中'
    })
    wxService.post(`/sale/trolley/add?count=${cartPro.count}&skuId=${cartPro.skuId}`).then(res => {
      if (res) {
        const { result } = res.data
        if (result == 0) {
          wx.hideLoading()
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      }
    })
  },

  // 输入商品数量
  inputProNumber(cartPro){
    wx.showLoading({
      title: '加载中'
    })
    wxService.post(`/sale/trolley/update?count=${cartPro.count}&skuId=${cartPro.skuId}`).then(res => {
      if (res) {
        const { result } = res.data
        if (result == 0) {
          wx.hideLoading()
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      }
    })
  },
  checkProChange(e) {
    this.checkPro(e.detail)
  },
  checkPro: function (e) { // 选中商品
    var cartList = this.data.cartList
    // var index = e.currentTarget.dataset.index
    var index = e
    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()
      })
    }
  },
  delItemChange(e) {
    this.deletePro(e.detail)
  },
  //删除商品
  deletePro(e) {
    const {index, skuid} = e
    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) //调用完成 
          var totalFee = 0
          // 购物车总金额
          for (let i = 0; i < cartList.length; i++) {
            if (cartList[i].checked) {
              totalFee += cartList[i].price * (cartList[i].count ? cartList[i].count : 1)
            }
          }
          self.setData({
            shopCartTotalFee: totalFee.toFixed(2)
          })
        } 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 {
    }
  },
})