<HTML>
<HEAD>
	<TITLE>{siteTitle}</TITLE>
	<meta http-equiv=content-type content="text/html; charset=gb2312">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<LINK href="../CSS/Android.css" type=text/css rel=stylesheet>
    <script type="text/javascript" src="../Offline/common/string.js.php"></script>
    <script type="text/javascript" src="../Offline/script/animation.js"></script>
	<script type="text/javascript" src="../JS/CheckQuestion.js.php"></script>
	<script type="text/javascript" src="../JS/SelRadioCheckBox.js.php"></script>
	<script type="text/javascript" src="../Offline/common/jquery-1.6.2.min.js.php"></script>
	<script type="text/javascript" src="../Offline/common/smart-2.8.min.js.php"></script>
	<SCRIPT type=text/javascript>
	if( rexseeScreen.getScreenHeight() < 500 || rexseeScreen.getScreenWidth() < 500 )
	{
		rexseeScreen.setScreenOrientation('landscape');
		document.write('<LINK href="../Offline/resources/phone.css" type=text/css rel=stylesheet>');
	}
	else
	{
		document.write('<LINK href="../Offline/resources/pad10.css" type=text/css rel=stylesheet>');
	}
	window.onRexseeReady = function(){
			rexseeApplication.setDefaultEncoding('gbk');
			rexseeMenu.setOptionsMenuId("mainOptionsMenu1");
			rexseeTitleBar.setStyle('visibility:hidden;');
			rexseeStatusBar.setStyle('visibility:hidden;');
			
			rexseeSpecialKey.enableBackKeyListener(false);
			//rexseeSpecialKey.enableVolumeKeyListener(false);
			//rexseeBrowserStyle.setStyle('browser-zoom-button:visible;');
			//正在加载信息
			rexseeDialog.toast("正在努力为您加载信息...");
	}
	function checkSelectSurvey()
	{
		var strErr = "操作要求必须先选择一张问卷！";
		objField = document.form.surveyID;
		if( objField.length == null )
		{
			if (objField.checked) return true;
			else
			{
				objField.focus();
				rexseeDialog.toast(strErr);
				return false;
			}
		}
		else
		{
			for (i=0;i<objField.length;i++){
				if (objField[i].checked) return true;
			}
			objField[0].focus();
			rexseeDialog.toast(strErr);
			return false;
		}
	}
	var theDataStep = 0;
	var theDataTotalStep = 0;
	var theSurveyID = 0;
	var theHomeURL = (rexseeApplication.getHome() == '' ) ? rexseeApplication.getDeveloperHome() : rexseeApplication.getHome();
	var remoteServer = str_replace('Offline/default.html','',theHomeURL);
	var surveyRow = '';
	
	var rtnMessage = '';
	var dataList = '';
	var dataRow = '';
	var dataIndex = [];
	var uploadFilePath = [];

	function uploadSurveyAction()
	{
		if ( !checkSelectSurvey()) {return false;}
		if ( window.confirm('您确定需要自本地上行问卷的回复数据，注意上行数据可能将花费较长时间，并上行成功后本地的数据将会被全部删除？!'))
		{
			rexseeChronometer.show('label:正在努力为您上行问卷数据，可能需要花费较长时间...;align:left;background-color:transparent;color:#000000;border-width:0;window-style:light;',1800,'javascript:document.getElementById("uploadBtn").disabled = true;');

			theSurveyID = getRadioCheckBoxValue(document.form.surveyID);

			document.getElementById("infocontent").innerHTML = "&nbsp;<img src=\"..\/Images\/wait.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=green><b>正在准备上行您选择的本地问卷的回复数据</b></font>&nbsp;";
			document.getElementById('uploadBtn').disabled = true;

			var sql = " SELECT fields,isRecord,uploadlist,surveyTitle,fields,isUploadRec FROM eq_survey_list WHERE surveyID ='"+theSurveyID+"'; ";
			surveyRow = eval('('+getDbRows(sql,'rexsee:enableq.db')+')');

			//var taskList = getDbRows('SELECT COUNT(*) as recNum FROM eq_task_list WHERE surveyID ="'+theSurveyID+'" LIMIT 1 ','rexsee:enableq.db');
			//var taskRow = eval('('+taskList+')');
			//if( parseInt(taskRow.rows[0][0]) > 0 )  //有任务
			//{
			//	var countRow = eval('('+getDbRows('SELECT count(*) FROM eq_response_'+theSurveyID+' WHERE overFlag = "1";','rexsee:enableq.db')+')');
			//}
			//else
			//{
				var countRow = eval('('+getDbRows('SELECT count(*) FROM eq_response_'+theSurveyID+' ;','rexsee:enableq.db')+')');
			//}
				
			if( count(countRow.rows) == 0 )
			{
				document.getElementById("infocontent").innerHTML = "&nbsp;<img src=\"..\/Images\/check_no.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=red><b>问卷："+surveyRow.rows[0][3]+"尚无数据</b></font>";
			}
			else
			{
				theDataTotalStep = parseInt(countRow.rows[0][0]);
				var theSingleRtn = startUploadTask();
				var rtnArray = theSingleRtn.split('|');
				if( rtnArray[0] == 'true')
				{
					sql = " DELETE FROM eq_abnormal_list WHERE surveyID = '"+theSurveyID+ "'; ";
					rexseeDatabase.exec(sql,'rexsee:enableq.db');

					var theUploadURL = remoteServer+'Offline/UserAction.php';
					var postData = eval('({surveyID: "'+theSurveyID+'", userId: "{userId}",nickName: "{nickName}",actionMess:"上行数据('+theDataTotalStep+'):'+surveyRow.rows[0][3]+'",actionType:2})');
					$.ajaxSetup({async:false});
					$.post(theUploadURL, postData);
					
					document.getElementById("infocontent").innerHTML = "&nbsp;<img src=\"..\/Images\/check_yes.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=green><b>问卷："+surveyRow.rows[0][3]+theDataTotalStep+"条数据全部上行成功</b></font>";
					if( parseInt(surveyRow.rows[0][1]) == 1 && parseInt(surveyRow.rows[0][5]) != 1 )
					{
						$('#uploadStat').append("<img src=\"..\/Images\/check_no.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=red><b>全程录音文件未随数据一并上传</b></font><br/>");
						var theStorageTmpPath = rexseeStorage.getRoot()+'enableq_offline/storage/'+theSurveyID+'/';
						$('#uploadStat').append("<img src=\"..\/Images\/check_yes.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=red><b>全程录音文件本地转存在"+str_replace("file:///mnt/",'',theStorageTmpPath)+"</b></font><br/>");
					}
				}
				else
				{	
					sql = " DELETE FROM eq_abnormal_list WHERE surveyID = '"+theSurveyID+ "'; ";
					rexseeDatabase.exec(sql,'rexsee:enableq.db');
					sql = " INSERT INTO eq_abnormal_list (surveyID,abnormalTypeId,abnormalText) VALUES ('"+theSurveyID+"','"+rtnArray[1]+"','"+str_replace('，无法进行数据上传，请联系系统管理员','',rtnArray[2])+"');";
					rexseeDatabase.exec(sql,'rexsee:enableq.db');

					//异常记录
					document.getElementById("infocontent").innerHTML = "&nbsp;<img src=\"..\/Images\/check_no.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=red><b>问卷："+surveyRow.rows[0][3]+"数据上行出现异常,异常错误:"+rtnArray[2]+"</b></font>";
				}			
			}
			rexseeChronometer.dismiss();
		}
	}

	function startUploadTask()
	{
		if( theDataStep == theDataTotalStep )
		{
			return 'true';
		}
		else
		{
			var taskRtn = startSingleUpLoad();
			var rtnArray = taskRtn.split('|');
			if( rtnArray[0] == 'true' )
			{	
				theDataStep++;
				$('#uploadStat').append("<img src=\"..\/Images\/check_yes.gif\" width=\"16px\" height=\"16px\">&nbsp;<font color=green><b>第"+theDataStep+"条数据上行成功</b></font><br/>");
				return startUploadTask();
			}
			else
			{
				var rtnDataId = theDataStep+1;
				return 'false|'+rtnArray[1]+'|第'+rtnDataId+'条数据:'+rtnArray[2];
			}					
		}
	}
	function startSingleUpLoad()
	{
	    //初始化
		rtnMessage = '';
		dataList = '';
		dataRow = '';
		dataIndex = [];
		uploadFilePath = [];

		var theCheckURL = remoteServer+'Offline/UploadCheckSurvey.php';
		var postData = eval('({surveyID: "'+theSurveyID+'", this_survey_fields: "'+surveyRow.rows[0][4]+'"})');
		$.ajaxSetup({async:false});
		$.post(theCheckURL, postData, 
			function(data) { 
				rtnMessage = data;
		});	
		var rtnArray = rtnMessage.split('|');
		if( rtnArray[0] == 'true' )
		{	
			//数据
			//var taskList = getDbRows('SELECT COUNT(*) as recNum FROM eq_task_list WHERE surveyID ="'+theSurveyID+'" LIMIT 1 ','rexsee:enableq.db');
			//var taskRow = eval('('+taskList+')');
			//if( parseInt(taskRow.rows[0][0]) > 0 )  //有任务
			//{
				//完成数据
			//	dataList = getDbRows('SELECT * FROM eq_response_'+theSurveyID+' WHERE overFlag = "1" ORDER BY responseID ASC LIMIT 1 ','rexsee:enableq.db');
			//}
			//else
			//{
				dataList = getDbRows('SELECT * FROM eq_response_'+theSurveyID+' ORDER BY responseID ASC LIMIT 1 ','rexsee:enableq.db');
			//}
			dataRow = eval('('+dataList+')');
			dataIndex = [];
			for( var tmp in dataRow.columns )
			{
				dataIndex[dataRow.columns[tmp]] = tmp;
			}

			var theFilePath = rexseeStorage.getRoot()+'enableq_offline/files/'+theSurveyID+'/';
			var theUploadURL = remoteServer+'Offline/UploadFileStart.php?surveyID='+theSurveyID;
			if( parseInt(surveyRow.rows[0][1]) == 1 ) //问卷需要全程录音
			{
				var the_rec_file = dataRow.rows[0][dataIndex['recordFile']];
				//if( parseInt(surveyRow.rows[0][5]) == 1 )
				if( parseInt(rtnArray[1]) == 1 ) //上传全程录音
				{
					//发起上传
					if( the_rec_file != '' && rexseeFile.exists(theFilePath+the_rec_file) )
					{	
						uploadFilePath.push(theFilePath+the_rec_file);
						rexseeProfessionalUpload.selectFile(theFilePath+the_rec_file);
						var rtnUploadMess = rexseeProfessionalUpload.syncUpload(theUploadURL+'&optionID=recFile'+'&fileTime='+dataRow.rows[0][dataIndex['joinTime']]+'&fileName='+the_rec_file,'uploadedfile');
						if( rtnUploadMess != '' )
						{
							return 'false|2|上传录音文件出现异常';
						}
					}
				}
				else //转存
				{
					if( the_rec_file != '' && rexseeFile.exists(theFilePath+the_rec_file) )
					{	
						var theStoragePath = rexseeStorage.getRoot()+'enableq_offline/storage/'+theSurveyID+'/';
						if( ! rexseeFile.exists(theStoragePath) )
						{
							rexseeFile.newDir(theStoragePath);
						}
						//修订文件名
						if( the_rec_file.split('.').length == 3 )
						{
							//删除旧的
							if( rexseeFile.exists(theStoragePath+substr(the_rec_file,0,-3) ) )
							{
								rexseeFile.remove(theStoragePath+substr(the_rec_file,0,-3));
							}
							if( !rexseeFile.copyTo(theFilePath+the_rec_file,theStoragePath+substr(the_rec_file,0,-3)) )
							{
								return 'false|2|录音文件本地转存出现异常';
							}
							else
							{
								uploadFilePath.push(theFilePath+the_rec_file);
							}
						}
						else
						{
							//删除旧的
							if( rexseeFile.exists(theStoragePath+the_rec_file) )
							{
								rexseeFile.remove(theStoragePath+the_rec_file);
							}
							if( !rexseeFile.copyTo(theFilePath+the_rec_file,theStoragePath+the_rec_file) )
							{
								return 'false|2|录音文件本地转存出现异常';
							}
							else
							{
								uploadFilePath.push(theFilePath+the_rec_file);
							}
						}
					}
				}				
			}
			//开始上行回复文件
			if( surveyRow.rows[0][2] != '' )
			{
				var the_upload_list = surveyRow.rows[0][2].split(',');
				for( var tmp in the_upload_list )
				{
					var the_upload_file = dataRow.rows[0][dataIndex[the_upload_list[tmp]]];
					if( the_upload_file != '' && rexseeFile.exists(theFilePath+the_upload_file) )
					{
						rexseeProfessionalUpload.selectFile(theFilePath+the_upload_file);
						uploadFilePath.push(theFilePath+the_upload_file);
						var rtnUploadMess = rexseeProfessionalUpload.syncUpload(theUploadURL+'&optionID='+the_upload_list[tmp]+'&fileTime='+dataRow.rows[0][dataIndex['joinTime']]+'&fileName='+the_upload_file,'uploadedfile');
						if( rtnUploadMess != '' )
						{
							return 'false|2|上传问卷附属文件出现异常';
						}
					}
				}
			}
			
			//开始上传数据任务
			var theUploadURL = remoteServer+'Offline/UploadDataStart.php';
			//alert(dataList);
			var postData = eval('({surveyID: "'+theSurveyID+'", datas: "'+base64_encode(dataList)+'",uploadList:"'+surveyRow.rows[0][2]+'",isUploadRec:"'+surveyRow.rows[0][5]+'"})');
			$.ajaxSetup({async:false});
			$.post(theUploadURL, postData, 
				function(data) { 
					rtnMessage = data;
			});	
			if( rtnMessage == 'true' )
			{	
				//删除本地文件
				for (var fileid in uploadFilePath )
				{
					var filePath = uploadFilePath[fileid];
					if( filePath != '' && rexseeFile.exists(filePath) )
					{
						rexseeFile.remove(filePath);
					}
				}
				//删除本数据
				var dsql = ' DELETE FROM eq_response_'+theSurveyID+' WHERE responseID = "'+dataRow.rows[0][dataIndex['responseID']]+'" ';
				rexseeDatabase.exec(dsql,'rexsee:enableq.db');
				//删除任务列表
				if(	typeof dataIndex['taskID'] != 'undefined' )
				{
					if( parseInt(dataRow.rows[0][dataIndex['taskID']]) != 0 )
					{
						var dsql = ' DELETE FROM eq_task_list WHERE taskID = "'+dataRow.rows[0][dataIndex['taskID']]+'" ';
						rexseeDatabase.exec(dsql,'rexsee:enableq.db');
					}
				}
				return 'true';
			}
			else
			{
				return 'false|3|'+rtnMessage;
			}
		}
		else
		{
			return rtnMessage; //返回错误
		}
	}
	function onUploadTimeout(path,timeout)
	{
		alert("上传文件:"+path+"出现超时异常,请通过任务管理器结束该上传进程!");
	}
	window.onException = function(className, message){
		//alert(unescape(message));
		var theLogFilePath = rexseeStorage.getRoot()+'enableq_offline/logs/';
		if( ! rexseeFile.exists(theLogFilePath) )
		{
			rexseeFile.newDir(theLogFilePath);
		}
		var theLogFile = theLogFilePath +'error.txt';
		if( !rexseeFile.exists(theLogFile) )
		{
			rexseeFile.newFile(theLogFile);
		}
		else
		{
			if( rexseeFile.size(theLogFile) > 102400 )
			{
				rexseeFile.remove(theLogFile);
				rexseeFile.newFile(theLogFile);
			}
		}
		var theOriFileContent = rexseeFile.getContent(theLogFile,'GBK');
		rexseeFile.putContent(theLogFile,theOriFileContent+"Error("+date('Y-m-d H:i:s',time())+"):"+className+":"+unescape(message)+"\r\n",'GBK');
	}
	</SCRIPT>
