import {
	request
} from './request.js'
import {
	baseUrl
} from "./apiconfig";
import {
	setToken
} from './auth';

export const isLogin = () => {
	// {
	// 	avatar: "ace4115743d581b60b34f9a93455e51c.jpeg"
	// 	avatar2: "http://tmp00002.learv.com/ace4115743d581b60b34f9a93455e51c.jpeg"
	// 	nickname: "默认用户"
	// 	token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuaWNrbmFtZSI6Ium7mOiupOeUqOaItyIsImF2YXRhciI6ImFjZTQxMTU3NDNkNTgxYjYwYjM0ZjlhOTM0NTVlNTFjLmpwZWciLCJhdmF0YXIyIjoiaHR0cDovL3RtcDAwMDAyLmxlYXJ2LmNvbS9hY2U0MTE1NzQzZDU4MWI2MGIzNGY5YTkzNDU1ZTUxYy5qcGVnIiwib3BlbmlkIjoib010a281RE9QTktQLXVXRDVTZzMwdzlfTzQ3TSIsImlhdCI6MTY5OTg3MDcxNH0.EeUwPzVmzpqAjJo-lOmfh7QMchG0E9I95PwJuzpfvdc"
	// }
	return uni.getStorageSync('userInfo') // 登录成功-返回上述信息，登录失败-返回布尔假
}

export const login = () => {
	uni.login({
		provider: 'weixin',
		success: (loginRes) => {
			// 登录成功，获取用户code
			console.log('用户登录信息', loginRes)
			// return
			const {
				code
			} = loginRes;
			// 发送code到后台换取token
			uni.request({
				url: baseUrl + `/api/wechat/login?code=${code}`, // 你的登录API地址
				method: 'POST',
				success: (res) => {
					console.log('登录成功', res)
					if (res.data && res.data.code === 200) {
						// 将token存储到本地
						uni.setStorageSync('token', res.data.token);
						uni.setStorageSync('openid', res.data.openid);
						setToken(res.data.token)
						// // 获取用户信息
						// uni.getUserInfo({
						// 	provider: 'weixin',
						// 	success: function(infoRes) {
						// 		console.log('用户昵称为：' + infoRes, infoRes.userInfo
						// 			.openId, infoRes.userInfo.nickName,
						// 			infoRes.userInfo.avatarUrl);
						// 	}
						// });
					} else {
						uni.showToast({
							title: '登录失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.log('登录失败', err)
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					});
				}
			});
		},
		fail: (err) => {
			console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err);
			uni.showToast({
				title: '登录失败',
				icon: 'none'
			});
		}
	});

}