<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.href = 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();
		},
		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.href = url;
					}
				}
			},
		},
		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",
			BASE_URL:"https://dm-api.elab-plus.cn",//默认环境
		}
	}
</script>

<style>
	
</style>