// 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: {},
    phone: '',
    formPhone: '',
    name: '',
    address: '',
    wx_number: '',
    sessionId: '',
    visible: false,
    errMsg: false,
    errMessage: '',
    platform: 'pc'
  },

  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.getPlatform()
    this.getUserInfo()
    this.getVipPrice()

    // 获取session id
    let that = this
    this.getSessionKey(function(sid) {
      that.setData({
        sessionId: sid
      })
    })
  },

  getPlatform: function() {
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        if (res.platform == "devtools") {
          that.setData({
            platform: 'pc',
          })
        } else if (res.platform == "ios") {
          that.setData({
            platform: 'ios',
          })
        } else if (res.platform == "android") {
          that.setData({
            platform: 'android',
          })
        }
      }
    })
  },

  makeClipboard: function (e){
    console.log(122222)
    wx.setClipboardData({
      data: '13120365050',
      success: function (res) {
        wx.showToast({
          title: '复制成功',
        })
      }
    })
    console.log(2111111)
  },

  // 获取个人资料
  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) {
    // 获取session key
    let encryptedData = event.detail.encryptedData
    let iv = event.detail.iv
    let that = this
    // 检查session key是否过期，如果过期的话，那么就获取新的再请求，否则直接请求
    wx.checkSession({
      success: function(res) {
        //session_key未过期，直接操作
        let sessionId = that.data.sessionId
        api.getPhoneNumber({
          sessionId: sessionId,
          encryptedData: encryptedData,
          iv: encodeURIComponent(iv)
        }).then(res => {
          if (!res.code) {
            that.setData({
              visible1: false
            })
            if (res.is_relation) {
              that.setData({
                visible2: true
              })
            }
            //更新下用户数据
            that.getUserInfo()
          } else {
            $Toast({
              content: res.msg,
              type: 'error'
            });
          }
        })
      },
      fail: function() {
        // session_key 已过期，进行登录操作，提示错误
        // 获取session id
        console.log('checkSession fail!')
        let that = this
        this.getSessionKey(function(sid) {
          that.setData({
            sessionId: sid
          })
          // 授权手机号
          api.getPhoneNumber({
            sessionId: sid,
            encryptedData: encryptedData,
            iv: encodeURIComponent(iv)
          }).then(res => {
            if (!res.code) {
              that.setData({
                visible1: false
              })
              if (res.is_relation) {
                that.setData({
                  visible2: true
                })
              }
              //更新下用户数据
              that.getUserInfo()
            } else {
              $Toast({
                content: res.msg,
                type: 'error'
              });
            }
          })
        })
      }
    })
  },

  /**
   * 获取服务器端 session key
   */
  getSessionKey(callback) {
    Wx.login().then(res => {
      if (res.errMsg == 'login:ok') {
        api.getSessionKey({
          code: res.code
        }).then(res => {
          if (res.code == 0) {
            typeof callback == "function" && callback(res.data)
          } else {
            $Toast({
              content: res.msg,
              type: 'error'
            });
          }
        })
      } else {
        $Toast({
          content: 'wx.login失败',
          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)
    })
  },

  /**
   * 保存手机号
   */
  savePhone() {
    //发送请求保存手机号
    const phone = this.data.formPhone
    api.getPhoneNumber({
      phone: phone
    }).then(res => {
      if (!res.code) {
        // 将刚拿到的手机号码放到全局数据中，否则phone数据只会是当前页面数据
        if (app.globalData.userInfo) {
          app.globalData.userInfo.phone = res.data.phone
        }
        this.setData({
          phone: res.data.phone,
          visible: false
        })
        if (res.is_relation) {
          $Toast({
            content: '温馨提示:手机号授权成功,系统已自动关联您在其他平台购买的美行者VIP会员',
            type: 'success'
          });

        } else {
          $Toast({
            content: '手机号授权成功',
            type: 'success'
          });
        }
        //在拉去一遍用户信息
        this.getUserInfo();
      } else {
        this.setData({
          'errMsg': true,
          'errMessage': '*' + res.msg
        })

      }
    })

  },

  /**
   * 关闭手机号填写弹窗
   */
  alertClose() {
    this.setData({
      visible: false
    });
  },

  /**
   * 打开手机号填写弹窗
   */
  openAlert() {
    this.setData({
      visible: true
    })
  },

  handlePhone: function(event) {
    this.setData({
      formPhone: event.detail.detail.value
    })
  },

})