// pages/me/vip/index.js
import api from '../../../utils/Api.js'
import Wx from '../../../utils/Wx.js'
const app = getApp()
const {
  $Toast
} = require('../../../iview/base/index');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    value1: 1,
    value2: 0.1,
    visible2: false,
    vip_price: 49.9,

    order: {},
    user: {},
    name: '',
    address: '',
    wx_number: '',

  },

  handleChange1({
    detail
  }) {
    this.setData({
      value1: detail.value
    })
  },

  handleChange2({
    detail
  }) {
    this.setData({
      value2: detail.value
    })
  },

  handleName: function(e) {
    this.setData({
      name: e.detail.detail.value
    })
  },

  handleWx: function(e) {
    this.setData({
      wx_number: e.detail.detail.value
    })
  },

  handleAddress: function(e) {
    this.setData({
      address: e.detail.detail.value
    })
  },

  modelCancel: function() {
    console.log(this.data.visible2);
    this.setData({
      visible2: false
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getUserInfo()
    this.getVipPrice()
  },

  // 获取个人资料
  getUserInfo: function() {
    api.me.info().then(res => {
      if (!res.code) {
        console.log(res.data);
        app.globalData.userInfo = res.data
        // 渲染数据
        this.setData({
          user: res.data,
          name: res.data.name,
          wx_number: res.data.wx_number,
          address: res.data.address,
        })
      }
    })
  },

  handlePhoneAuth: function(event) {
    Wx.login().then(res => {
      let encryptedData = event.detail.encryptedData
      let iv = event.detail.iv
      this.decodePhoneData(res.code, encryptedData, iv)
    })
  },

  /**
   * 解密手机号数据
   */
  decodePhoneData: function(code, encryptedData, iv) {
    let that = this
    api.getPhoneNumber({
      code: code,
      encryptedData: encryptedData,
      iv: iv
    }).then(res => {
      if (!res.code) {
        that.setData({
          visible1: false
        })
        if (res.is_relation){
          that.setData({
            visible2: true
          })
        }
        //更新下用户数据
        that.getUserInfo()
      } else {
        $Toast({
          content: '手机号授权失败',
          type: 'error'
        });
      }
    })
  },



  // 获取VIP单价
  getVipPrice: function() {
    api.me.vipPrice().then(res => {
      if (!res.code) {
        this.setData({
          vip_price: res.price
        })
      } else {
        wx.showToast({
          title: res.msg
        })
      }
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 立即购买/续费
   */
  handleClick: function() {
    let that = this
    let year = this.data.value1
    let wx_number = this.data.wx_number
    let name = this.data.name
    let address = this.data.address
    let params = {
      year: year,
      wx_number: wx_number,
      name: name,
      address: address
    }
  
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: '加载中...',
    })
    // 获取支付参数
    api.me.vipOrder(params).then(res => {
      wx.hideNavigationBarLoading()
      wx.hideLoading()
      if (res.code == 0) {
        that.setData({
          order: res.data
        })
        // 发起微信支付
        wx.requestPayment({
          timeStamp: '' + res.result.timeStamp,
          nonceStr: '' + res.result.nonceStr,
          package: '' + res.result.package,
          signType: '' + res.result.signType,
          paySign: '' + res.result.paySign,
          success: function(ret) {
            console.log(ret)
            if (ret.errMsg === 'requestPayment:ok') {
              that.setOrderPaid(that.data.order.order_id, function(res) {
                // 支付同步回调结果
                console.log("发送模版消息", res)
                // 刷新当前页面
                setTimeout(() => {
                  that.getUserInfo()
                }, 500)
              })
            } else {
              wx.showToast({
                title: ret.errMsg,
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },

  /**
   * 同步支付结果回调：重置订单状态
   */
  setOrderPaid(id, callback) {
    let params = {
      order_id: id
    }
    api.me.vipOrderSendTemplate(params).then(res => {
      typeof callback == "function" && callback(res)
    })
  }
})