var shares = null;
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

//答题卡
function getPaperData(){
	var exampaperNum = $("#exampaperNum").val();
	var rptSource=$("#rptSource").val();
	
	var url = $.getUrl()+"/appIndex!getPaperData.action";
	
	$.newAjax( {
		 url : url,//目标地址
		 data : {
			 exampaperNum:exampaperNum
		 },
		 success : function(data) {
			if(data[3]=='0'){//不开放学生答题卡
				$("#item1Str").html("<div style='padding-top:0.44rem;font-size:26px;text-align:center;'>暂不开放查询</div>");
				return;
			}
			 
		 	var item1Str = "";
		 	var picUrl = data[1];
			var examp=data[2];
		 	if(picUrl == ""){
		 		picUrl = $.getUrl();
		 	}
		 	if(data[0][0].scan_import!='0'){
				item1Str += "<div><img  class='bigImg' src='../../../img/appendStuImg.png' style='width: 100%;height:auto;border: 0px;' data-preview-src='' data-preview-group='0'/></div>";
			}else{
				$.each(data[0],function(i,obj){
					
					item1Str += "<div>"+
								"<img data='3' id='simg"+obj.id+"' class='bigImg' src='"+picUrl+"/imageAction!fetchBigImage.action?regId="+obj.id+"&category="+examp+"' "+
								"questionImagesUrl='"+picUrl+"/imageAction!getBigImageCombineInfoList.action?regId="+obj.id+"&category="+examp+"&rptSource="+rptSource+"' "+
								"onload='imgOnLoad(this,\""+data[4]+"\")' "+
								"style='width: 100%;height:auto;border: 0px;' data-preview-src='' data-preview-group='0'/>"+
								"</div>";
				});
			}
		 	$("#item1Str").html(item1Str);
			$("#item1Str img").each(function(i){
				$(this).error(function(){
					$(this).attr("src","../../../img/imgError.jpg");
					$(this).unbind("error");
				})
			});
			if(isAndroid){
				mui.previewImage();
			}else{
				mui('.mui-content-padded.datika').on('tap', 'img', function() {
					var images = [].slice.call(document.querySelectorAll('.mui-content-padded.datika img'));
					var urls = [];
					images.forEach(function(item) {
					  urls.push(item.src);
					});
				
				  var index = images.indexOf(this);
				  plus.nativeUI.previewImage(urls, {
				    current: index,
				    loop: false,
				    indicator: 'number',
					onLongPress:function(){
						
					}
				  });
				});
			}
		 },
		 error : function(data) {
		 	return false;
		 }
	});
}

//试卷||标准答案-- 原来的
// function getQueOrAnsData(imgdiv,imgtype){
// 	var exampaperNum = $("#exampaperNum").val();
	
// 	var url = $.getUrl()+"/appIndex!getQueOrAnsData.action";
	
// 	$.newAjax( {
// 		 url : url,//目标地址
// 		 data : {
// 			 exampaperNum:exampaperNum,
// 			 imgtype:imgtype
// 		 },
// 		 success : function(data) {
// 			 console.log("84");
// 			 console.log(data);
// 		 	var itemStr = "";
// 		 	var picUrl = data[1];
// 		 	if(picUrl == ""){
// 		 		picUrl = $.getUrl();
// 		 	}
// 		 	$.each(data[0],function(i,obj){
// 		 		itemStr += "<div>"+
// 		 						"<img data='"+imgtype+"' id='pimg"+obj.id+"' class='bigImg' src='"+picUrl+"/imageAction!fetchQuestionOrAnswerBigImg.action?id="+obj.id+"' "+
// 		 						"style='width: 100%;height:auto;border: 0px;' onerror='imgerrorfun();' data-preview-src='' data-preview-group='"+imgtype+"'/>"+
// 		 					"</div>";
// 		 	});
// 			// console.log("itemStr："+itemStr);
// 			if(itemStr!=""){
// 				$("#"+imgdiv).html(itemStr);
// 				if(isAndroid){
// 					mui.previewImage();
// 				}else{
// 					if(imgdiv == "item2Str"){
// 						var images = [].slice.call(document.querySelectorAll('.mui-content-padded.shijuan img'));
// 						var urls = [];
// 						images.forEach(function(item) {
// 						  urls.push(item.src);
// 						});
						
// 						mui('.mui-content-padded.shijuan').on('tap', 'img', function() {
// 						  var index = images.indexOf(this);
// 						  plus.nativeUI.previewImage(urls, {
// 							current: index,
// 							loop: false,
// 							indicator: 'number',
// 							onLongPress:function(){
								
