const app = getApp()
import request from '../../utils/request'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    firstData: null,// 首充数据
    orderList: [],
    imgUrl: 'https://formall.oss-accelerate.aliyuncs.com/ga/payOrder-1.png',
    currentIndex: null,
    currentId: '',
    isShowNumberCheck: false,
    phone: '',
    noticeText: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (app.globalData.noticeText) {
      this.setData({
        noticeText: app.globalData.noticeText
      })
    }
    this.setData({
      userInfo: JSON.parse(options.userInfo)
    })
    // **已弃用
    // this.getProductDetail()
    this.getProductList()
    this.checkUserInfo()
  },

  // 获取产品详情（价格、库存等）**已弃用
  // getProductDetail() {
  //   const that = this
  //   request.get({
  //     url: '/api/product/detail',
  //   }).then(res => {
  //     console.log(res, 'getProductDetail');
  //     that.setData({
  //       salePrice: res.data.salePrice,
  //       price: res.data.price,
  //       days: res.data.days,
  //     })
  //   }).catch(err => {
  //     console.log(err, 'err');
  //   })
  // },

  // 跳转至联系我们页面
  goToProductDetail() {
    wx.navigateTo({
      url: '/pages/ContactUs/ContactUs',
    })
  },

  getProductList() {
    const that = this
    request.get({
      url: '/api/product/list',
    }).then(res => {
      console.log(res, 'getProductList');
      const firstData = res.data.filter(item => item.first == 1)
      // 首充数据
      if (firstData.length) {
        const data = {
          days: firstData[0].days,
          price: firstData[0].price,
          salePrice: firstData[0].salePrice,
        }
        this.setData({
          firstData: data,
          currentId: firstData[0].id
        })
        // 非首冲数据
      } else {
        this.setData({
          orderList: res.data
        })
      }

    }).catch(err => {
      console.log(err, 'err');
    })
  },

  selectItem(e) {
    const index = e.currentTarget.dataset.index
    const id = e.currentTarget.dataset.id
    const currentIndex = this.data.currentIndex
    this.setData({
      currentIndex: index == currentIndex ? null : index,
      currentId: index == currentIndex ? '' : id
    })
  },

  createPayOrder() {
    if (!this.data.phone) {
      this.setData({
        isShowNumberCheck: true
      })
      return
    }

    if (!this.data.currentId) {
      wx.showToast({
        title: '请选择一个套餐！',
        icon: 'error'
      })
    }

    const data = {
      appId: request.appId,
      productId: this.data.currentId
    }
    request.post({
      url: '/api/pay/createPayOrder',
      data
    }).then(res => {
      console.log(res, 'createPayOrder');
      this.requestPayment(res.data.data)
    }).catch(err => {
      console.log(err, 'err');
    })
  },

  requestPayment(data) {
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType ? data.signType : "MD5",
      paySign: data.paySign,
      success: res => {
        wx.showLoading({
          title: '订单正在处理中...',
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/index/index?checkUserInfo="go"'
          })
        }, 2000);
      },
      fail: res => {
        wx.hideLoading();
        wx.showToast({
          title: '支付失败',
          icon: 'error'
        })
        /**
         * 支付失败，需要更新订单的状态
         */
      },
      complete: res => { }
    });
  },

  /**
  * @description 检查用户信息
  * @returns userInfo
  */
  checkUserInfo() {
    const that = this
    request.get({
      url: '/api/user/userinfo'
    }).then(res => {
      console.log(res, 'userinfo');
      that.setData({
        phone: res.data.phone || null
      })
    }).catch(err => {
      console.log(err, 'err');
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})