import {
  imgServerUrl
} from '../../config/config.js'
import {
  decodePhone
} from '../../services/wx.js'
import {
  updataStorageData
} from '../../utils/storage.js'
var app = getApp()

Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getPhoneNumber'),
    imgServerUrl: imgServerUrl,
    isShow: true
  },
  onLoad: function(options) {
    app.globalData.noPhone = true
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1]; //当前页面
    var prevPage = pages[pages.length - 2]; //上一个页面

    prevPage.setData({
      noPhone: false
    })
  },
  privacyCancel(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  getPhoneNumber: function(e) {
    let iv = e.detail.iv || ''
    let encryptedData = e.detail.encryptedData || ''
    if (iv) {
      //用户按了允许授权按钮
      this.decodePhoneCallback({
        iv: iv,
        encryptedData: encryptedData,
      }).then(data => {
        app.globalData.noPhone = false
        updataStorageData('phone', data.data.hpUser.phone);
        wx.navigateBack()
      })
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '未经授权会导致系统部分功能无法使用。',
        confirmText: '返回授权',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  },
  // 手机号解密回调 返回成功失败
  decodePhoneCallback(params) {
    return new Promise((resolve, reject) => {
      decodePhone({
        'encryptedData': encodeURIComponent(params.encryptedData),
        'iv': encodeURIComponent(params.iv),
        'user_id': app.globalData.userId,
        'user_token': app.globalData.userToken
      }).then(data => {
        resolve(data)
      }).catch(data => {
        reject(false)
      })
    })
  }

})