<script>
	const config = require('./static/config.js');
	
	export default {
		onLaunch: function() {
			let href = location.href;
			let code  = this.getQueryString('code');
			/**
			 * 解题思路,由于不可抗因素，导致必须想办法，现有如下想法
			 * （一）如是不带code，则为自然进入，给他用微信加code；
			 * （二）如果带了code，则有可能是分享（非图片分享）或者复制链接进来的
			 *    bug: 如果之前去掉code，则会进入（一）进入了死循环;
			 *    想法：先去让他带着code去regist，成功则说明是新的code，失败则去掉code进入（一）
			 */
			if(!code){
				let url =  href.split('#')[0];
				url = encodeURIComponent(url);
				url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+config.appid+"&redirect_uri="+url+"&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect"
				window.location.replace(url);
			}
			this.globalData.BASE_URL = config.BASE_URL;
			let shareToken  = this.getQueryString('shareToken');
			let projectId  = this.getQueryString('projectId');
			this.globalData.projectId = projectId||'';
			this.globalData.shareToken = shareToken||'';
			this.regist();
			this.signJsapiTicket();
		},
		onShow: function() {
			document.body.style.setProperty("background-color",this.globalData.color4);
		},
		onHide: function() {

		},
		methods: {
			getThemeInfo() {
			
			},
			getQueryString(name){
				var reg = new RegExp("(^|\\?|&)"+ name +"=([^&]*)(\\s|&|$)", "i");
				return reg.test(location.href) ? unescape(RegExp.$2.replace(/\+/g, " ")) : ""
			},
			async regist() {
				let code  = this.getQueryString('code'); 
				if(code){
					let ret = await this.$myRequest({
						url: "/regist",
						data: {
							"code": code,
							"shareToken":this.globalData.shareToken||"",
							"projectId":this.globalData.projectId||"",
						}
					});
					if (ret.data.success) {
						let userId = ret.data.single.userId;
						this.globalData.userId = userId;
						if (ret.data.single.authed == 1) {
							let token = ret.data.single.token;
							this.globalData.token = token
						}
						uni.$emit('request')
					}else{
						//注册失败，去掉老的code，会进入onLaunch，重新获取新的code
						let projectId  = this.getQueryString('projectId'); 
						let shareToken  = this.getQueryString('shareToken'); 
						let url = location.origin+location.pathname + "?projectId="+projectId+"&shareToken="+shareToken;
						window.location.replace(url);
					}
				}
			},
			async signJsapiTicket(){
				const wx = require('weixin-js-sdk');
				let url =  location.href.split('#')[0]
				let parmas = {
					url: url,
				}
				let self = this;
				let res = await this.$myRequest({
					url: '/wechat/signJsapiTicket',
					data: parmas,
					method:"GET",
				});
				if(res.data.success){
				   let single =	res.data.single;
				   wx.config({
				   	debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				   	appId: config.appid, // 必填，公众号的唯一标识
				   	timestamp: single.timestamp, // 必填，生成签名的时间戳
				   	nonceStr: single.nonceStr, // 必填，生成签名的随机串
				   	signature: single.signature, // 必填，签名
				       jsApiList: ["updateAppMessageShareData","updateTimelineShareData",'showMenuItems','hideMenuItems'] // 必填，需要使用的JS接口列表
				   });
				   wx.ready(function() {
				   	
				   });
				   wx.error(function(res) {
				   	// config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
				   });
				   
				   wx.hideMenuItems({
				     menuList: ['menuItem:share:qq','menuItem:share:QZone','menuItem:favorite','menuItem:originPage','menuItem:copyUrl','menuItem:openWithSafari','menuItem:openWithQQBrowser'] // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
				   });
				}
			},
		},
		globalData: {
			token: "",
			userId:"",
			projectId:"",
			shareToken:"",
			pathName:"",
			color1: "#F07423",
			color2: "#FD8F3C",
			color3: "#FFC444",
			color4: "#F5F5F7",
			color5: "#F7A98E",
			color6: "#FFF4EB",
			color7:"#F8BA91",
			color8:"#FFF4EB",
			color9:"#8B654D",
			color10:"#FCF6F1",
			contentColor:"#B1B1B1",
			titleColor:"#262626",
			BASE_URL:"https://dm-api.elab-plus.cn",//默认环境
		}
	}
</script>

<style>
	
</style>
