const { miniLogin } = require('./api/index')
const { login, sessionStorageKey } = require('../../api/request')
const { envDomain } = require('../../utils/config')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked: false,
    booLock: false
  },
  wxCode: '',

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

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

  },

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

  },

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

  },

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

  },
  async getWxCode() {
    try {
      this.wxCode = await login()
    } catch (e) {}
  },
  bindTip() {
    wx.showToast({
      title: '请阅读并勾选协议',
      icon: 'none'
    })
  },
  // 获取token
  async getPhoneNumber(e) {
    const { errMsg, encryptedData, iv } = e.detail
    if (errMsg === 'getPhoneNumber:ok') {
      this.setData({
        booLock: true
      })

      try {
        const { status, data } = await miniLogin({ wxCode: this.wxCode, encryptedData, iv })
        if (status) {
          try {
            wx.setStorageSync(sessionStorageKey, data.token)
          } catch (err) {}

          await app.fetchUserData()

          const pages = getCurrentPages()
          if (pages.length > 1) {
            const route = pages[pages.length - 2]
            wx.navigateBack({
              delta: 1
            })
            route.bindCallBack && route.bindCallBack()
          }
        } else {
          wx.showToast({
            title: '登录出错了，请重试',
            icon: 'none'
          })
          this.getWxCode()
        }
      } catch (e) {
        this.getWxCode()
      }

      this.setData({
        booLock: false
      })
    }
  },
  jumpBind() {
    wx.navigateTo({
      url: '/pages/bind/bind'
    })
  },
  // 去包个大巴服务协议
  jumpAgreement() {
    wx.navigateTo({
      url: '/pages/h5/h5?url=' + envDomain.h5Domain + '/agreement'
    })
  },
  // 去隐私政策
  jumpPrivacy() {
    wx.navigateTo({
      url: '/pages/h5/h5?url=' + envDomain.h5Domain + '/privacy'
    })
  },
  bindChange() {
    this.setData({
      checked: !(this.data.checked)
    })
  }
})
