import {getopenId} from "../requests/api";
async function checkSession(){
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success() {
        resolve(true)
      },
      fail() {
        resolve(false)
      }
    })
  })
}
async function authlogin(){
  return new Promise((resolve,reject)=>{
    wx.login({
      success:async function (res) {
        // 进行登录操作
        resolve(res)

      },
      fail:function (err){
        wx.showToast({
          title: '获取code失败',
          icon: 'none'
        })
        reject(err);
      }
    })
  })
}
// 检测登录状态，返回 true / false
async function checkHasLogined() {
  const openId = wx.getStorageSync('openId');
  if (!openId) {
    return false
  }
  const loggined = await checkSession();
  if (!loggined) {
    wx.removeStorageSync('openId')
    return false
  }
  return true
}

function wxaCode(){
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        return resolve(res.code)
      },
      fail() {
        wx.showToast({
          title: '获取code失败',
          icon: 'none'
        })
        return resolve('获取code失败')
      }
    })
  })
}
function getUserInfo() {
  return new Promise((resolve, reject) => {
    wx.getUserInfo({
      success: res => {
         resolve(res)
      },
      fail: err => {
        reject(err)
      }
    })
  })
}
// 检查是否位置授权
function getSetting(){
  return new Promise(function (resolve, reject) {
    wx.getSetting({
      success: (res) => {
        resolve(res)
      },
      fail: function fail(error) {
        wx.showModal({
          title: '网络错误',
          content: '网络出错，请刷新重试',
          showCancel: false
        })
        reject(error);
      },
    })
  })
}
// 获取位置信息
function getLocation(){
  return new Promise(function (resolve, reject) {
    wx.getLocation({
      altitude: 'false',
      type: 'wgs84',
      success: (res) => {
        resolve(res)
      },
      fail: function fail(error) {
        wx.showToast({
          title: '未定位到您所在位置',
          icon: 'none'
        })
        // Toast.fail('未定位到您所在位置');
        // this.setData({
        //   havePower: {
        //     result: "fail",
        //     message: "未定位到您的位置"
        //   }
        // })
        reject(error);
      },
    })
  })
}
module.exports = {
  checkHasLogined: checkHasLogined,
  wxaCode: wxaCode,
  getUserInfo: getUserInfo,
  authlogin: authlogin,
  getSetting,
  getLocation,
}