// 							}
// 						  });
// 						});
// 					}else{
// 						var images = [].slice.call(document.querySelectorAll('.mui-content-padded.biaozhun img'));
// 						var urls = [];
// 						images.forEach(function(item) {
// 						  urls.push(item.src);
// 						});
// 						mui('.mui-content-padded.biaozhun').on('tap', 'img', function() {
// 						  var index = images.indexOf(this);
// 						  plus.nativeUI.previewImage(urls, {
// 							current: index,
// 							loop: false,
// 							indicator: 'number',
// 							onLongPress:function(){
								
// 							}
// 						  });
// 						});
// 					}
// 				}
// 			}else{
// 				$("#"+imgdiv).html("<div style='padding-top:0.44rem;font-size:26px;text-align:center;'>未上传</div>");
// 			}
// 		 },
// 		 error : function(data) {
// 		 	return false;
// 		 }
// 	});
// }

//试卷||标准答案-- 组卷后改的
function getQueOrAnsData(imgdiv,imgtype){
	
	var exampaperNum = $("#exampaperNum").val();
	
	var url = $.getUrl()+"/teacherAppSingleSubejct!getQueOrAnsData.action";
	
	$.newAjax( {
		 url : url,//目标地址
		 data : {
			 exampaperNum:exampaperNum,
			 imgtype:imgtype
		 },
		 success : function(data) {
			 if(data!=null&&data.htmlList!=undefined){
				 var itemStr = "";
				 $.each(data.htmlList,function(i,obj){
					itemStr+="<div class='isDiv'>"+(i+1)+"、";
				 	itemStr += obj;
					itemStr +="</div>";
				 });
				
				$("#"+imgdiv).html(itemStr);
				
			 }else{
				 var src="";
				 if(imgtype=='1'){
					src='../../../img/yuantiweiluru.png'; 
				 }else{
					src='../../../img/weiluru.png';
				 }
				 $("#"+imgdiv).html("<img style='width:98%;height:auto;border:1px red solid;margin-left: 1%;' onerror='changeSrc(this)' src='"+src+"'>");
				 	
			 }
			
			console.log("184");
			 // if(isAndroid){
			 // 	mui.previewImage();
			 // }else{
			 // 	if(imgtype=='1'){ //原题
				// 	var images = [].slice.call(document.querySelectorAll('.mui-content-padded.shijuan img'));
				// 	var urls = [];
				// 	images.forEach(function(item) {
				// 	  urls.push(item.src);
				// 	});
				// 	mui('.mui-content-padded.shijuan').on('tap', 'img', function() {
					
				// 	  var index = images.indexOf(this);
				// 	  plus.nativeUI.previewImage(urls, {
				// 	    current: index,
				// 	    loop: false,
				// 	    indicator: 'number',
				// 		onLongPress:function(){
							
				// 		}
				// 	  });
				// 	});
				// }else{ //答案
				// 	var images = [].slice.call(document.querySelectorAll('.mui-content-padded.biaozhun img'));
				// 	var urls = [];
				// 	images.forEach(function(item) {
				// 	  urls.push(item.src);
				// 	});
				// 	mui('.mui-content-padded.biaozhun').on('tap', 'img', function() {
					
				// 	  var index = images.indexOf(this);
				// 	  plus.nativeUI.previewImage(urls, {
				// 	    current: index,
				// 	    loop: false,
				// 	    indicator: 'number',
				// 		onLongPress:function(){
							
				// 		}
				// 	  });
				// 	});
				// }
			 // }
			 
				// if(isAndroid){
				// 	mui.previewImage();
				// }else{
					if(imgdiv == "item2Str"){
						var images = [].slice.call(document.querySelectorAll('.mui-content-padded.shijuan img'));
						var urls = [];
						console.log(images);
						images.forEach(function(item) {
						  urls.push(item.src);
						});
						
						mui('.mui-content-padded.shijuan').on('tap', 'img', function() {
						  var index = images.indexOf(this);
						  plus.nativeUI.previewImage(urls, {
							current: index,
							loop: false,
							indicator: 'number',
							onLongPress:function(){
								
							}
						  });
						});
					}else{
						var images = [].slice.call(document.querySelectorAll('.mui-content-padded.biaozhun img'));
						var urls = [];
						console.log("252");
						console.log(images);
						images.forEach(function(item) {
						  urls.push(item.src);
						});
						mui('.mui-content-padded.biaozhun').on('tap', 'img', function() {
						  var index = images.indexOf(this);
						  plus.nativeUI.previewImage(urls, {
							current: index,
							loop: false,
							indicator: 'number',
							onLongPress:function(){
								
							}
						  });
						});
					}
				// }
			
		 },
		 error : function(data) {
		 	return false;
		 }
	});
}

function changeSrc(obj){
	obj.src="../../../img/jiazaichaoshi.png"; 
	obj.onerror=null;
}

