/**
 * 用户相关服务
 */
import store from '@/store'
import request from '@/common/request'


/**
 * Promise封装wx.checkSession
 */
function checkSession() {
	return new Promise(function(resolve, reject) {
		wx.checkSession({
			success: function() {
				resolve(true);
			},
			fail: function() {
				reject(false);
			}
		})
	});
}

/**
 * Promise封装wx.login
 */
function login() {
	return new Promise(function(resolve, reject) {
		wx.login({
			success: function(res) {
				if (res.code) {
					resolve(res);
				} else {
					reject(res);
				}
			},
			fail: function(err) {
				reject(err);
			}
		});
	});
}
/**
 * 调用微信登录
 */
function loginByWeixinCode() {
	return new Promise(function(resolve, reject) {
		return login().then((res) => {
			var code = res.code;
			//登录远程服务器
			request.post('/api/v1/common/wxLogin', {
				wechat_code: code
			}).then(res => {
				if (res.code == 200) {
					if (res.data.token) {
						store.commit('setJwt', res.data.token);
						store.commit('setUser', res.data);
						store.commit('login');
						resolve(res);
					} else {
						uni.showToast({
							title: '登录失败',
							icon: "none"
						})
						reject(res);
					}
				} else {
					reject(res);
				}
			}).catch((err) => {
				reject(err);
			});
		}).catch((err) => {
			reject(err);
		})
	});
}
/**
 * 调用微信登录
 */
function loginByWeixin(userInfo) {
	return new Promise(function(resolve, reject) {
		return login().then((res) => {
			var code = res.code;
			//登录远程服务器
			request.post('/api/v1/common/wxLogin', {
				// up_id: uni.getStorageSync("up_id"),
				wechat_code: code,
				nickname: userInfo.nickName,
				avatar: userInfo.avatarUrl,
			}).then(res => {
				if (res.status == 0) {
					if (res.data.token) {
						store.commit('setJwt', res.data.token);
						store.commit('setUser', res.data);
						store.commit('login');
						resolve(res);
					} else {
						reject(res);
					}
				} else {
					reject(res);
				}
			}).catch((err) => {
				reject(err);
			});
		}).catch((err) => {
			reject(err);
		})
	});
}

/**
 * 判断用户是否登录
 */
function checkLogin() {
	return new Promise(function(resolve, reject) {
		if (store.getters['verifyJwt']) {
			checkSession().then(() => {
				resolve(true);
			}).catch(() => {
				reject(false);
			});
		} else {
			reject(false);
		}
	});
}




module.exports = {
	loginByWeixin,
	loginByWeixinCode,
	checkLogin,
};
