var weixin = {
	
	AppId: 'wx6de69d22565ac596',
	
	// 解析页面查询参数
	parseQueryParams(url, decode=true) {
	    var queryString = url.split('?')[1];
	    // console.log('queryString: ' + queryString);
	    if (queryString == undefined)
	        return '';
	
	    if (decode)
	        queryString = Base64.decode(queryString);
	    // console.log(queryString);
	    var params = new URLSearchParams(queryString);
	    return params;
	},
	
	// 获取微信code用于后续服务端获取用户openid
	getWxCode() {
		var code = '';
		var params = this.parseQueryParams(window.location.href, false);
		if (params != '')
			code = params.get('code');
		
		if (code == null || code === '') {
			var redirect_uri = window.location.href;
			redirect_uri = encodeURIComponent(redirect_uri);
			console.log('redirect_uri:' + redirect_uri);
			window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+ this.AppId 
				+ '&redirect_uri=' + redirect_uri
				+ '&response_type=code&scope=snsapi_base&state=1#wechat_redirect';
		} else {
			return code;
		}
	},
	
	initWeixinJSBridge(payParam, successFunc=null, successParam=null, failFunc=null, failParam=null) {
		// 支付只能在微信内置浏览器才有效果,在其他浏览器里面是无效的，进行判断
		if (typeof WeixinJSBridge == "undefined") {
			console.log("请在微信客户端打开");
			alert("请在微信客户端打开");
			if (document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', onBridgeReady(payParam, successFunc, successParam, failFunc, failParam), false);
			} else if (document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', onBridgeReady(payParam, successFunc, successParam, failFunc, failParam));
				document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(payParam, successFunc, successParam, failFunc, failParam));
			}
		} else {
			onBridgeReady(payParam, successFunc, successParam, failFunc, failParam);
		}
	},
	
	// JSAPI调起支付
	onBridgeReady(payParam, successFunc=null, successParam=null, failFunc=null, failParam=null) {
		WeixinJSBridge.invoke(
			"getBrandWCPayRequest",
			{
				appId: payParam.AppId,          //公众号ID，由商户传入
				timeStamp: payParam.TimeStamp,  //时间戳，自1970年以来的秒数
				nonceStr: payParam.NonceStr,    //随机串
				package: payParam.Package,
				signType: payParam.SignType,    //微信签名方式
				paySign: payParam.PaySign       //微信签名
			},
			function (res) {
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					// 使用以上方式判断前端返回,微信团队郑重提示：
					//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
					if (successFunc != null && successFunc != '') {
						if (successParam != null && successParam != '') {
							successFunc(successParam);
						} else {
							successFunc();
						}
					} else {
						alert("支付成功");
					}
				} else {
					if (failFunc != null && failFunc != '') {
						if (failParam != null && failParam != '') {
							failFunc(failParam);
						} else {
							failFunc();
						}
					} else {
						alert("支付取消");
					}
				}
			}
		);
	}
};

export default weixin;