//专属二维码海报截图-数据（包括截图状态和本地文件路径）
var successCBData;
//二维码链接地址
var appCodeUrl = '';
//二维码中间的logo
var appCodeLogo = 'http://51baxue.com/static/img/app/teacher/dmj/head.png';

//分享操作
var shares = {};
var ids = [{
		id: "weixin",
		ex: "WXSceneSession"
	}, {
		id: "weixin",
		ex: "WXSceneTimeline"
	}, {
		id: "baocun"
	}, {
		id: "fuzhi"
	}],
	bts = [{
		title: "分享给微信好友"
	}, {
		title: "分享到朋友圈"
	}, {
		title: "保存到本地"
	}, {
		title: "复制链接"
	}];
	
	function initYouHuiQuan(){
		var systemId = plus.storage.getItem("systemid");
		//查询推荐人
		$.newAjax({
			url: plus.storage.getItem('payUrl') + "/youhuiquan/query/getAppTuijianHaoyouHaiBaoYouhui",
			data: {
				systemId: systemId
			},
			async: false,
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log(XMLHttpRequest.status);
			},
			success: function(d) {
				var money0 = new Big(d[0]);
				if(money0.eq(0)){
					$(".fuli1").hide();
				}else{
					$(".fuli1").show();
					$(".fuli1Jine").text(money0);
				}
				var money1 = new Big(d[1]);
				if(money1.eq(0)){
					$(".fuli2").hide();
				}else{
					$(".fuli2").show();
					$(".fuli2Jine").text(money1);
				}
				var money2 = new Big(d[2]);
				if(money2.eq(0)){
					$(".tuijianfan2").hide();
				}else{
					$(".tuijianfan2").show();
					$(".tuijianfan2Jine").text(money2);
				}
				var money3 = new Big(d[3]);
				if(money3.eq(0)){
					$(".tuijianfan1").hide();
				}else{
					$(".tuijianfan1").show();
					$(".tuijianfan1Jine").text(money3);
				}
			},
		});
	}
	
mui.plusReady(function() {
	$("#systemName").html(plus.storage.getItem("systemName"));
	
	initYouHuiQuan();
	
	//edei地址
	var systemUrl = $.getUrl();
	//推荐人
	var tuijianren = plus.storage.getItem("xuejihao");
	//唤醒链接地址
	//在线调试
	// var huaxingurl = 'hbuilder://html/sf/productAll.html?systemUrl='+systemUrl+'&tuijianren='+tuijianren;
	// var huaxingurl = 'hbuilder://index.html?systemUrl='+systemUrl+'&tuijianren='+tuijianren+"&systemName="+plus.storage.getItem("systemName");
	//打包
	var huaxingurl = 'domegaparentapp://index.html?';
	//二维码链接地址
	// appCodeUrl = 'http://51baxue.com/huanxing/app/student/index.html?huanxingurl='+encodeURIComponent(huaxingurl);
	appCodeUrl = $.getUrl() + '/app/student/appRegister.jsp?tuijianren='+tuijianren+'&huanxingurl='+encodeURIComponent(huaxingurl);
	
	console.log(appCodeUrl)
	// 生成二维码
	$("#appCode").qrcode({
		"render": "table",
		"height": 100,
		"width": 100,
		"colorDark": "#ff0000",
		"colorLight": "#ff00ff",
		"text": appCodeUrl,
		"src": appCodeLogo,
		correctLevel: QRErrorCorrectLevel.L,
	});

	// 截屏图片（IOS需要渲染完页面才能截图）
	setTimeout(function() {
		
		drawScreenToImg();
	}, 1000);

	plus.share.getServices(function(s) {
		if (s && s.length > 0) {
			for (var i = 0; i < s.length; i++) {
				var t = s[i];
				shares[t.id] = t;
			}
		}
	}, function() {
		console.log("获取分享服务列表失败");
	});
});
//分享链接点击事件
mui("body").on("tap", ".share", function() {
	var i = $(this).attr("index");
	if (i == 3) { //保存到本地
		if (successCBData && successCBData['success'] == 'success') {
			var filePath = successCBData['details'];
			saveToGallery(filePath);
		}
	} else if (i == 4) { //复制链接
		copyShareUrl();
	} else if (i == 1 || i == 2) {
		var s_id = ids[i - 1].id;
		var share = shares[s_id];
		if (share.authenticated) {
			shareMessage_img(share, ids[i - 1].ex);
		} else {
			share.authorize(function() {
				shareMessage_img(share, ids[i - 1].ex);
			}, function(e) {
				console.log("认证授权失败：" + e.code + " - " + e.message);
			});
		}
	}
});