</HEAD>
<body style="background:#e5e5e5;color:#666">

<div class="titlebar">
 <table width=100%>
   <tr><td width=85><a id="rtnURL"><img src="../Images/return.png" width=85 height=30 border=0></a></td>
   <td align=center width=* class="pageTitle">数据上行</td>
   <td width=85><a href="Logout.php"><img src="../Images/lout.png" width=85 height=30 border=0></a></td>
 </table>
</div>

<div class="notesInfo">【说明】欢迎您，{nickName}，请选择需要上行数据的本地问卷。</div>

<div class="invertedshiftdown">
	<ul>
	<li><a href="javascript:animationLoad('DownSurveyList.php');">下载问卷</a></li>
	<li><a href="javascript:animationLoad('DownTaskList.php');">任务下载</a></li>
	<li class="current"><a href="javascript:animationLoad('UploadSurveyData.php');">数据上行</a></li>
	<li><a href="javascript:animationLoad('AbnormalSurveyList.php');">异常处理</a></li>
	<li><a href="javascript:animationLoad('DeleSurveyList.php');">问卷删除</a></li>
	<li><a href="javascript:animationLoad('CheckServerVersion.php');">程序更新</a></li>
	</ul>
</div>

<script id="main_list_tpl" type="text/x-jsmart-tmpl">
<div id="androidList" style="padding-left:10px;padding-right:10px;padding-top:5px;background: #e5e5e5;">
 <form name="form" id="form" method="post">
{foreach $surveys as $i => $survey}
 <table width=100% style="border:#d9d9d9 2px solid;margin-bottom:5px;margin-top:5px;background:#ffffff">
   <tr>
      <td height=70 width=99% valign=center style="border-bottom:#ddd 1px solid"><a href="javascript:void(0);" onclick="javascript:selRadioCheckRows('surveyID',{$survey.theOptionOdNum});"><div class="actiontitle"  style="line-height:30px;padding-top:20px;padding-bottom:20px;border-bottom:none">{$survey.surveyTitle}</div></a></td>
	  <td align=right valign=center width=1% style="border-bottom:#ddd 1px solid"><input type="radio" name="surveyID" id="surveyID" value="{$survey.surveyID}" {$survey.disabled}>&nbsp;</td>
   </tr>
   <tr>
      <td height=40 align=left style="padding-left:20px" class="sysinfo">{$survey.info}</td>
      <td align=right valign=center nowrap>{$survey.beginTime}&nbsp;(<font color=red>{$survey.replyNum}</font>)&nbsp;</td></tr>
 </table>
 {/foreach}
 <table width=100%>
   <tr><td><input type="button" name="uploadBtn" id="uploadBtn" class=btnclass value="开始上行" onclick="javascript:uploadSurveyAction();">&nbsp;&nbsp;<span id="infocontent"></span>
   </td></tr>
   <tr><td><span id="uploadStat"></span></td></tr>
 </table>
 
 </form>
