<script>
	let util = require('@/utils/utils.js');
	var registerFlag = true;
	let crypto = require("crypto");
	export default {
		globalData:{
		    userInfo: {},
		    shopInfo: {
		        shop_name: "数字茶城",
		        desc: "数字茶城"
		    },
		    kfCode: '',
			
			ShopUrl: 'https://shop.haocha13.cn/ShuZiTeaYW/',
			SignUrl: 'https://shop.haocha13.cn/ShuZiTeaIntegral/',
			SpecUrl: 'https://shop.haocha13.cn/ShuZiTeaSpecial/',
			groupUrl:'https://shop.haocha13.cn/ShuZiTeaSpell/', // 团购测试url  tea

			// ShopUrl: 'https://tea.soowin.com/ShuZiTeaYW/',
			// SignUrl: 'https://tea.soowin.com/ShuZiTeaIntegral/',
			// SpecUrl: 'https://tea.soowin.com/ShuZiTeaSpecial/',
			// groupUrl:'https://tea.soowin.com/ShuZiTeaSpell/', // 团购测试url  tea

			// ShopUrl: 'http://192.168.31.176:8080/ShuZiTeaYW/',
			// SignUrl: 'http://192.168.31.176:8080/ShuZiTeaIntegral/',
			// SpecUrl: 'http://192.168.31.176:8080/ShuZiTeaSpecial/',
			// groupUrl:'http://192.168.31.176:8080/ShuZiTeaSpell/', // 团购测试url  tea

		    openId: '',
		    agentId: 1, //推荐人ID
		    interfaceheader: {
		        "Content-Type": "application/x-www-form-urlencoded"
		    },
		    authorizeWindow: true, //是否可以打开用户信息授权页面，避免重复打开
		    bindPhoneWindow: true, //是否可以打开绑定手机号码页面，避免重复打开
		    hasUpdate: false, // 小程序是否有更新版本 默认为没有
		    newVersionInfo: {
		        num: "1.0.0",
		        desc: "数字茶城上线啦！",
		        updateInfo: [] // 数组形式描述一下具体更新了什么内容
		    }, // 当前小程序最新版本信息
		    msgTmp: null ,//订阅消息模板id信息
			systemUserInfo:''
		},
		//检测缓存中是否有当前用户信息
		authorizeUserInfo: function (callback, isHome) {
			var that=this
		    if (this.globalData.systemUserInfo=='') {
		        uni.getStorage({
		            key: 'systemUserInfo',
		            success(res) {
		                that.globalData.systemUserInfo = res.data;
		                if (callback) {
		                    callback(res.data.userId);
		                }
		            },
		            fail() {
						that.login(callback, isHome);
		            }
		        })
		    } else {
		        if (callback) {
		            callback(this.globalData.systemUserInfo.userId);
		        }
		    }
		},
		login: function(callback, isHome) {
		    var that = this;
		    uni.showLoading({
				icon: 'loading',
				mask: true
			});
			uni.login({
				provider: 'weixin',
				success: function (res) {
					if (res.code) {
						// console.log(res.code)
						//查询当前用户openId并返回是否已注册
						uni.request({
							//获取openID
							url: that.globalData.ShopUrl + 'login/openid',
							method: 'POST',
							header: that.globalData.interfaceheader,
							data: {
								code: res.code
							},
							success: function (res) {
								uni.hideLoading();
								if (res.data.status == '200' || res.data.status == '300') {
									that.globalData.openId = res.data.openid;
									//用户已存在
									if (res.data.userInfo && res.data.userInfo != ''){
										that.globalData.systemUserInfo = res.data.userInfo;
										uni.setStorage({
											key: 'systemUserInfo',
											data: res.data.userInfo
										})
										if (callback) {
											callback(res.data.userInfo.userId);
										}
									}else{
										//如果不是首页
										if (!isHome){
											//用户不存在
											if(res.data.status == '300'){
												let is=1
												that.sendauthorizeUserInfo(is,callback);
											}else{
												let is=1
												that.sendauthorizeUserInfo(is,callback);
											}
										}else{
											callback();
										}
									}
								} else {
									console.log("登录" + res.data.status);
									that.errTips(res.data.msg || "");
								}
							}
						})
					} else {
						uni.hideLoading();
						that.errTips("登录失败，请稍后重试。");
					}
				},
				fail: (err) => {
					console.log(err)
				}
			})
		},
		setAppData:function(id,data){
			this.globalData.systemUserInfo=data
			this.globalData.openId=id
		},
		//发起userInfo授权
		sendauthorizeUserInfo: function(is,callback) {
		    var that = this;
		    //检测当前微信版本是否兼容wx.getUserInfo
		    if (uni.getSetting) {
		        uni.getSetting({
		            success(res) {
		                if (res.authSetting['scope.userInfo']) {
							if(is==1){
								that.setData(callback);
							}else if(is==2){
								that.setUnionid(callback)
							}
		                } else {
		                    if (that.globalData.authorizeWindow) {
		                        uni.navigateTo({
		                            url: "/pages/authorize/index"
		                        })
								
								that.globalData.authorizeWindow = false;
		                    }
		                }
		            },
		            fail(res) {
		                uni.showModal({
		                    content: "登录失败，请稍后重试。",
		                    showCancel: false
		                });
		            }
		        })
		    } else {
		        // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样提示
		        that.checkEdition();
		        return;
		    }
		},
		//微信版本太旧提示
		checkEdition: function() {
		    uni.showModal({
		        title: '微信版本太旧',
		        content: '使用旧版本微信，将无法登录、使用一些功能。请至 微信 -> 设置 或其他可信渠道更新微信。',
		        showCancel: false,
		        confirmColor: "#f02f2f",
		        confirmText: "好",
		    })
		},
		//发起userInfo授权
		sendauthorizeUserInfo: function(is,callback) {
		    var that = this;
		    //检测当前微信版本是否兼容wx.getUserInfo
		    if (uni.getSetting) {
		        uni.getSetting({
		            success(res) {
		                if (res.authSetting['scope.userInfo']) {
							if(is==1){
								that.setData(callback);
							}else if(is==2){
								that.setUnionid(callback)
							}
		                } else {
		                    if (that.globalData.authorizeWindow) {
		                        uni.navigateTo({
		                            url: "/pages/authorize/index"
		                        })
								
								that.globalData.authorizeWindow = false;
		                    }
		                }
		            },
		            fail(res) {
		                uni.showModal({
		                    content: "登录失败，请稍后重试。",
		                    showCancel: false
		                });
		            }
		        })
		    } else {
		        // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样提示
		        that.checkEdition();
		        return;
		    }
		},
		// 获取data
		setData(callback){
		    var that = this;
		    // 如果改为unionid注册时以下代码加上注释
		    uni.getUserProfile({
		        desc: '获取用户注册信息',
		    	lang:'zh_CN',
		        success: function (res) {
		            var userinfo = {
		                nickname: res.userInfo.nickName ? util.emoji_utf16toEntities(res.userInfo.nickName) : '',
		                headimgurl: res.userInfo.avatarUrl || '',
		                sex: res.userInfo.gender == 2 ? '女' : '男',
		                city: res.userInfo.city || '',
		                province: res.userInfo.province || '',
		                country: res.userInfo.country || ''
		            };
					console.log(userinfo,"aaaaaaaaa")
					return
		            that.globalData.systemUserInfo = userinfo;
		            var data = {
		                agentId: that.globalData.agentId,
		                openid: that.globalData.openId,
		                ...userinfo
		            };
		    		let isdata=1
		            that.setUnionidApi(data,isdata, callback);
		        },
		        fail: function (res) {
		            console.log(res);
		        }
		    })
		},
		setUnionid:function(callback){
			var that=this
			// 如果改为unionid注册时以下代码去掉注释
			uni.login({
			    success: function (obj) {
			        if (obj.code) {
			            uni.getUserInfo({
			                withCredentials: true,
			                success: function (res) {
			                    var data = {
			                        agentId: that.globalData.agentId,
			                        code: obj.code,
			                        encryptedData: res.encryptedData,
			                        iv: res.iv
			                    };
			                    let isUnionid=2
			                    that.setUnionidApi(data,isUnionid, callback);
			                },
			                fail: function (res) {
			                    console.log("unionid授权失败：" + res);
			                }
			            })
			        }else{
			            console.log("unionid登录code获取失败：" + obj);
			        }
			    },
			    fail: function (obj) {
			        console.log("unionid登录code获取失败：" + obj);
			    }
			})
		},
		setUnionidApi(data = this.parameter("data"),is, callback){
		    var that = this;
			if(is==1){
				uni.request({
				    url: this.globalData.ShopUrl + 'login/data', // 如果改为unionid注册时改回'login/addUnionid'接口
				    method: 'POST',
				    header: this.globalData.interfaceheader,
				    data: data,
				    success: function (res) {
				        if (res.data.status == 200) { //登录成功
				            var userInfo = that.globalData.systemUserInfo;
				            userInfo = res.data.userInfo;
				            that.globalData.systemUserInfo = userInfo;
				            uni.setStorage({
				                key: 'systemUserInfo',
				                data: userInfo
				            })
				            if (callback) {
				                callback(userInfo.userId);
				            }
				        } else {
				            uni.hideLoading();
				            console.log(res.data.msg || "保存信息接口失败");
				        }
				    }
				})
			}else if(is==2){
				uni.request({
				    url: this.globalData.miniShopUrl + 'login/addUnionid', 
				    method: 'POST',
				    header: this.globalData.interfaceheader,
				    data: data,
				    success: function (res) {
				        if (res.data.status == 200) { //登录成功
				            var userInfo = that.globalData.systemUserInfo;
				            userInfo = res.data.userInfo;
				            that.globalData.systemUserInfo = userInfo;
				            // var userinfo = res.data.userInfo;
				            // that.globalData.systemUserInfo = userinfo;
				            uni.setStorage({
				                key: 'systemUserInfo',
				                data: userInfo
				            })
				            if (callback) {
				                callback(userInfo.userId);
				            }
				        } else {
				            uni.hideLoading();
				            console.log(res.data.msg||"保存unionid接口失败");
				            // console.log(res.data.msg || "保存信息接口失败");
				        }
				    }
				})
			}
		},
		errTips(msg, duration, open){
		    uni.showToast({
		        title: msg,
		        icon:'none',
		        duration: duration ? duration : 1200,
		        mask: true
		    })
		},
		// 接口未传递有效参数值的错误提示
		parameter(authName) {
		    throw new Error("'" + authName + "' cat\'t be empty!");
		},
		onLaunch: function() {
			var logs = uni.getStorageSync('logs') || []
			logs.unshift(Date.now())
			uni.setStorageSync('logs', logs);
			uni.setStorageSync('mallName', "数字茶城");
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		}
	}
</script>

<style>
	/*每个页面公共css */
	@import "./app.scss";
</style>
