import {
	getStuOpenId,
	getAppID
} from './url.js'

export default {
	getOpenId(callback) {
		uni.showLoading({
			title: '加载中'
		});
		if (uni.getStorageSync('openId')) {
			uni.hideLoading();
			callback();
		} else {
			this.getAppid(callback);
		}

	},
	async getAppid(callback) {
		console.log(callback,'callback');
		let result = await getAppID();
		console.log(result, 'result');
		if (result.code == '200') {
			this.getCode(result.msg,callback);
		} else {
			uni.hideLoading();
		}
	},
	getCode(appid,callback) { // 非静默授权，第一次有弹框
		let local = window.location.href; // 获取页面url
		let code = this.getUrlCode().code; // 截取code
		if (code && code !== '') { // 如果有code
			// 拿到code去请求openId并存在本地 ?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
			this.requestNet(code,callback);
		} else {
			uni.hideLoading();
			// window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
			window.location.href =
				`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
		}
	},
	getUrlCode() { // 截取url中的code方法
		let url = location.search;
		let theRequest = {};
		if (url.indexOf("?") !== -1) {
			let str = url.substr(1);
			let strs = str.split("&");
			for (let i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
			}
		}
		return theRequest
	},
	async requestNet(code, callback) {
		let result = await getStuOpenId({
			jsCode: code
		}, "GET");
		if (data.msg && data.msg !== 'null') {
			// window.localStorage.setItem("openId", result.data.openid);
			uni.setStorageSync('openId', data.msg);
			callback();
			uni.hideLoading();
		} else {
			uni.hideLoading();
		}
	},


}
