const api = require('../config/api')
const util = require('./util')

/*
** Promise封装auth.code2Session
*/
function getSessionKey() {
  return new Promise((resolve, reject) => {
		wx.login({
			success: res => util.request(api.GetSessionKey, res.code, 'POST').then(res => resolve(res)).catch(() => reject()),
      fail: () => reject()
		})
  })
}

/*
** 调用手机号登录
*/
function loginByPhone(data) {
  return new Promise((resolve, reject) => {
		util.request(api.LoginByWeixin, data).then(res => {
			if (res.errno === 0) {
				wx.setStorageSync('userInfo', res.data.userInfo)
				wx.setStorageSync('token', res.data.token)
				resolve(res)
			} else reject('网络波动请重试')
		}).catch(() => reject('网络连接失败'))
  })
}

module.exports = { getSessionKey, loginByPhone }