// subPackagesE/pages/giftBagOrder/giftBagOrder.js
import {
  get,
  post
} from '../../../utils/http'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    store_id: '', //店铺ID
    storeInfo: '', //店铺信息
    giftInfo: "", //礼盒信息
    goodsDetailsList: '', //美妆产品详情
    showMoneyGood: '', //商品价格
    payNow: false, //控制提交订单弹出框
    inserllAmount: '', // 我的储值
    pay_methon: 1, //支付方式 1微信2储值
    orderId: '', //订单ID
    exchangeCondition: '', //加购规则
    exchangeList: [], //加购产品列表
    exchangeSum: 0, //加购总次数
    exchangeSelect: false, //是否选中加购产品
    toExchangePrice: '', //选中加购产品的总价格
    exchangePop: true, //加购弹窗
    exchangeCountDown: 5, //加购弹窗倒计时
    timer: null, //倒计时器
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 弹窗倒计时
    this.countDown()
    // 计算产品总数量
    let sum = 0
    if (options.productList) {
      let list = JSON.parse(options.productList)
      list.forEach(item => {
        sum = item.num + sum
      })
    }
    this.setData({
      store_id: options.store_id || wx.getStorageSync('store_id'), //店铺名称
      goodsDetailsList: JSON.parse(options.productList), //产品信息
      giftID: options.giftID, //礼盒ID
      total: sum
    })
    console.log(JSON.parse(options.productList));
    // 获取店铺信息
    this.getStoreInfo()
    // 获取礼盒信息
    this.getGiftBagDetail()
  },
  // 加购弹窗倒计时

  countDown: function () {
    let that = this;
    let exchangeCountDown = that.data.exchangeCountDown; //获取倒计时初始值
    that.setData({
      timer: setInterval(function () {
        exchangeCountDown--;
        that.setData({
          exchangeCountDown: exchangeCountDown
        })
        if (exchangeCountDown == 0) {
          clearInterval(that.data.timer);
          that.setData({
            exchangePop: false
          })
        }
      }, 1000)
    })
  },
  // 关闭弹窗
  onCloseLandscape() {
    clearInterval(this.data.timer);
    this.setData({
      exchangePop: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },
  // 提交订单
  onNewPay() {
    // 判断加购产品是否选择完成
    if (this.data.exchangeSelect) {
      if (this.data.exchangeSum < this.data.exchangeCondition.time) {
        wx.showToast({
          title: '您还有剩余次数未选',
          icon: 'none'
        })
        return
      }
    }
    // 筛选礼包信息
    let item_data = []
    this.data.goodsDetailsList.forEach(item => {
      let list = {}
      list.item_id = item.item_id
      list.goods_id = item.goods_id
      list.num = item.num
      item_data.push(list)
    })
    // 筛选添加换购产品
    let plus = []
    this.data.exchangeList.list.forEach(item => {
      if (item.num != 0) {
        plus.push(item.id)
      }
    })
    let params = {
      store_id: this.data.store_id || wx.getStorageSync('store_id'),
      id: this.data.giftID, //礼盒ID
      item_data: JSON.stringify(item_data), //配置数据，json字符串，格式如[{item_id:"",goods_id:"",num:""}]，item_id配置ID，goods_id商品ID，num商品对应数量
      plus_ids: plus.toString()
    }
    post('v2/api/package/add', params, res => {
      if (res.code == 200) {
        if (res.data.pay_status == 1) {
          wx.showToast({
            title: '支付成功',
            icon: 'success'
          })
          // 只有项目购买，需要订阅消息
          wx.reLaunch({
            url: `/pages/paySuccess/paySuccess?current=1&source=goods&order_id=${res.data.order_id}`
          })
        } else {
          this.setData({
            payNow: true,
            orderId: res.data.order_id
          })
          this.getAmount()
        }
      }
    })
  },
  /**
   * 订单支付
   */
  payOrder() {
    let that = this
    post(
      'v2/api/order/goods/pay', {
        pay_way: this.data.pay_methon == 1 ? 'weixin' : 'amount',
        order_id: this.data.orderId
      },
      (res) => {
        that.setData({
          payNow: false
        })
        if (that.data.pay_methon == 2) {
          that.goToOrder('支付成功')
          return
        }
        wx.requestPayment({
          timeStamp: res.data.pay_data.timeStamp,
          nonceStr: res.data.pay_data.nonceStr,
          package: res.data.pay_data.package,
          signType: res.data.pay_data.signType,
          paySign: res.data.pay_data.paySign,
          success(res) {
            if (res.errMsg == 'requestPayment:ok') {
              that.goToOrder('支付成功')
            }
          },
          fail(res) {
            that.goToOrder('支付失败')
          }
        })
      }
    )
  },
  /**
   * 跳转订单列表
   */
  goToOrder(text) {
    let that = this
    wx.showToast({
      title: text,
      icon: text == '支付成功' ? 'success' : 'error'
    })
    if (text == '支付成功') {
      // 只有项目购买，需要订阅消息
      wx.reLaunch({
        url: `/pages/paySuccess/paySuccess?current=1&source=goods&order_id=${that.data.orderId}`
      })
      // 获取下发权限
      wx.requestSubscribeMessage({
        tmplIds: ['RNife3ZhTYYpUuT26ylGQj8W0v07IPo2TGe941iR3y8'],
        success(res) {
          let status = ''
          if (res['RNife3ZhTYYpUuT26ylGQj8W0v07IPo2TGe941iR3y8'] == 'reject') {
            status = 2
          } else {
            status = 1
          }
          get('/v2/api/activity/push', {
            type: 2,
            status,
          }, res => {})
        },
      })
      return
    } else {
      let failUrl = `/pages/goods/orderList/orderList?current=0`
      setTimeout(() => {
        wx.reLaunch({
          url: failUrl
        })
      }, 1000)
    }
  },
  // 关闭提交订单框
  onClosePay() {
    this.setData({
      payNow: false
    })
  },
  // 选择微信支付
  pay_methonw() {
    this.setData({
      pay_methon: 1
    })
  },
  // 选择储值支付
  pay_methonc() {
    this.setData({
      pay_methon: 2
    })
  },
  /**
   * 获取我的储值
   * api/user
   */
  getAmount() {
    get('api/user/amount', {}, (res) => {
      if (res.data) {
        this.setData({
          inserllAmount: res.data.amount
        })
      }
    })
  },
  // 获取店铺信息
  getStoreInfo() {
    get('api/store/info', {
      store_id: this.data.store_id
    }, (res => {
      this.setData({
        storeInfo: res.data
      })
    }))
  },
  // 获取礼包详情
  getGiftBagDetail() {
    get('v2/api/package/info', {
      id: this.data.giftID
    }, (res => {
      this.setData({
        giftInfo: res.data,
        showMoneyGood: res.data.price
      })
      // 获取加购列表
      this.getNewPlus()
    }))
  },
  //获取新加购列表
  getNewPlus() {
    post('v2/api/car/plus', {}, (res => {
      if (res.code == 200) {
        let flag = true
        res.data.time = res.data.time.reverse()
        res.data.time.forEach(item => {
          if (Number(this.data.showMoneyGood) >= item.price && flag) {
            flag = false
            this.setData({
              exchangeCondition: item
            })
          }
        })
        res.data.list.forEach(item => {
          item.num = 0
        })
        this.setData({
          exchangeList: res.data,
        })
      }
    }))
  },
  // 加购加产品
  add(e) {
    let index = e.currentTarget.dataset.index
    // 如果加购产品数量大于总次数就返回
    if (this.data.exchangeSum + 1 > this.data.exchangeCondition.time) {
      return
    }
    let exchangeList = `exchangeList.list[${index}].num`
    this.setData({
      [exchangeList]: this.data.exchangeList.list[index].num + 1
    })
    // 遍历计算出总共加购多少次
    let sum = 0
    this.data.exchangeList.list.forEach(item => {
      sum = item.num + sum
    })
    this.setData({
      exchangeSum: sum
    })
    // 判断是否选中加购产品
    if (sum >= 1) {
      this.setData({
        exchangeSelect: true,
        toExchangePrice: 99,
        toExchangePrice: (Number(this.data.showMoneyGood) + 99).toFixed(2)
      })
    }
  },
  // 加购减产品
  reduce(e) {
    let index = e.currentTarget.dataset.index
    if (this.data.exchangeList.list[index].num == 0) {
      return
    }
    let exchangeList = `exchangeList.list[${index}].num`
    this.setData({
      [exchangeList]: this.data.exchangeList.list[index].num - 1
    })
    // 遍历计算出总共加购多少次
    let sum = 0
    this.data.exchangeList.list.forEach(item => {
      sum = item.num + sum
    })
    this.setData({
      exchangeSum: sum
    })
    // 判断是否选中加购产品
    if (sum < 1) {
      this.setData({
        exchangeSelect: false,
        toExchangePrice: 0,
      })
    }
  },
})