// index.js
let myPro = require("../../../utils/wxRequest.js");
let util = require("../../../utils/util.js");

Page({
    data: {
       
    },
    onLoad: function (options) {
        // Do some initialize when page load.
		let that = this;
    },
    onShow: function () {
        // Do something when page show.
		let that = this;
		// 拿code换openid
		wx.login({
			success: function(res) {
				console.log('获取wxcode',res)
				let params = {
					code: res.code
				};
				myPro.wxRequest("user/mini-auth","POST",params).then(res=>{
					let result = res.result;
					// 有token 是老用户
					if(result.token){
						console.log('token',result.token)
						getApp().globalData.token = result.token;
						// getApp().globalData.openid = result.user.openid;
						wx.setStorage({
							key: "token",
							data: result.token
						});
						getApp().globalData.is_member = result.user.is_member; // 会员 0否 1是
						getApp().globalData.userInfo = {
							nickname: result.user.nickname,
							thumb: result.user.thumb,
							phone: result.user.phone
						};
						if(result.user.store){
							getApp().globalData.role = 1; // 有店铺,即为门店
						};
						// 回跳到首页
						wx.reLaunch({
							url: "/pages/index/index"
						});
						// console.log('用户',getApp().globalData.userInfo)
					}else{
						// 新用户
						getApp().globalData.openid = result.openid;
						getApp().globalData.session_key = result.session_key;
					}
				}).catch(err=>{
					console.log('报错信息',err);
					wx.showToast({
						title: err,
						icon: "none"
					})
				})
			},
			fail: function(res){
				wx.showToast({
					title: "微信未授权成功，请在设置中允许使用用户信息",
					icon: "none"
				});
			}
		})
    },
	// 授权获取用户信息
	getUserProfile(event){
		if(wx.getUserProfile){
			wx.getUserProfile({
				desc: '获取您的昵称、头像、及性别', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				success: (res) => {
					// 存一下用户信息  昵称 头像 性别
					console.log('已授权',res);
					getApp().globalData.userInfo = {
						nickname: res.userInfo.nickName,
						thumb: res.userInfo.avatarUrl,
						sex: res.userInfo.gender
					};
					// console.log('用户信息',getApp().globalData.userInfo)
					// 跳到下一页
					wx.navigateTo({
						url: "/pages/login/wechat/index"
					});
				}
			})
		}else{
			// 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
			wx.showModal({
				title: '提示',
				content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
			});
		}
	},
    onReady: function () {
        // Do something when page ready.
    },
    onHide: function () {
        // Do something when page hide.
    },
    onUnload: function () {
        // Do something when page close.
    },
    onPullDownRefresh: function () {
        // Do something when pull down.
		
    },
    onReachBottom: function () {
        // Do something when page reach bottom.
    },
    onPageScroll: function () {
        // Do something when page scroll
		
    },
    onResize: function () {
        // Do something when page resize
    },
});
