Page({

  /**
   * 页面的初始数据
   */
  data: {
    booShow: false,
    actions: [
      {
        name: '呼叫',
        value: 'makePhoneCall'
      },
      {
        name: '复制号码',
        value: 'setClipboardData'
      },
      {
        name: '添加到手机通讯录',
        value: 'addPhoneContact'
      }
    ],
    businessInfo: {
      phone: '13429176706'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },
  showActionSheet() {
    this.setData({ booShow: true })
  },
  hideActionSheet() {
    this.setData({ booShow: false })
  },
  async onSelect(event) {
    const { value } = event.detail
    const { businessInfo } = this.data
    this.hideActionSheet()
    switch (value) {
      case 'makePhoneCall':
        try {
          await wx.makePhoneCall({ phoneNumber: businessInfo.phone })
        } catch (err) {}
        break
      case 'setClipboardData':
        try {
          await wx.setClipboardData({ data: businessInfo.phone })
        } catch (err) {}
        break
      case 'addPhoneContact':
        this.handleGetSetting()
        break
      default:
    }
  },
  // 获取添加手机通讯录联系人权限
  async handleGetSetting() {
    const that = this

    try {
      const { errMsg, authSetting } = await wx.getSetting()
      if (errMsg === 'getSetting:ok') {
        if (authSetting['scope.addPhoneContact']) {
          await that.addPhoneContactBridge()
          return
        }
      }
    } catch (err) {}

    try {
      await wx.authorize({ scope: 'scope.addPhoneContact' })
      await that.addPhoneContactBridge()
    } catch (err) {
      wx.showModal({
        title: '提示',
        content: '未开启添加手机通讯录联系人权限,去设置中打开',
        success(res) {
          if (res.confirm) {
            that.openSetting()
          }
        }
      })
    }
  },
  // 去小程序自带设置页:返回
  async openSetting() {
    try {
      const openSettingData = await wx.openSetting()
      if (openSettingData.authSetting['scope.addPhoneContact']) {
        await this.addPhoneContactBridge()
      }
    } catch (err) {}
  },
  async addPhoneContactBridge() {
    const { businessInfo } = this.data

    try {
      await wx.addPhoneContact({
        firstName: 'businessInfo.phone',
        mobilePhoneNumber: businessInfo.phone
      })
    } catch (err) {}
  },
  async openLocationBridge() {
    try {
      // 测试 latitude: 30.25727 longitude: 120.20523
      await wx.openLocation({
        latitude: 30.25727,
        longitude: 120.20523,
        name: '浙江省杭州市余杭区'
      })
    } catch (err) {}
  }
})