</div>
<div class="pageinfo infoTotal">共计<span class=red>{$survey@total}</span>张问卷</div>
</script>
<script>
	var sql = "CREATE TABLE eq_task_list(taskID int(30) NOT NULL default '0',surveyID int(30) NOT NULL DEFAULT '0',taskName varchar(255) NOT NULL default '',taskDesc varchar(255) NOT NULL default '' );";
	if( ! rexseeDatabase.tableExists('eq_task_list','rexsee:enableq.db') )
	{
		rexseeDatabase.exec(sql,'rexsee:enableq.db');
	}
	var dataCheckRow = eval('('+ getDbRows('SELECT * FROM eq_survey_list WHERE surveyID =0 LIMIT 1','rexsee:enableq.db')+')');
	if( ! in_array('userName',dataCheckRow.columns) )
	{
		sql = " ALTER TABLE eq_survey_list ADD userName varchar(255) NOT NULL default '' ";
		rexseeDatabase.exec(sql,'rexsee:enableq.db');
	}
	dataCheckRow = null;

	//问卷列表
	sql = " SELECT * FROM eq_survey_list WHERE ( userName = '' OR userName ='{nickName}' ) ORDER BY surveyID DESC; ";
	var surveyRow = eval('('+getDbRows(sql,'rexsee:enableq.db')+')');
	var thisTotal = 0;
	if( count(surveyRow.rows) != 0 )
	{
		var datas ="{ surveys:[";
		var theOptionOdNum = 0;
		for( var tmp in surveyRow.rows )
		{
			datas += "{";
			datas += "surveyID:" + surveyRow.rows[tmp][0] +",";
			datas += "surveyTitle:'" + surveyRow.rows[tmp][1] +"',";
			datas += "beginTime:'" + surveyRow.rows[tmp][2]+"',";
			datas += "theOptionOdNum:" + theOptionOdNum +",";
			theOptionOdNum++;
			if( rexseeDatabase.tableExists('eq_response_'+surveyRow.rows[tmp][0],'rexsee:enableq.db') )
			{
				//var taskList = getDbRows('SELECT COUNT(*) as recNum FROM eq_task_list WHERE surveyID ="'+surveyRow.rows[tmp][0]+'" LIMIT 1 ','rexsee:enableq.db');
				//var taskRow = eval('('+taskList+')');
				//if( parseInt(taskRow.rows[0][0]) > 0 )  //有任务
				//{
				//	var datasRow = eval('('+getDbRows('SELECT COUNT(*) as totalResponseNum FROM eq_response_'+surveyRow.rows[tmp][0]+' WHERE overFlag="1"','rexsee:enableq.db')+')');
				//}
				//else
				//{
					var datasRow = eval('('+getDbRows('SELECT COUNT(*) as totalResponseNum FROM eq_response_'+surveyRow.rows[tmp][0],'rexsee:enableq.db')+')');
				//}

				if( count(datasRow.rows) != 0 )
				{
					if( parseInt(datasRow.rows[0][0]) == 0 )
					{
						datas += " info:'<font color=red><b>本地尚无数据，无法上行</b></span>',";
						datas += " disabled:'disabled',";
					}
					else
					{
						thisTotal++;
						var checkRow = eval('('+getDbRows('SELECT COUNT(*) as totalResponseNum FROM eq_abnormal_list WHERE surveyID = '+surveyRow.rows[tmp][0],'rexsee:enableq.db')+')');
						if( count(checkRow.rows) != 0 )
						{
							if( parseInt(checkRow.rows[0][0]) == 0 )
							{
								datas += " info:'<font color=green><b>本地有数据，可上行</b></font>',";
								datas += " disabled:'',";
							}
							else
							{
								datas += " info:'<font color=green><b>上次上行数据出现异常，仍可尝试上行</b></font>',";
								datas += " disabled:'',";
							}
						}
						else
						{
							datas += " info:'<font color=green><b>本地有数据，可上行</b></font>',";
							datas += " disabled:'',";
						}
					}
					datas += " replyNum:'"+datasRow.rows[0][0] +"'";
				}
				else
				{
					datas += " info:'<font color=red><b>本地尚无数据，无法上行</b></span>',";
					datas += " disabled:'disabled',";
					datas += " replyNum:'0'";
				}
			}
			else
			{
				datas += " info:'<font color=red><b>本地无数据，无法上行</b></span>',";
				datas += " disabled:'disabled',";
				datas += " replyNum:'0'";
			}			  
			datas += "},";
		}
		datas = datas.substr(0,datas.length-1)+"] }";
	}
	else
	{
		var datas ="{ surveys:[] }";
	}
	var jsondatas = eval('('+datas+')');				

	var tplText = document.getElementById('main_list_tpl').innerHTML;
	var tpl = new jSmart( tplText );
	var res = tpl.fetch( jsondatas );
    document.write( res );

	if(thisTotal >0 )
	{
		document.getElementById('uploadBtn').disabled = false;
	}
	else
	{
		document.getElementById('uploadBtn').disabled = true;
	}
	$('#rtnURL').attr('href',"javascript:animationLoad('"+rexseeClient.getRoot('bulidClient.xml')+"index.html');");
</script>
<script>scroll(0, 0);</script>
</body>
</html>