// 保存至相册
function saveToGallery(path) {
	// console.log(path)
	plus.gallery.save(path, function(e) {
		console.log(JSON.stringify(e));
		mui.toast('已保存到相册');
	}, function(err) {
		// console.log("保存到相册失败：" + JSON.stringify(err));
		mui.toast('图片保存至相册失败');
	});
}

//分享链接
function shareMessage_url(share, ex) {
	var msg = {
		extra: {
			scene: ex
		}
	};
	msg.href = appCodeUrl; //链接URL
	msg.title = "分享测试标题"; //分享链接的标题
	msg.content = "分享测试内容"; //这是再要内容
	//msg.thumbs是缩略图
	if (successCBData && successCBData['success'] == 'success') {
		var filePath = successCBData['details'];
		msg.thumbs = [filePath];
	}
	share.send(msg, function() {
		console.log("分享到\"" + share.description + "\"成功！ ");
	}, function(e) {
		console.log("分享到\"" + share.description + "\"失败: " + e.code + " - " + e.message);
	});
}

//分享图片
function shareMessage_img(share, ex) {
	if (successCBData && successCBData['success'] == 'success') {
		var filePath = successCBData['details'];
		var msg = {
			content: "海报分享",
			pictures: [filePath],
			extra: {
				scene: ex
			}
		};
		share.send(
			msg,
			function() {
				console.log("分享到\"" + share.description + "\"成功！ ");
			},
			function(e) {
				console.log("分享到\"" + share.description + "\"失败: " + e.code + " - " + e.message);
			}
		);
	}
}

// 实现一键复制链接到手机剪切板的功能
function copyShareUrl() {
	mui.plusReady(function() {
		var copy_content = appCodeUrl;
		console.log(copy_content);
		//判断设备是android还是ios
		if (mui.os.ios) { //ios
			var UIPasteboard = plus.ios.importClass("UIPasteboard");
			var generalPasteboard = UIPasteboard.generalPasteboard();
			//设置/获取文本内容:
			generalPasteboard.plusCallMethod({
				setValue: copy_content,
				forPasteboardType: "public.utf8-plain-text"
			});
			generalPasteboard.plusCallMethod({
				valueForPasteboardType: "public.utf8-plain-text"
			});
			mui.toast("复制链接成功"); //自动消失提示框
		} else { //android
			var context = plus.android.importClass("android.content.Context");
			var main = plus.android.runtimeMainActivity();
			var clip = main.getSystemService(context.CLIPBOARD_SERVICE);
			plus.android.invoke(clip, "setText", copy_content);
			mui.toast("复制链接成功"); //自动消失提示框
		}
	});
}
//屏幕截图
function drawScreenToImg() {
	var topDiv = document.getElementsByClassName('topDiv')[0];
	var descWidth = topDiv.clientWidth;
	var descHeight = topDiv.clientHeight;
	var descTop = topDiv.getBoundingClientRect().top;
	var descLeft = topDiv.getBoundingClientRect().left;
	if (mui.os.android) {
		descWidth += descLeft;
		descHeight += descTop;
	}

	var options = {
		// 文件名如果使用时间戳，每次都会生成一个新的图片，会不会占用手机内存？？？
		// fileName: 'studentAppYaoQingImg',
		// imgID: 'studentAppYaoQingImg',
		successCB: function(e) { //截图返回本地路径
			successCBData = e;
			// console.log(JSON.stringify(e));
		},
		errorCB: function(e) { //截图失败
			successCBData = e;
			console.log(JSON.stringify(e));
		},
		quality: 100, //截图清晰度 0~100，默认50
		clip: { //截图区域
			top: descTop,
			left: descLeft,
			width: descWidth,
			height: descHeight
		}
	}
	// console.log("descTop:"+descTop);
	// console.log("descLeft:"+descLeft);
	// console.log("descWidth:"+descWidth);
	// console.log("descHeight:"+descHeight);

	drawScreen(options);
}