function imgerrorfun(){
	var img=event.srcElement; 
	img.src="../../../img/noCollect.jpg"; 
	img.onerror=null;
}

//下拉刷新数据
function refreshData(index){
	if(index == 0){
		getPaperData();
	}else if(index == 1){
		getQueOrAnsData("item2Str","1");
	}else if(index == 2){
		getQueOrAnsData("item3Str","2");
	}
	
}

//将图片保存到相册
// 	长按屏幕事件
function saveImg(mui,plus){
	$(".bigImg").on('longtap',function(){
		updateSerivces();
	    var actionList = {buttons:[
				    		{title:"保存图片"},
				    		//{title:"分享给QQ好友",id:"qq"},
				    		{title:"分享给微信好友",id:"weixin",ex:"WXSceneSession"},
				    		{title:"分享到微信朋友圈",id:"weixin",ex:"WXSceneTimeline"},
				    		{title:"取消"},
				    	]};
//	    var idList = [{id: "qq"},{id:"weixin",ex:"WXSceneSession"},{id:"weixin",ex:"WXSceneTimeline"}];
	    var idList = [{id:"weixin",ex:"WXSceneSession"},{id:"weixin",ex:"WXSceneTimeline"}];
	    var imgSrc = this.src;
	    var imgType = this.getAttribute("data");
	    
	    var filename = this.id;
	    
	    //弹出actionSheet选项
	    plus.nativeUI.actionSheet(actionList,function(e){
	        if(e.index==1){//保存图片
				var imgSrc_new = imgSrc;
				if(mui.os.android && imgSrc.indexOf('data:image/')==0){
					imgSrc_new = convertBase64ToUrl($.getUrl(),imgSrc);
				}
	            //创建一个下载任务
	            var imgDtask = plus.downloader.createDownload(imgSrc_new,{method:"GET",filename:"_doc/"+filename+".jpg"},function(d,status){
	                //下载完成的回调函数
	                if (status == 200 ) { 
	                    plus.gallery.save(d.filename,function(){//保存到相册
	                        plus.io.resolveLocalFileSystemURL(d.filename,function(entry){
	                            entry.remove();//删除临时文件
	                        });
	//                      return alert('图片已保存至相册');
							mui.toast('保存成功');
	                    });                     
	                }else{
	                    mui.toast("保存失败!" + status); 
	                }  
	            });
	            imgDtask.start();//开始下载任务
	        }else if(e.index==4){
	        	
	        }else{//分享给QQ好友
				var examNum = $("#examNum").val();
				var imgSrc_new = imgSrc;
				if(imgSrc.indexOf('data:image/')==0){
					imgSrc_new = convertBase64ToUrl($.getUrl(),imgSrc,'1',examNum);
				}
				// var imgSrc_new = convertBase64ToUrl($.getUrl(),imgSrc,'1',examNum);
	        	var i = e.index;
		        shareAction(idList[i - 2].id, idList[i - 2].ex, imgSrc_new, imgType);
	        }
	    });
	});
}

/**
 * 分享操作
 */
function shareAction(id, ex, imgUrl, imgType) {
    var s = null;
    if (!id || !(s = shares[id])) {
        return;
    }
    if (s.authenticated) {
        shareMessage(s, ex, imgUrl, imgType);
    } else {
        s.authorize(function() {
            shareMessage(s, ex, imgUrl, imgType);
        }, function(e) {
        });
    }
}

/**
 * 发送分享消息
 */
function shareMessage(s, ex, imgUrl, imgType) {
//	var schName = plus.storage.getItem("schoolname");
//	var claName = plus.storage.getItem("classname");
	var stuName = plus.storage.getItem("studentname");
	var subjectName = $("#subjectName").val();
	var examName = $("#examName").val();
	var content = stuName+subjectName+"答题卡";
	var title = "考试："+examName;
	if(imgType == 1){//试卷
		content = subjectName+"试卷";
	}else if(imgType == 2){//标准答案
		content = subjectName+"标准答案";
	}
    var msg = {
        content: content,
        href: imgUrl,
        title: title,
        thumbs: ['../../../img/oneSub/sharePic.png'],
        pictures: ['../../../img/oneSub/sharePic.png'],
        extra: {
            scene: ex
        }
    };
    s.send(msg, function() {
    }, function(e) {
    });
}

/**
 * 更新分享服务
 */
function updateSerivces() {
    plus.share.getServices(function(s) {
        shares = {};
        for (var i in s) {
            var t = s[i];
            shares[t.id] = t;
        }
    }, function(e) {
    });
}

function imgOnLoad(img,logType) {
	new DrawCombineImage(img, {
		logType: logType,
		tupianType: 'dtk'
	});
}




